core.py 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159
  1. #
  2. # core.py
  3. #
  4. from collections import deque
  5. import os
  6. import typing
  7. from typing import (
  8. Any,
  9. Callable,
  10. Generator,
  11. List,
  12. NamedTuple,
  13. Sequence,
  14. Set,
  15. TextIO,
  16. Tuple,
  17. Union,
  18. cast,
  19. )
  20. from abc import ABC, abstractmethod
  21. from enum import Enum
  22. import string
  23. import copy
  24. import warnings
  25. import re
  26. import sys
  27. from collections.abc import Iterable
  28. import traceback
  29. import types
  30. from operator import itemgetter
  31. from functools import wraps
  32. from threading import RLock
  33. from pathlib import Path
  34. from .util import (
  35. _FifoCache,
  36. _UnboundedCache,
  37. __config_flags,
  38. _collapse_string_to_ranges,
  39. _escape_regex_range_chars,
  40. _bslash,
  41. _flatten,
  42. LRUMemo as _LRUMemo,
  43. UnboundedMemo as _UnboundedMemo,
  44. replaced_by_pep8,
  45. )
  46. from .exceptions import *
  47. from .actions import *
  48. from .results import ParseResults, _ParseResultsWithOffset
  49. from .unicode import pyparsing_unicode
  50. _MAX_INT = sys.maxsize
  51. str_type: Tuple[type, ...] = (str, bytes)
  52. #
  53. # Copyright (c) 2003-2022 Paul T. McGuire
  54. #
  55. # Permission is hereby granted, free of charge, to any person obtaining
  56. # a copy of this software and associated documentation files (the
  57. # "Software"), to deal in the Software without restriction, including
  58. # without limitation the rights to use, copy, modify, merge, publish,
  59. # distribute, sublicense, and/or sell copies of the Software, and to
  60. # permit persons to whom the Software is furnished to do so, subject to
  61. # the following conditions:
  62. #
  63. # The above copyright notice and this permission notice shall be
  64. # included in all copies or substantial portions of the Software.
  65. #
  66. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  67. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  68. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  69. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  70. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  71. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  72. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  73. #
  74. if sys.version_info >= (3, 8):
  75. from functools import cached_property
  76. else:
  77. class cached_property:
  78. def __init__(self, func):
  79. self._func = func
  80. def __get__(self, instance, owner=None):
  81. ret = instance.__dict__[self._func.__name__] = self._func(instance)
  82. return ret
  83. class __compat__(__config_flags):
  84. """
  85. A cross-version compatibility configuration for pyparsing features that will be
  86. released in a future version. By setting values in this configuration to True,
  87. those features can be enabled in prior versions for compatibility development
  88. and testing.
  89. - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping
  90. of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;
  91. maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1
  92. behavior
  93. """
  94. _type_desc = "compatibility"
  95. collect_all_And_tokens = True
  96. _all_names = [__ for __ in locals() if not __.startswith("_")]
  97. _fixed_names = """
  98. collect_all_And_tokens
  99. """.split()
  100. class __diag__(__config_flags):
  101. _type_desc = "diagnostic"
  102. warn_multiple_tokens_in_named_alternation = False
  103. warn_ungrouped_named_tokens_in_collection = False
  104. warn_name_set_on_empty_Forward = False
  105. warn_on_parse_using_empty_Forward = False
  106. warn_on_assignment_to_Forward = False
  107. warn_on_multiple_string_args_to_oneof = False
  108. warn_on_match_first_with_lshift_operator = False
  109. enable_debug_on_named_expressions = False
  110. _all_names = [__ for __ in locals() if not __.startswith("_")]
  111. _warning_names = [name for name in _all_names if name.startswith("warn")]
  112. _debug_names = [name for name in _all_names if name.startswith("enable_debug")]
  113. @classmethod
  114. def enable_all_warnings(cls) -> None:
  115. for name in cls._warning_names:
  116. cls.enable(name)
  117. class Diagnostics(Enum):
  118. """
  119. Diagnostic configuration (all default to disabled)
  120. - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results
  121. name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions
  122. - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results
  123. name is defined on a containing expression with ungrouped subexpressions that also
  124. have results names
  125. - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined
  126. with a results name, but has no contents defined
  127. - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is
  128. defined in a grammar but has never had an expression attached to it
  129. - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined
  130. but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``
  131. - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is
  132. incorrectly called with multiple str arguments
  133. - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent
  134. calls to :class:`ParserElement.set_name`
  135. Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.
  136. All warnings can be enabled by calling :class:`enable_all_warnings`.
  137. """
  138. warn_multiple_tokens_in_named_alternation = 0
  139. warn_ungrouped_named_tokens_in_collection = 1
  140. warn_name_set_on_empty_Forward = 2
  141. warn_on_parse_using_empty_Forward = 3
  142. warn_on_assignment_to_Forward = 4
  143. warn_on_multiple_string_args_to_oneof = 5
  144. warn_on_match_first_with_lshift_operator = 6
  145. enable_debug_on_named_expressions = 7
  146. def enable_diag(diag_enum: Diagnostics) -> None:
  147. """
  148. Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).
  149. """
  150. __diag__.enable(diag_enum.name)
  151. def disable_diag(diag_enum: Diagnostics) -> None:
  152. """
  153. Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`).
  154. """
  155. __diag__.disable(diag_enum.name)
  156. def enable_all_warnings() -> None:
  157. """
  158. Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).
  159. """
  160. __diag__.enable_all_warnings()
  161. # hide abstract class
  162. del __config_flags
  163. def _should_enable_warnings(
  164. cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str]
  165. ) -> bool:
  166. enable = bool(warn_env_var)
  167. for warn_opt in cmd_line_warn_options:
  168. w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split(
  169. ":"
  170. )[:5]
  171. if not w_action.lower().startswith("i") and (
  172. not (w_message or w_category or w_module) or w_module == "pyparsing"
  173. ):
  174. enable = True
  175. elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""):
  176. enable = False
  177. return enable
  178. if _should_enable_warnings(
  179. sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS")
  180. ):
  181. enable_all_warnings()
  182. # build list of single arg builtins, that can be used as parse actions
  183. _single_arg_builtins = {
  184. sum,
  185. len,
  186. sorted,
  187. reversed,
  188. list,
  189. tuple,
  190. set,
  191. any,
  192. all,
  193. min,
  194. max,
  195. }
  196. _generatorType = types.GeneratorType
  197. ParseImplReturnType = Tuple[int, Any]
  198. PostParseReturnType = Union[ParseResults, Sequence[ParseResults]]
  199. ParseAction = Union[
  200. Callable[[], Any],
  201. Callable[[ParseResults], Any],
  202. Callable[[int, ParseResults], Any],
  203. Callable[[str, int, ParseResults], Any],
  204. ]
  205. ParseCondition = Union[
  206. Callable[[], bool],
  207. Callable[[ParseResults], bool],
  208. Callable[[int, ParseResults], bool],
  209. Callable[[str, int, ParseResults], bool],
  210. ]
  211. ParseFailAction = Callable[[str, int, "ParserElement", Exception], None]
  212. DebugStartAction = Callable[[str, int, "ParserElement", bool], None]
  213. DebugSuccessAction = Callable[
  214. [str, int, int, "ParserElement", ParseResults, bool], None
  215. ]
  216. DebugExceptionAction = Callable[[str, int, "ParserElement", Exception, bool], None]
  217. alphas = string.ascii_uppercase + string.ascii_lowercase
  218. identchars = pyparsing_unicode.Latin1.identchars
  219. identbodychars = pyparsing_unicode.Latin1.identbodychars
  220. nums = "0123456789"
  221. hexnums = nums + "ABCDEFabcdef"
  222. alphanums = alphas + nums
  223. printables = "".join([c for c in string.printable if c not in string.whitespace])
  224. _trim_arity_call_line: traceback.StackSummary = None # type: ignore[assignment]
  225. def _trim_arity(func, max_limit=3):
  226. """decorator to trim function calls to match the arity of the target"""
  227. global _trim_arity_call_line
  228. if func in _single_arg_builtins:
  229. return lambda s, l, t: func(t)
  230. limit = 0
  231. found_arity = False
  232. # synthesize what would be returned by traceback.extract_stack at the call to
  233. # user's parse action 'func', so that we don't incur call penalty at parse time
  234. # fmt: off
  235. LINE_DIFF = 7
  236. # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND
  237. # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
  238. _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])
  239. pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)
  240. def wrapper(*args):
  241. nonlocal found_arity, limit
  242. while 1:
  243. try:
  244. ret = func(*args[limit:])
  245. found_arity = True
  246. return ret
  247. except TypeError as te:
  248. # re-raise TypeErrors if they did not come from our arity testing
  249. if found_arity:
  250. raise
  251. else:
  252. tb = te.__traceback__
  253. frames = traceback.extract_tb(tb, limit=2)
  254. frame_summary = frames[-1]
  255. trim_arity_type_error = (
  256. [frame_summary[:2]][-1][:2] == pa_call_line_synth
  257. )
  258. del tb
  259. if trim_arity_type_error:
  260. if limit < max_limit:
  261. limit += 1
  262. continue
  263. raise
  264. # fmt: on
  265. # copy func name to wrapper for sensible debug output
  266. # (can't use functools.wraps, since that messes with function signature)
  267. func_name = getattr(func, "__name__", getattr(func, "__class__").__name__)
  268. wrapper.__name__ = func_name
  269. wrapper.__doc__ = func.__doc__
  270. return wrapper
  271. def condition_as_parse_action(
  272. fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False
  273. ) -> ParseAction:
  274. """
  275. Function to convert a simple predicate function that returns ``True`` or ``False``
  276. into a parse action. Can be used in places when a parse action is required
  277. and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition
  278. to an operator level in :class:`infix_notation`).
  279. Optional keyword arguments:
  280. - ``message`` - define a custom message to be used in the raised exception
  281. - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately;
  282. otherwise will raise :class:`ParseException`
  283. """
  284. msg = message if message is not None else "failed user-defined condition"
  285. exc_type = ParseFatalException if fatal else ParseException
  286. fn = _trim_arity(fn)
  287. @wraps(fn)
  288. def pa(s, l, t):
  289. if not bool(fn(s, l, t)):
  290. raise exc_type(s, l, msg)
  291. return pa
  292. def _default_start_debug_action(
  293. instring: str, loc: int, expr: "ParserElement", cache_hit: bool = False
  294. ):
  295. cache_hit_str = "*" if cache_hit else ""
  296. print(
  297. (
  298. f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n"
  299. f" {line(loc, instring)}\n"
  300. f" {' ' * (col(loc, instring) - 1)}^"
  301. )
  302. )
  303. def _default_success_debug_action(
  304. instring: str,
  305. startloc: int,
  306. endloc: int,
  307. expr: "ParserElement",
  308. toks: ParseResults,
  309. cache_hit: bool = False,
  310. ):
  311. cache_hit_str = "*" if cache_hit else ""
  312. print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}")
  313. def _default_exception_debug_action(
  314. instring: str,
  315. loc: int,
  316. expr: "ParserElement",
  317. exc: Exception,
  318. cache_hit: bool = False,
  319. ):
  320. cache_hit_str = "*" if cache_hit else ""
  321. print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}")
  322. def null_debug_action(*args):
  323. """'Do-nothing' debug action, to suppress debugging output during parsing."""
  324. class ParserElement(ABC):
  325. """Abstract base level parser element class."""
  326. DEFAULT_WHITE_CHARS: str = " \n\t\r"
  327. verbose_stacktrace: bool = False
  328. _literalStringClass: type = None # type: ignore[assignment]
  329. @staticmethod
  330. def set_default_whitespace_chars(chars: str) -> None:
  331. r"""
  332. Overrides the default whitespace chars
  333. Example::
  334. # default whitespace chars are space, <TAB> and newline
  335. Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
  336. # change to just treat newline as significant
  337. ParserElement.set_default_whitespace_chars(" \t")
  338. Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def']
  339. """
  340. ParserElement.DEFAULT_WHITE_CHARS = chars
  341. # update whitespace all parse expressions defined in this module
  342. for expr in _builtin_exprs:
  343. if expr.copyDefaultWhiteChars:
  344. expr.whiteChars = set(chars)
  345. @staticmethod
  346. def inline_literals_using(cls: type) -> None:
  347. """
  348. Set class to be used for inclusion of string literals into a parser.
  349. Example::
  350. # default literal class used is Literal
  351. integer = Word(nums)
  352. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  353. date_str.parse_string("1999/12/31") # -> ['1999', '/', '12', '/', '31']
  354. # change to Suppress
  355. ParserElement.inline_literals_using(Suppress)
  356. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  357. date_str.parse_string("1999/12/31") # -> ['1999', '12', '31']
  358. """
  359. ParserElement._literalStringClass = cls
  360. @classmethod
  361. def using_each(cls, seq, **class_kwargs):
  362. """
  363. Yields a sequence of class(obj, **class_kwargs) for obj in seq.
  364. Example::
  365. LPAR, RPAR, LBRACE, RBRACE, SEMI = Suppress.using_each("(){};")
  366. """
  367. yield from (cls(obj, **class_kwargs) for obj in seq)
  368. class DebugActions(NamedTuple):
  369. debug_try: typing.Optional[DebugStartAction]
  370. debug_match: typing.Optional[DebugSuccessAction]
  371. debug_fail: typing.Optional[DebugExceptionAction]
  372. def __init__(self, savelist: bool = False):
  373. self.parseAction: List[ParseAction] = list()
  374. self.failAction: typing.Optional[ParseFailAction] = None
  375. self.customName: str = None # type: ignore[assignment]
  376. self._defaultName: typing.Optional[str] = None
  377. self.resultsName: str = None # type: ignore[assignment]
  378. self.saveAsList = savelist
  379. self.skipWhitespace = True
  380. self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)
  381. self.copyDefaultWhiteChars = True
  382. # used when checking for left-recursion
  383. self.mayReturnEmpty = False
  384. self.keepTabs = False
  385. self.ignoreExprs: List["ParserElement"] = list()
  386. self.debug = False
  387. self.streamlined = False
  388. # optimize exception handling for subclasses that don't advance parse index
  389. self.mayIndexError = True
  390. self.errmsg = ""
  391. # mark results names as modal (report only last) or cumulative (list all)
  392. self.modalResults = True
  393. # custom debug actions
  394. self.debugActions = self.DebugActions(None, None, None)
  395. # avoid redundant calls to preParse
  396. self.callPreparse = True
  397. self.callDuringTry = False
  398. self.suppress_warnings_: List[Diagnostics] = []
  399. def suppress_warning(self, warning_type: Diagnostics) -> "ParserElement":
  400. """
  401. Suppress warnings emitted for a particular diagnostic on this expression.
  402. Example::
  403. base = pp.Forward()
  404. base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)
  405. # statement would normally raise a warning, but is now suppressed
  406. print(base.parse_string("x"))
  407. """
  408. self.suppress_warnings_.append(warning_type)
  409. return self
  410. def visit_all(self):
  411. """General-purpose method to yield all expressions and sub-expressions
  412. in a grammar. Typically just for internal use.
  413. """
  414. to_visit = deque([self])
  415. seen = set()
  416. while to_visit:
  417. cur = to_visit.popleft()
  418. # guard against looping forever through recursive grammars
  419. if cur in seen:
  420. continue
  421. seen.add(cur)
  422. to_visit.extend(cur.recurse())
  423. yield cur
  424. def copy(self) -> "ParserElement":
  425. """
  426. Make a copy of this :class:`ParserElement`. Useful for defining
  427. different parse actions for the same parsing pattern, using copies of
  428. the original parse element.
  429. Example::
  430. integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
  431. integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress("K")
  432. integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
  433. print((integerK | integerM | integer)[1, ...].parse_string("5K 100 640K 256M"))
  434. prints::
  435. [5120, 100, 655360, 268435456]
  436. Equivalent form of ``expr.copy()`` is just ``expr()``::
  437. integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
  438. """
  439. cpy = copy.copy(self)
  440. cpy.parseAction = self.parseAction[:]
  441. cpy.ignoreExprs = self.ignoreExprs[:]
  442. if self.copyDefaultWhiteChars:
  443. cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)
  444. return cpy
  445. def set_results_name(
  446. self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False
  447. ) -> "ParserElement":
  448. """
  449. Define name for referencing matching tokens as a nested attribute
  450. of the returned parse results.
  451. Normally, results names are assigned as you would assign keys in a dict:
  452. any existing value is overwritten by later values. If it is necessary to
  453. keep all values captured for a particular results name, call ``set_results_name``
  454. with ``list_all_matches`` = True.
  455. NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;
  456. this is so that the client can define a basic element, such as an
  457. integer, and reference it in multiple places with different names.
  458. You can also set results names using the abbreviated syntax,
  459. ``expr("name")`` in place of ``expr.set_results_name("name")``
  460. - see :class:`__call__`. If ``list_all_matches`` is required, use
  461. ``expr("name*")``.
  462. Example::
  463. date_str = (integer.set_results_name("year") + '/'
  464. + integer.set_results_name("month") + '/'
  465. + integer.set_results_name("day"))
  466. # equivalent form:
  467. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  468. """
  469. listAllMatches = listAllMatches or list_all_matches
  470. return self._setResultsName(name, listAllMatches)
  471. def _setResultsName(self, name, listAllMatches=False):
  472. if name is None:
  473. return self
  474. newself = self.copy()
  475. if name.endswith("*"):
  476. name = name[:-1]
  477. listAllMatches = True
  478. newself.resultsName = name
  479. newself.modalResults = not listAllMatches
  480. return newself
  481. def set_break(self, break_flag: bool = True) -> "ParserElement":
  482. """
  483. Method to invoke the Python pdb debugger when this element is
  484. about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to
  485. disable.
  486. """
  487. if break_flag:
  488. _parseMethod = self._parse
  489. def breaker(instring, loc, doActions=True, callPreParse=True):
  490. import pdb
  491. # this call to pdb.set_trace() is intentional, not a checkin error
  492. pdb.set_trace()
  493. return _parseMethod(instring, loc, doActions, callPreParse)
  494. breaker._originalParseMethod = _parseMethod # type: ignore [attr-defined]
  495. self._parse = breaker # type: ignore [assignment]
  496. else:
  497. if hasattr(self._parse, "_originalParseMethod"):
  498. self._parse = self._parse._originalParseMethod # type: ignore [attr-defined, assignment]
  499. return self
  500. def set_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
  501. """
  502. Define one or more actions to perform when successfully matching parse element definition.
  503. Parse actions can be called to perform data conversions, do extra validation,
  504. update external data structures, or enhance or replace the parsed tokens.
  505. Each parse action ``fn`` is a callable method with 0-3 arguments, called as
  506. ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
  507. - ``s`` = the original string being parsed (see note below)
  508. - ``loc`` = the location of the matching substring
  509. - ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object
  510. The parsed tokens are passed to the parse action as ParseResults. They can be
  511. modified in place using list-style append, extend, and pop operations to update
  512. the parsed list elements; and with dictionary-style item set and del operations
  513. to add, update, or remove any named results. If the tokens are modified in place,
  514. it is not necessary to return them with a return statement.
  515. Parse actions can also completely replace the given tokens, with another ``ParseResults``
  516. object, or with some entirely different object (common for parse actions that perform data
  517. conversions). A convenient way to build a new parse result is to define the values
  518. using a dict, and then create the return value using :class:`ParseResults.from_dict`.
  519. If None is passed as the ``fn`` parse action, all previously added parse actions for this
  520. expression are cleared.
  521. Optional keyword arguments:
  522. - ``call_during_try`` = (default= ``False``) indicate if parse action should be run during
  523. lookaheads and alternate testing. For parse actions that have side effects, it is
  524. important to only call the parse action once it is determined that it is being
  525. called as part of a successful parse. For parse actions that perform additional
  526. validation, then call_during_try should be passed as True, so that the validation
  527. code is included in the preliminary "try" parses.
  528. Note: the default parsing behavior is to expand tabs in the input string
  529. before starting the parsing process. See :class:`parse_string` for more
  530. information on parsing strings containing ``<TAB>`` s, and suggested
  531. methods to maintain a consistent view of the parsed string, the parse
  532. location, and line and column positions within the parsed string.
  533. Example::
  534. # parse dates in the form YYYY/MM/DD
  535. # use parse action to convert toks from str to int at parse time
  536. def convert_to_int(toks):
  537. return int(toks[0])
  538. # use a parse action to verify that the date is a valid date
  539. def is_valid_date(instring, loc, toks):
  540. from datetime import date
  541. year, month, day = toks[::2]
  542. try:
  543. date(year, month, day)
  544. except ValueError:
  545. raise ParseException(instring, loc, "invalid date given")
  546. integer = Word(nums)
  547. date_str = integer + '/' + integer + '/' + integer
  548. # add parse actions
  549. integer.set_parse_action(convert_to_int)
  550. date_str.set_parse_action(is_valid_date)
  551. # note that integer fields are now ints, not strings
  552. date_str.run_tests('''
  553. # successful parse - note that integer fields were converted to ints
  554. 1999/12/31
  555. # fail - invalid date
  556. 1999/13/31
  557. ''')
  558. """
  559. if list(fns) == [None]:
  560. self.parseAction = []
  561. else:
  562. if not all(callable(fn) for fn in fns):
  563. raise TypeError("parse actions must be callable")
  564. self.parseAction = [_trim_arity(fn) for fn in fns]
  565. self.callDuringTry = kwargs.get(
  566. "call_during_try", kwargs.get("callDuringTry", False)
  567. )
  568. return self
  569. def add_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
  570. """
  571. Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.
  572. See examples in :class:`copy`.
  573. """
  574. self.parseAction += [_trim_arity(fn) for fn in fns]
  575. self.callDuringTry = self.callDuringTry or kwargs.get(
  576. "call_during_try", kwargs.get("callDuringTry", False)
  577. )
  578. return self
  579. def add_condition(self, *fns: ParseCondition, **kwargs) -> "ParserElement":
  580. """Add a boolean predicate function to expression's list of parse actions. See
  581. :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,
  582. functions passed to ``add_condition`` need to return boolean success/fail of the condition.
  583. Optional keyword arguments:
  584. - ``message`` = define a custom message to be used in the raised exception
  585. - ``fatal`` = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise
  586. ParseException
  587. - ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls,
  588. default=False
  589. Example::
  590. integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
  591. year_int = integer.copy()
  592. year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
  593. date_str = year_int + '/' + integer + '/' + integer
  594. result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0),
  595. (line:1, col:1)
  596. """
  597. for fn in fns:
  598. self.parseAction.append(
  599. condition_as_parse_action(
  600. fn,
  601. message=str(kwargs.get("message")),
  602. fatal=bool(kwargs.get("fatal", False)),
  603. )
  604. )
  605. self.callDuringTry = self.callDuringTry or kwargs.get(
  606. "call_during_try", kwargs.get("callDuringTry", False)
  607. )
  608. return self
  609. def set_fail_action(self, fn: ParseFailAction) -> "ParserElement":
  610. """
  611. Define action to perform if parsing fails at this expression.
  612. Fail acton fn is a callable function that takes the arguments
  613. ``fn(s, loc, expr, err)`` where:
  614. - ``s`` = string being parsed
  615. - ``loc`` = location where expression match was attempted and failed
  616. - ``expr`` = the parse expression that failed
  617. - ``err`` = the exception thrown
  618. The function returns no value. It may throw :class:`ParseFatalException`
  619. if it is desired to stop parsing immediately."""
  620. self.failAction = fn
  621. return self
  622. def _skipIgnorables(self, instring: str, loc: int) -> int:
  623. if not self.ignoreExprs:
  624. return loc
  625. exprsFound = True
  626. ignore_expr_fns = [e._parse for e in self.ignoreExprs]
  627. last_loc = loc
  628. while exprsFound:
  629. exprsFound = False
  630. for ignore_fn in ignore_expr_fns:
  631. try:
  632. while 1:
  633. loc, dummy = ignore_fn(instring, loc)
  634. exprsFound = True
  635. except ParseException:
  636. pass
  637. # check if all ignore exprs matched but didn't actually advance the parse location
  638. if loc == last_loc:
  639. break
  640. last_loc = loc
  641. return loc
  642. def preParse(self, instring: str, loc: int) -> int:
  643. if self.ignoreExprs:
  644. loc = self._skipIgnorables(instring, loc)
  645. if self.skipWhitespace:
  646. instrlen = len(instring)
  647. white_chars = self.whiteChars
  648. while loc < instrlen and instring[loc] in white_chars:
  649. loc += 1
  650. return loc
  651. def parseImpl(self, instring, loc, doActions=True):
  652. return loc, []
  653. def postParse(self, instring, loc, tokenlist):
  654. return tokenlist
  655. # @profile
  656. def _parseNoCache(
  657. self, instring, loc, doActions=True, callPreParse=True
  658. ) -> Tuple[int, ParseResults]:
  659. TRY, MATCH, FAIL = 0, 1, 2
  660. debugging = self.debug # and doActions)
  661. len_instring = len(instring)
  662. if debugging or self.failAction:
  663. # print("Match {} at loc {}({}, {})".format(self, loc, lineno(loc, instring), col(loc, instring)))
  664. try:
  665. if callPreParse and self.callPreparse:
  666. pre_loc = self.preParse(instring, loc)
  667. else:
  668. pre_loc = loc
  669. tokens_start = pre_loc
  670. if self.debugActions.debug_try:
  671. self.debugActions.debug_try(instring, tokens_start, self, False)
  672. if self.mayIndexError or pre_loc >= len_instring:
  673. try:
  674. loc, tokens = self.parseImpl(instring, pre_loc, doActions)
  675. except IndexError:
  676. raise ParseException(instring, len_instring, self.errmsg, self)
  677. else:
  678. loc, tokens = self.parseImpl(instring, pre_loc, doActions)
  679. except Exception as err:
  680. # print("Exception raised:", err)
  681. if self.debugActions.debug_fail:
  682. self.debugActions.debug_fail(
  683. instring, tokens_start, self, err, False
  684. )
  685. if self.failAction:
  686. self.failAction(instring, tokens_start, self, err)
  687. raise
  688. else:
  689. if callPreParse and self.callPreparse:
  690. pre_loc = self.preParse(instring, loc)
  691. else:
  692. pre_loc = loc
  693. tokens_start = pre_loc
  694. if self.mayIndexError or pre_loc >= len_instring:
  695. try:
  696. loc, tokens = self.parseImpl(instring, pre_loc, doActions)
  697. except IndexError:
  698. raise ParseException(instring, len_instring, self.errmsg, self)
  699. else:
  700. loc, tokens = self.parseImpl(instring, pre_loc, doActions)
  701. tokens = self.postParse(instring, loc, tokens)
  702. ret_tokens = ParseResults(
  703. tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults
  704. )
  705. if self.parseAction and (doActions or self.callDuringTry):
  706. if debugging:
  707. try:
  708. for fn in self.parseAction:
  709. try:
  710. tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type]
  711. except IndexError as parse_action_exc:
  712. exc = ParseException("exception raised in parse action")
  713. raise exc from parse_action_exc
  714. if tokens is not None and tokens is not ret_tokens:
  715. ret_tokens = ParseResults(
  716. tokens,
  717. self.resultsName,
  718. asList=self.saveAsList
  719. and isinstance(tokens, (ParseResults, list)),
  720. modal=self.modalResults,
  721. )
  722. except Exception as err:
  723. # print "Exception raised in user parse action:", err
  724. if self.debugActions.debug_fail:
  725. self.debugActions.debug_fail(
  726. instring, tokens_start, self, err, False
  727. )
  728. raise
  729. else:
  730. for fn in self.parseAction:
  731. try:
  732. tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type]
  733. except IndexError as parse_action_exc:
  734. exc = ParseException("exception raised in parse action")
  735. raise exc from parse_action_exc
  736. if tokens is not None and tokens is not ret_tokens:
  737. ret_tokens = ParseResults(
  738. tokens,
  739. self.resultsName,
  740. asList=self.saveAsList
  741. and isinstance(tokens, (ParseResults, list)),
  742. modal=self.modalResults,
  743. )
  744. if debugging:
  745. # print("Matched", self, "->", ret_tokens.as_list())
  746. if self.debugActions.debug_match:
  747. self.debugActions.debug_match(
  748. instring, tokens_start, loc, self, ret_tokens, False
  749. )
  750. return loc, ret_tokens
  751. def try_parse(
  752. self,
  753. instring: str,
  754. loc: int,
  755. *,
  756. raise_fatal: bool = False,
  757. do_actions: bool = False,
  758. ) -> int:
  759. try:
  760. return self._parse(instring, loc, doActions=do_actions)[0]
  761. except ParseFatalException:
  762. if raise_fatal:
  763. raise
  764. raise ParseException(instring, loc, self.errmsg, self)
  765. def can_parse_next(self, instring: str, loc: int, do_actions: bool = False) -> bool:
  766. try:
  767. self.try_parse(instring, loc, do_actions=do_actions)
  768. except (ParseException, IndexError):
  769. return False
  770. else:
  771. return True
  772. # cache for left-recursion in Forward references
  773. recursion_lock = RLock()
  774. recursion_memos: typing.Dict[
  775. Tuple[int, "Forward", bool], Tuple[int, Union[ParseResults, Exception]]
  776. ] = {}
  777. class _CacheType(dict):
  778. """
  779. class to help type checking
  780. """
  781. not_in_cache: bool
  782. def get(self, *args):
  783. ...
  784. def set(self, *args):
  785. ...
  786. # argument cache for optimizing repeated calls when backtracking through recursive expressions
  787. packrat_cache = (
  788. _CacheType()
  789. ) # set later by enable_packrat(); this is here so that reset_cache() doesn't fail
  790. packrat_cache_lock = RLock()
  791. packrat_cache_stats = [0, 0]
  792. # this method gets repeatedly called during backtracking with the same arguments -
  793. # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
  794. def _parseCache(
  795. self, instring, loc, doActions=True, callPreParse=True
  796. ) -> Tuple[int, ParseResults]:
  797. HIT, MISS = 0, 1
  798. TRY, MATCH, FAIL = 0, 1, 2
  799. lookup = (self, instring, loc, callPreParse, doActions)
  800. with ParserElement.packrat_cache_lock:
  801. cache = ParserElement.packrat_cache
  802. value = cache.get(lookup)
  803. if value is cache.not_in_cache:
  804. ParserElement.packrat_cache_stats[MISS] += 1
  805. try:
  806. value = self._parseNoCache(instring, loc, doActions, callPreParse)
  807. except ParseBaseException as pe:
  808. # cache a copy of the exception, without the traceback
  809. cache.set(lookup, pe.__class__(*pe.args))
  810. raise
  811. else:
  812. cache.set(lookup, (value[0], value[1].copy(), loc))
  813. return value
  814. else:
  815. ParserElement.packrat_cache_stats[HIT] += 1
  816. if self.debug and self.debugActions.debug_try:
  817. try:
  818. self.debugActions.debug_try(instring, loc, self, cache_hit=True) # type: ignore [call-arg]
  819. except TypeError:
  820. pass
  821. if isinstance(value, Exception):
  822. if self.debug and self.debugActions.debug_fail:
  823. try:
  824. self.debugActions.debug_fail(
  825. instring, loc, self, value, cache_hit=True # type: ignore [call-arg]
  826. )
  827. except TypeError:
  828. pass
  829. raise value
  830. value = cast(Tuple[int, ParseResults, int], value)
  831. loc_, result, endloc = value[0], value[1].copy(), value[2]
  832. if self.debug and self.debugActions.debug_match:
  833. try:
  834. self.debugActions.debug_match(
  835. instring, loc_, endloc, self, result, cache_hit=True # type: ignore [call-arg]
  836. )
  837. except TypeError:
  838. pass
  839. return loc_, result
  840. _parse = _parseNoCache
  841. @staticmethod
  842. def reset_cache() -> None:
  843. ParserElement.packrat_cache.clear()
  844. ParserElement.packrat_cache_stats[:] = [0] * len(
  845. ParserElement.packrat_cache_stats
  846. )
  847. ParserElement.recursion_memos.clear()
  848. _packratEnabled = False
  849. _left_recursion_enabled = False
  850. @staticmethod
  851. def disable_memoization() -> None:
  852. """
  853. Disables active Packrat or Left Recursion parsing and their memoization
  854. This method also works if neither Packrat nor Left Recursion are enabled.
  855. This makes it safe to call before activating Packrat nor Left Recursion
  856. to clear any previous settings.
  857. """
  858. ParserElement.reset_cache()
  859. ParserElement._left_recursion_enabled = False
  860. ParserElement._packratEnabled = False
  861. ParserElement._parse = ParserElement._parseNoCache
  862. @staticmethod
  863. def enable_left_recursion(
  864. cache_size_limit: typing.Optional[int] = None, *, force=False
  865. ) -> None:
  866. """
  867. Enables "bounded recursion" parsing, which allows for both direct and indirect
  868. left-recursion. During parsing, left-recursive :class:`Forward` elements are
  869. repeatedly matched with a fixed recursion depth that is gradually increased
  870. until finding the longest match.
  871. Example::
  872. import pyparsing as pp
  873. pp.ParserElement.enable_left_recursion()
  874. E = pp.Forward("E")
  875. num = pp.Word(pp.nums)
  876. # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...
  877. E <<= E + '+' - num | num
  878. print(E.parse_string("1+2+3"))
  879. Recursion search naturally memoizes matches of ``Forward`` elements and may
  880. thus skip reevaluation of parse actions during backtracking. This may break
  881. programs with parse actions which rely on strict ordering of side-effects.
  882. Parameters:
  883. - ``cache_size_limit`` - (default=``None``) - memoize at most this many
  884. ``Forward`` elements during matching; if ``None`` (the default),
  885. memoize all ``Forward`` elements.
  886. Bounded Recursion parsing works similar but not identical to Packrat parsing,
  887. thus the two cannot be used together. Use ``force=True`` to disable any
  888. previous, conflicting settings.
  889. """
  890. if force:
  891. ParserElement.disable_memoization()
  892. elif ParserElement._packratEnabled:
  893. raise RuntimeError("Packrat and Bounded Recursion are not compatible")
  894. if cache_size_limit is None:
  895. ParserElement.recursion_memos = _UnboundedMemo() # type: ignore[assignment]
  896. elif cache_size_limit > 0:
  897. ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit) # type: ignore[assignment]
  898. else:
  899. raise NotImplementedError("Memo size of %s" % cache_size_limit)
  900. ParserElement._left_recursion_enabled = True
  901. @staticmethod
  902. def enable_packrat(
  903. cache_size_limit: Union[int, None] = 128, *, force: bool = False
  904. ) -> None:
  905. """
  906. Enables "packrat" parsing, which adds memoizing to the parsing logic.
  907. Repeated parse attempts at the same string location (which happens
  908. often in many complex grammars) can immediately return a cached value,
  909. instead of re-executing parsing/validating code. Memoizing is done of
  910. both valid results and parsing exceptions.
  911. Parameters:
  912. - ``cache_size_limit`` - (default= ``128``) - if an integer value is provided
  913. will limit the size of the packrat cache; if None is passed, then
  914. the cache size will be unbounded; if 0 is passed, the cache will
  915. be effectively disabled.
  916. This speedup may break existing programs that use parse actions that
  917. have side-effects. For this reason, packrat parsing is disabled when
  918. you first import pyparsing. To activate the packrat feature, your
  919. program must call the class method :class:`ParserElement.enable_packrat`.
  920. For best results, call ``enable_packrat()`` immediately after
  921. importing pyparsing.
  922. Example::
  923. import pyparsing
  924. pyparsing.ParserElement.enable_packrat()
  925. Packrat parsing works similar but not identical to Bounded Recursion parsing,
  926. thus the two cannot be used together. Use ``force=True`` to disable any
  927. previous, conflicting settings.
  928. """
  929. if force:
  930. ParserElement.disable_memoization()
  931. elif ParserElement._left_recursion_enabled:
  932. raise RuntimeError("Packrat and Bounded Recursion are not compatible")
  933. if not ParserElement._packratEnabled:
  934. ParserElement._packratEnabled = True
  935. if cache_size_limit is None:
  936. ParserElement.packrat_cache = _UnboundedCache()
  937. else:
  938. ParserElement.packrat_cache = _FifoCache(cache_size_limit) # type: ignore[assignment]
  939. ParserElement._parse = ParserElement._parseCache
  940. def parse_string(
  941. self, instring: str, parse_all: bool = False, *, parseAll: bool = False
  942. ) -> ParseResults:
  943. """
  944. Parse a string with respect to the parser definition. This function is intended as the primary interface to the
  945. client code.
  946. :param instring: The input string to be parsed.
  947. :param parse_all: If set, the entire input string must match the grammar.
  948. :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.
  949. :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.
  950. :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or
  951. an object with attributes if the given parser includes results names.
  952. If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This
  953. is also equivalent to ending the grammar with :class:`StringEnd`\\ ().
  954. To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are
  955. converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string
  956. contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string
  957. being parsed, one can ensure a consistent view of the input string by doing one of the following:
  958. - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),
  959. - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the
  960. parse action's ``s`` argument, or
  961. - explicitly expand the tabs in your input string before calling ``parse_string``.
  962. Examples:
  963. By default, partial matches are OK.
  964. >>> res = Word('a').parse_string('aaaaabaaa')
  965. >>> print(res)
  966. ['aaaaa']
  967. The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children
  968. directly to see more examples.
  969. It raises an exception if parse_all flag is set and instring does not match the whole grammar.
  970. >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)
  971. Traceback (most recent call last):
  972. ...
  973. pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6)
  974. """
  975. parseAll = parse_all or parseAll
  976. ParserElement.reset_cache()
  977. if not self.streamlined:
  978. self.streamline()
  979. for e in self.ignoreExprs:
  980. e.streamline()
  981. if not self.keepTabs:
  982. instring = instring.expandtabs()
  983. try:
  984. loc, tokens = self._parse(instring, 0)
  985. if parseAll:
  986. loc = self.preParse(instring, loc)
  987. se = Empty() + StringEnd()
  988. se._parse(instring, loc)
  989. except ParseBaseException as exc:
  990. if ParserElement.verbose_stacktrace:
  991. raise
  992. else:
  993. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  994. raise exc.with_traceback(None)
  995. else:
  996. return tokens
  997. def scan_string(
  998. self,
  999. instring: str,
  1000. max_matches: int = _MAX_INT,
  1001. overlap: bool = False,
  1002. *,
  1003. debug: bool = False,
  1004. maxMatches: int = _MAX_INT,
  1005. ) -> Generator[Tuple[ParseResults, int, int], None, None]:
  1006. """
  1007. Scan the input string for expression matches. Each match will return the
  1008. matching tokens, start location, and end location. May be called with optional
  1009. ``max_matches`` argument, to clip scanning after 'n' matches are found. If
  1010. ``overlap`` is specified, then overlapping matches will be reported.
  1011. Note that the start and end locations are reported relative to the string
  1012. being parsed. See :class:`parse_string` for more information on parsing
  1013. strings with embedded tabs.
  1014. Example::
  1015. source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
  1016. print(source)
  1017. for tokens, start, end in Word(alphas).scan_string(source):
  1018. print(' '*start + '^'*(end-start))
  1019. print(' '*start + tokens[0])
  1020. prints::
  1021. sldjf123lsdjjkf345sldkjf879lkjsfd987
  1022. ^^^^^
  1023. sldjf
  1024. ^^^^^^^
  1025. lsdjjkf
  1026. ^^^^^^
  1027. sldkjf
  1028. ^^^^^^
  1029. lkjsfd
  1030. """
  1031. maxMatches = min(maxMatches, max_matches)
  1032. if not self.streamlined:
  1033. self.streamline()
  1034. for e in self.ignoreExprs:
  1035. e.streamline()
  1036. if not self.keepTabs:
  1037. instring = str(instring).expandtabs()
  1038. instrlen = len(instring)
  1039. loc = 0
  1040. preparseFn = self.preParse
  1041. parseFn = self._parse
  1042. ParserElement.resetCache()
  1043. matches = 0
  1044. try:
  1045. while loc <= instrlen and matches < maxMatches:
  1046. try:
  1047. preloc: int = preparseFn(instring, loc)
  1048. nextLoc: int
  1049. tokens: ParseResults
  1050. nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)
  1051. except ParseException:
  1052. loc = preloc + 1
  1053. else:
  1054. if nextLoc > loc:
  1055. matches += 1
  1056. if debug:
  1057. print(
  1058. {
  1059. "tokens": tokens.asList(),
  1060. "start": preloc,
  1061. "end": nextLoc,
  1062. }
  1063. )
  1064. yield tokens, preloc, nextLoc
  1065. if overlap:
  1066. nextloc = preparseFn(instring, loc)
  1067. if nextloc > loc:
  1068. loc = nextLoc
  1069. else:
  1070. loc += 1
  1071. else:
  1072. loc = nextLoc
  1073. else:
  1074. loc = preloc + 1
  1075. except ParseBaseException as exc:
  1076. if ParserElement.verbose_stacktrace:
  1077. raise
  1078. else:
  1079. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1080. raise exc.with_traceback(None)
  1081. def transform_string(self, instring: str, *, debug: bool = False) -> str:
  1082. """
  1083. Extension to :class:`scan_string`, to modify matching text with modified tokens that may
  1084. be returned from a parse action. To use ``transform_string``, define a grammar and
  1085. attach a parse action to it that modifies the returned token list.
  1086. Invoking ``transform_string()`` on a target string will then scan for matches,
  1087. and replace the matched text patterns according to the logic in the parse
  1088. action. ``transform_string()`` returns the resulting transformed string.
  1089. Example::
  1090. wd = Word(alphas)
  1091. wd.set_parse_action(lambda toks: toks[0].title())
  1092. print(wd.transform_string("now is the winter of our discontent made glorious summer by this sun of york."))
  1093. prints::
  1094. Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
  1095. """
  1096. out: List[str] = []
  1097. lastE = 0
  1098. # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
  1099. # keep string locs straight between transform_string and scan_string
  1100. self.keepTabs = True
  1101. try:
  1102. for t, s, e in self.scan_string(instring, debug=debug):
  1103. out.append(instring[lastE:s])
  1104. if t:
  1105. if isinstance(t, ParseResults):
  1106. out += t.as_list()
  1107. elif isinstance(t, Iterable) and not isinstance(t, str_type):
  1108. out.extend(t)
  1109. else:
  1110. out.append(t)
  1111. lastE = e
  1112. out.append(instring[lastE:])
  1113. out = [o for o in out if o]
  1114. return "".join([str(s) for s in _flatten(out)])
  1115. except ParseBaseException as exc:
  1116. if ParserElement.verbose_stacktrace:
  1117. raise
  1118. else:
  1119. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1120. raise exc.with_traceback(None)
  1121. def search_string(
  1122. self,
  1123. instring: str,
  1124. max_matches: int = _MAX_INT,
  1125. *,
  1126. debug: bool = False,
  1127. maxMatches: int = _MAX_INT,
  1128. ) -> ParseResults:
  1129. """
  1130. Another extension to :class:`scan_string`, simplifying the access to the tokens found
  1131. to match the given parse expression. May be called with optional
  1132. ``max_matches`` argument, to clip searching after 'n' matches are found.
  1133. Example::
  1134. # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
  1135. cap_word = Word(alphas.upper(), alphas.lower())
  1136. print(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity"))
  1137. # the sum() builtin can be used to merge results into a single ParseResults object
  1138. print(sum(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity")))
  1139. prints::
  1140. [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
  1141. ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
  1142. """
  1143. maxMatches = min(maxMatches, max_matches)
  1144. try:
  1145. return ParseResults(
  1146. [t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]
  1147. )
  1148. except ParseBaseException as exc:
  1149. if ParserElement.verbose_stacktrace:
  1150. raise
  1151. else:
  1152. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1153. raise exc.with_traceback(None)
  1154. def split(
  1155. self,
  1156. instring: str,
  1157. maxsplit: int = _MAX_INT,
  1158. include_separators: bool = False,
  1159. *,
  1160. includeSeparators=False,
  1161. ) -> Generator[str, None, None]:
  1162. """
  1163. Generator method to split a string using the given expression as a separator.
  1164. May be called with optional ``maxsplit`` argument, to limit the number of splits;
  1165. and the optional ``include_separators`` argument (default= ``False``), if the separating
  1166. matching text should be included in the split results.
  1167. Example::
  1168. punc = one_of(list(".,;:/-!?"))
  1169. print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
  1170. prints::
  1171. ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
  1172. """
  1173. includeSeparators = includeSeparators or include_separators
  1174. last = 0
  1175. for t, s, e in self.scan_string(instring, max_matches=maxsplit):
  1176. yield instring[last:s]
  1177. if includeSeparators:
  1178. yield t[0]
  1179. last = e
  1180. yield instring[last:]
  1181. def __add__(self, other) -> "ParserElement":
  1182. """
  1183. Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`
  1184. converts them to :class:`Literal`\\ s by default.
  1185. Example::
  1186. greet = Word(alphas) + "," + Word(alphas) + "!"
  1187. hello = "Hello, World!"
  1188. print(hello, "->", greet.parse_string(hello))
  1189. prints::
  1190. Hello, World! -> ['Hello', ',', 'World', '!']
  1191. ``...`` may be used as a parse expression as a short form of :class:`SkipTo`::
  1192. Literal('start') + ... + Literal('end')
  1193. is equivalent to::
  1194. Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
  1195. Note that the skipped text is returned with '_skipped' as a results name,
  1196. and to support having multiple skips in the same parser, the value returned is
  1197. a list of all skipped text.
  1198. """
  1199. if other is Ellipsis:
  1200. return _PendingSkip(self)
  1201. if isinstance(other, str_type):
  1202. other = self._literalStringClass(other)
  1203. if not isinstance(other, ParserElement):
  1204. return NotImplemented
  1205. return And([self, other])
  1206. def __radd__(self, other) -> "ParserElement":
  1207. """
  1208. Implementation of ``+`` operator when left operand is not a :class:`ParserElement`
  1209. """
  1210. if other is Ellipsis:
  1211. return SkipTo(self)("_skipped*") + self
  1212. if isinstance(other, str_type):
  1213. other = self._literalStringClass(other)
  1214. if not isinstance(other, ParserElement):
  1215. return NotImplemented
  1216. return other + self
  1217. def __sub__(self, other) -> "ParserElement":
  1218. """
  1219. Implementation of ``-`` operator, returns :class:`And` with error stop
  1220. """
  1221. if isinstance(other, str_type):
  1222. other = self._literalStringClass(other)
  1223. if not isinstance(other, ParserElement):
  1224. return NotImplemented
  1225. return self + And._ErrorStop() + other
  1226. def __rsub__(self, other) -> "ParserElement":
  1227. """
  1228. Implementation of ``-`` operator when left operand is not a :class:`ParserElement`
  1229. """
  1230. if isinstance(other, str_type):
  1231. other = self._literalStringClass(other)
  1232. if not isinstance(other, ParserElement):
  1233. return NotImplemented
  1234. return other - self
  1235. def __mul__(self, other) -> "ParserElement":
  1236. """
  1237. Implementation of ``*`` operator, allows use of ``expr * 3`` in place of
  1238. ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer
  1239. tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
  1240. may also include ``None`` as in:
  1241. - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
  1242. to ``expr*n + ZeroOrMore(expr)``
  1243. (read as "at least n instances of ``expr``")
  1244. - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
  1245. (read as "0 to n instances of ``expr``")
  1246. - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
  1247. - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
  1248. Note that ``expr*(None, n)`` does not raise an exception if
  1249. more than n exprs exist in the input stream; that is,
  1250. ``expr*(None, n)`` does not enforce a maximum number of expr
  1251. occurrences. If this behavior is desired, then write
  1252. ``expr*(None, n) + ~expr``
  1253. """
  1254. if other is Ellipsis:
  1255. other = (0, None)
  1256. elif isinstance(other, tuple) and other[:1] == (Ellipsis,):
  1257. other = ((0,) + other[1:] + (None,))[:2]
  1258. if isinstance(other, int):
  1259. minElements, optElements = other, 0
  1260. elif isinstance(other, tuple):
  1261. other = tuple(o if o is not Ellipsis else None for o in other)
  1262. other = (other + (None, None))[:2]
  1263. if other[0] is None:
  1264. other = (0, other[1])
  1265. if isinstance(other[0], int) and other[1] is None:
  1266. if other[0] == 0:
  1267. return ZeroOrMore(self)
  1268. if other[0] == 1:
  1269. return OneOrMore(self)
  1270. else:
  1271. return self * other[0] + ZeroOrMore(self)
  1272. elif isinstance(other[0], int) and isinstance(other[1], int):
  1273. minElements, optElements = other
  1274. optElements -= minElements
  1275. else:
  1276. return NotImplemented
  1277. else:
  1278. return NotImplemented
  1279. if minElements < 0:
  1280. raise ValueError("cannot multiply ParserElement by negative value")
  1281. if optElements < 0:
  1282. raise ValueError(
  1283. "second tuple value must be greater or equal to first tuple value"
  1284. )
  1285. if minElements == optElements == 0:
  1286. return And([])
  1287. if optElements:
  1288. def makeOptionalList(n):
  1289. if n > 1:
  1290. return Opt(self + makeOptionalList(n - 1))
  1291. else:
  1292. return Opt(self)
  1293. if minElements:
  1294. if minElements == 1:
  1295. ret = self + makeOptionalList(optElements)
  1296. else:
  1297. ret = And([self] * minElements) + makeOptionalList(optElements)
  1298. else:
  1299. ret = makeOptionalList(optElements)
  1300. else:
  1301. if minElements == 1:
  1302. ret = self
  1303. else:
  1304. ret = And([self] * minElements)
  1305. return ret
  1306. def __rmul__(self, other) -> "ParserElement":
  1307. return self.__mul__(other)
  1308. def __or__(self, other) -> "ParserElement":
  1309. """
  1310. Implementation of ``|`` operator - returns :class:`MatchFirst`
  1311. """
  1312. if other is Ellipsis:
  1313. return _PendingSkip(self, must_skip=True)
  1314. if isinstance(other, str_type):
  1315. # `expr | ""` is equivalent to `Opt(expr)`
  1316. if other == "":
  1317. return Opt(self)
  1318. other = self._literalStringClass(other)
  1319. if not isinstance(other, ParserElement):
  1320. return NotImplemented
  1321. return MatchFirst([self, other])
  1322. def __ror__(self, other) -> "ParserElement":
  1323. """
  1324. Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
  1325. """
  1326. if isinstance(other, str_type):
  1327. other = self._literalStringClass(other)
  1328. if not isinstance(other, ParserElement):
  1329. return NotImplemented
  1330. return other | self
  1331. def __xor__(self, other) -> "ParserElement":
  1332. """
  1333. Implementation of ``^`` operator - returns :class:`Or`
  1334. """
  1335. if isinstance(other, str_type):
  1336. other = self._literalStringClass(other)
  1337. if not isinstance(other, ParserElement):
  1338. return NotImplemented
  1339. return Or([self, other])
  1340. def __rxor__(self, other) -> "ParserElement":
  1341. """
  1342. Implementation of ``^`` operator when left operand is not a :class:`ParserElement`
  1343. """
  1344. if isinstance(other, str_type):
  1345. other = self._literalStringClass(other)
  1346. if not isinstance(other, ParserElement):
  1347. return NotImplemented
  1348. return other ^ self
  1349. def __and__(self, other) -> "ParserElement":
  1350. """
  1351. Implementation of ``&`` operator - returns :class:`Each`
  1352. """
  1353. if isinstance(other, str_type):
  1354. other = self._literalStringClass(other)
  1355. if not isinstance(other, ParserElement):
  1356. return NotImplemented
  1357. return Each([self, other])
  1358. def __rand__(self, other) -> "ParserElement":
  1359. """
  1360. Implementation of ``&`` operator when left operand is not a :class:`ParserElement`
  1361. """
  1362. if isinstance(other, str_type):
  1363. other = self._literalStringClass(other)
  1364. if not isinstance(other, ParserElement):
  1365. return NotImplemented
  1366. return other & self
  1367. def __invert__(self) -> "ParserElement":
  1368. """
  1369. Implementation of ``~`` operator - returns :class:`NotAny`
  1370. """
  1371. return NotAny(self)
  1372. # disable __iter__ to override legacy use of sequential access to __getitem__ to
  1373. # iterate over a sequence
  1374. __iter__ = None
  1375. def __getitem__(self, key):
  1376. """
  1377. use ``[]`` indexing notation as a short form for expression repetition:
  1378. - ``expr[n]`` is equivalent to ``expr*n``
  1379. - ``expr[m, n]`` is equivalent to ``expr*(m, n)``
  1380. - ``expr[n, ...]`` or ``expr[n,]`` is equivalent
  1381. to ``expr*n + ZeroOrMore(expr)``
  1382. (read as "at least n instances of ``expr``")
  1383. - ``expr[..., n]`` is equivalent to ``expr*(0, n)``
  1384. (read as "0 to n instances of ``expr``")
  1385. - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
  1386. - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
  1387. ``None`` may be used in place of ``...``.
  1388. Note that ``expr[..., n]`` and ``expr[m, n]`` do not raise an exception
  1389. if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is
  1390. desired, then write ``expr[..., n] + ~expr``.
  1391. For repetition with a stop_on expression, use slice notation:
  1392. - ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)``
  1393. - ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)``
  1394. """
  1395. stop_on_defined = False
  1396. stop_on = NoMatch()
  1397. if isinstance(key, slice):
  1398. key, stop_on = key.start, key.stop
  1399. if key is None:
  1400. key = ...
  1401. stop_on_defined = True
  1402. elif isinstance(key, tuple) and isinstance(key[-1], slice):
  1403. key, stop_on = (key[0], key[1].start), key[1].stop
  1404. stop_on_defined = True
  1405. # convert single arg keys to tuples
  1406. if isinstance(key, str_type):
  1407. key = (key,)
  1408. try:
  1409. iter(key)
  1410. except TypeError:
  1411. key = (key, key)
  1412. if len(key) > 2:
  1413. raise TypeError(
  1414. f"only 1 or 2 index arguments supported ({key[:5]}{f'... [{len(key)}]' if len(key) > 5 else ''})"
  1415. )
  1416. # clip to 2 elements
  1417. ret = self * tuple(key[:2])
  1418. ret = typing.cast(_MultipleMatch, ret)
  1419. if stop_on_defined:
  1420. ret.stopOn(stop_on)
  1421. return ret
  1422. def __call__(self, name: typing.Optional[str] = None) -> "ParserElement":
  1423. """
  1424. Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.
  1425. If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be
  1426. passed as ``True``.
  1427. If ``name`` is omitted, same as calling :class:`copy`.
  1428. Example::
  1429. # these are equivalent
  1430. userdata = Word(alphas).set_results_name("name") + Word(nums + "-").set_results_name("socsecno")
  1431. userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
  1432. """
  1433. if name is not None:
  1434. return self._setResultsName(name)
  1435. else:
  1436. return self.copy()
  1437. def suppress(self) -> "ParserElement":
  1438. """
  1439. Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
  1440. cluttering up returned output.
  1441. """
  1442. return Suppress(self)
  1443. def ignore_whitespace(self, recursive: bool = True) -> "ParserElement":
  1444. """
  1445. Enables the skipping of whitespace before matching the characters in the
  1446. :class:`ParserElement`'s defined pattern.
  1447. :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)
  1448. """
  1449. self.skipWhitespace = True
  1450. return self
  1451. def leave_whitespace(self, recursive: bool = True) -> "ParserElement":
  1452. """
  1453. Disables the skipping of whitespace before matching the characters in the
  1454. :class:`ParserElement`'s defined pattern. This is normally only used internally by
  1455. the pyparsing module, but may be needed in some whitespace-sensitive grammars.
  1456. :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)
  1457. """
  1458. self.skipWhitespace = False
  1459. return self
  1460. def set_whitespace_chars(
  1461. self, chars: Union[Set[str], str], copy_defaults: bool = False
  1462. ) -> "ParserElement":
  1463. """
  1464. Overrides the default whitespace chars
  1465. """
  1466. self.skipWhitespace = True
  1467. self.whiteChars = set(chars)
  1468. self.copyDefaultWhiteChars = copy_defaults
  1469. return self
  1470. def parse_with_tabs(self) -> "ParserElement":
  1471. """
  1472. Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.
  1473. Must be called before ``parse_string`` when the input grammar contains elements that
  1474. match ``<TAB>`` characters.
  1475. """
  1476. self.keepTabs = True
  1477. return self
  1478. def ignore(self, other: "ParserElement") -> "ParserElement":
  1479. """
  1480. Define expression to be ignored (e.g., comments) while doing pattern
  1481. matching; may be called repeatedly, to define multiple comment or other
  1482. ignorable patterns.
  1483. Example::
  1484. patt = Word(alphas)[1, ...]
  1485. patt.parse_string('ablaj /* comment */ lskjd')
  1486. # -> ['ablaj']
  1487. patt.ignore(c_style_comment)
  1488. patt.parse_string('ablaj /* comment */ lskjd')
  1489. # -> ['ablaj', 'lskjd']
  1490. """
  1491. import typing
  1492. if isinstance(other, str_type):
  1493. other = Suppress(other)
  1494. if isinstance(other, Suppress):
  1495. if other not in self.ignoreExprs:
  1496. self.ignoreExprs.append(other)
  1497. else:
  1498. self.ignoreExprs.append(Suppress(other.copy()))
  1499. return self
  1500. def set_debug_actions(
  1501. self,
  1502. start_action: DebugStartAction,
  1503. success_action: DebugSuccessAction,
  1504. exception_action: DebugExceptionAction,
  1505. ) -> "ParserElement":
  1506. """
  1507. Customize display of debugging messages while doing pattern matching:
  1508. - ``start_action`` - method to be called when an expression is about to be parsed;
  1509. should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)``
  1510. - ``success_action`` - method to be called when an expression has successfully parsed;
  1511. should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)``
  1512. - ``exception_action`` - method to be called when expression fails to parse;
  1513. should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``
  1514. """
  1515. self.debugActions = self.DebugActions(
  1516. start_action or _default_start_debug_action, # type: ignore[truthy-function]
  1517. success_action or _default_success_debug_action, # type: ignore[truthy-function]
  1518. exception_action or _default_exception_debug_action, # type: ignore[truthy-function]
  1519. )
  1520. self.debug = True
  1521. return self
  1522. def set_debug(self, flag: bool = True, recurse: bool = False) -> "ParserElement":
  1523. """
  1524. Enable display of debugging messages while doing pattern matching.
  1525. Set ``flag`` to ``True`` to enable, ``False`` to disable.
  1526. Set ``recurse`` to ``True`` to set the debug flag on this expression and all sub-expressions.
  1527. Example::
  1528. wd = Word(alphas).set_name("alphaword")
  1529. integer = Word(nums).set_name("numword")
  1530. term = wd | integer
  1531. # turn on debugging for wd
  1532. wd.set_debug()
  1533. term[1, ...].parse_string("abc 123 xyz 890")
  1534. prints::
  1535. Match alphaword at loc 0(1,1)
  1536. Matched alphaword -> ['abc']
  1537. Match alphaword at loc 3(1,4)
  1538. Exception raised:Expected alphaword (at char 4), (line:1, col:5)
  1539. Match alphaword at loc 7(1,8)
  1540. Matched alphaword -> ['xyz']
  1541. Match alphaword at loc 11(1,12)
  1542. Exception raised:Expected alphaword (at char 12), (line:1, col:13)
  1543. Match alphaword at loc 15(1,16)
  1544. Exception raised:Expected alphaword (at char 15), (line:1, col:16)
  1545. The output shown is that produced by the default debug actions - custom debug actions can be
  1546. specified using :class:`set_debug_actions`. Prior to attempting
  1547. to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
  1548. is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
  1549. message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,
  1550. which makes debugging and exception messages easier to understand - for instance, the default
  1551. name created for the :class:`Word` expression without calling ``set_name`` is ``"W:(A-Za-z)"``.
  1552. """
  1553. if recurse:
  1554. for expr in self.visit_all():
  1555. expr.set_debug(flag, recurse=False)
  1556. return self
  1557. if flag:
  1558. self.set_debug_actions(
  1559. _default_start_debug_action,
  1560. _default_success_debug_action,
  1561. _default_exception_debug_action,
  1562. )
  1563. else:
  1564. self.debug = False
  1565. return self
  1566. @property
  1567. def default_name(self) -> str:
  1568. if self._defaultName is None:
  1569. self._defaultName = self._generateDefaultName()
  1570. return self._defaultName
  1571. @abstractmethod
  1572. def _generateDefaultName(self) -> str:
  1573. """
  1574. Child classes must define this method, which defines how the ``default_name`` is set.
  1575. """
  1576. def set_name(self, name: str) -> "ParserElement":
  1577. """
  1578. Define name for this expression, makes debugging and exception messages clearer.
  1579. Example::
  1580. Word(nums).parse_string("ABC") # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)
  1581. Word(nums).set_name("integer").parse_string("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
  1582. """
  1583. self.customName = name
  1584. self.errmsg = "Expected " + self.name
  1585. if __diag__.enable_debug_on_named_expressions:
  1586. self.set_debug()
  1587. return self
  1588. @property
  1589. def name(self) -> str:
  1590. # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name
  1591. return self.customName if self.customName is not None else self.default_name
  1592. def __str__(self) -> str:
  1593. return self.name
  1594. def __repr__(self) -> str:
  1595. return str(self)
  1596. def streamline(self) -> "ParserElement":
  1597. self.streamlined = True
  1598. self._defaultName = None
  1599. return self
  1600. def recurse(self) -> List["ParserElement"]:
  1601. return []
  1602. def _checkRecursion(self, parseElementList):
  1603. subRecCheckList = parseElementList[:] + [self]
  1604. for e in self.recurse():
  1605. e._checkRecursion(subRecCheckList)
  1606. def validate(self, validateTrace=None) -> None:
  1607. """
  1608. Check defined expressions for valid structure, check for infinite recursive definitions.
  1609. """
  1610. warnings.warn(
  1611. "ParserElement.validate() is deprecated, and should not be used to check for left recursion",
  1612. DeprecationWarning,
  1613. stacklevel=2,
  1614. )
  1615. self._checkRecursion([])
  1616. def parse_file(
  1617. self,
  1618. file_or_filename: Union[str, Path, TextIO],
  1619. encoding: str = "utf-8",
  1620. parse_all: bool = False,
  1621. *,
  1622. parseAll: bool = False,
  1623. ) -> ParseResults:
  1624. """
  1625. Execute the parse expression on the given file or filename.
  1626. If a filename is specified (instead of a file object),
  1627. the entire file is opened, read, and closed before parsing.
  1628. """
  1629. parseAll = parseAll or parse_all
  1630. try:
  1631. file_or_filename = typing.cast(TextIO, file_or_filename)
  1632. file_contents = file_or_filename.read()
  1633. except AttributeError:
  1634. file_or_filename = typing.cast(str, file_or_filename)
  1635. with open(file_or_filename, "r", encoding=encoding) as f:
  1636. file_contents = f.read()
  1637. try:
  1638. return self.parse_string(file_contents, parseAll)
  1639. except ParseBaseException as exc:
  1640. if ParserElement.verbose_stacktrace:
  1641. raise
  1642. else:
  1643. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1644. raise exc.with_traceback(None)
  1645. def __eq__(self, other):
  1646. if self is other:
  1647. return True
  1648. elif isinstance(other, str_type):
  1649. return self.matches(other, parse_all=True)
  1650. elif isinstance(other, ParserElement):
  1651. return vars(self) == vars(other)
  1652. return False
  1653. def __hash__(self):
  1654. return id(self)
  1655. def matches(
  1656. self, test_string: str, parse_all: bool = True, *, parseAll: bool = True
  1657. ) -> bool:
  1658. """
  1659. Method for quick testing of a parser against a test string. Good for simple
  1660. inline microtests of sub expressions while building up larger parser.
  1661. Parameters:
  1662. - ``test_string`` - to test against this expression for a match
  1663. - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
  1664. Example::
  1665. expr = Word(nums)
  1666. assert expr.matches("100")
  1667. """
  1668. parseAll = parseAll and parse_all
  1669. try:
  1670. self.parse_string(str(test_string), parse_all=parseAll)
  1671. return True
  1672. except ParseBaseException:
  1673. return False
  1674. def run_tests(
  1675. self,
  1676. tests: Union[str, List[str]],
  1677. parse_all: bool = True,
  1678. comment: typing.Optional[Union["ParserElement", str]] = "#",
  1679. full_dump: bool = True,
  1680. print_results: bool = True,
  1681. failure_tests: bool = False,
  1682. post_parse: typing.Optional[Callable[[str, ParseResults], str]] = None,
  1683. file: typing.Optional[TextIO] = None,
  1684. with_line_numbers: bool = False,
  1685. *,
  1686. parseAll: bool = True,
  1687. fullDump: bool = True,
  1688. printResults: bool = True,
  1689. failureTests: bool = False,
  1690. postParse: typing.Optional[Callable[[str, ParseResults], str]] = None,
  1691. ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:
  1692. """
  1693. Execute the parse expression on a series of test strings, showing each
  1694. test, the parsed results or where the parse failed. Quick and easy way to
  1695. run a parse expression against a list of sample strings.
  1696. Parameters:
  1697. - ``tests`` - a list of separate test strings, or a multiline string of test strings
  1698. - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests
  1699. - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test
  1700. string; pass None to disable comment filtering
  1701. - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;
  1702. if False, only dump nested list
  1703. - ``print_results`` - (default= ``True``) prints test output to stdout
  1704. - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing
  1705. - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as
  1706. `fn(test_string, parse_results)` and returns a string to be added to the test output
  1707. - ``file`` - (default= ``None``) optional file-like object to which test output will be written;
  1708. if None, will default to ``sys.stdout``
  1709. - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers
  1710. Returns: a (success, results) tuple, where success indicates that all tests succeeded
  1711. (or failed if ``failure_tests`` is True), and the results contain a list of lines of each
  1712. test's output
  1713. Example::
  1714. number_expr = pyparsing_common.number.copy()
  1715. result = number_expr.run_tests('''
  1716. # unsigned integer
  1717. 100
  1718. # negative integer
  1719. -100
  1720. # float with scientific notation
  1721. 6.02e23
  1722. # integer with scientific notation
  1723. 1e-12
  1724. ''')
  1725. print("Success" if result[0] else "Failed!")
  1726. result = number_expr.run_tests('''
  1727. # stray character
  1728. 100Z
  1729. # missing leading digit before '.'
  1730. -.100
  1731. # too many '.'
  1732. 3.14.159
  1733. ''', failure_tests=True)
  1734. print("Success" if result[0] else "Failed!")
  1735. prints::
  1736. # unsigned integer
  1737. 100
  1738. [100]
  1739. # negative integer
  1740. -100
  1741. [-100]
  1742. # float with scientific notation
  1743. 6.02e23
  1744. [6.02e+23]
  1745. # integer with scientific notation
  1746. 1e-12
  1747. [1e-12]
  1748. Success
  1749. # stray character
  1750. 100Z
  1751. ^
  1752. FAIL: Expected end of text (at char 3), (line:1, col:4)
  1753. # missing leading digit before '.'
  1754. -.100
  1755. ^
  1756. FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
  1757. # too many '.'
  1758. 3.14.159
  1759. ^
  1760. FAIL: Expected end of text (at char 4), (line:1, col:5)
  1761. Success
  1762. Each test string must be on a single line. If you want to test a string that spans multiple
  1763. lines, create a test like this::
  1764. expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines")
  1765. (Note that this is a raw string literal, you must include the leading ``'r'``.)
  1766. """
  1767. from .testing import pyparsing_test
  1768. parseAll = parseAll and parse_all
  1769. fullDump = fullDump and full_dump
  1770. printResults = printResults and print_results
  1771. failureTests = failureTests or failure_tests
  1772. postParse = postParse or post_parse
  1773. if isinstance(tests, str_type):
  1774. tests = typing.cast(str, tests)
  1775. line_strip = type(tests).strip
  1776. tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]
  1777. comment_specified = comment is not None
  1778. if comment_specified:
  1779. if isinstance(comment, str_type):
  1780. comment = typing.cast(str, comment)
  1781. comment = Literal(comment)
  1782. comment = typing.cast(ParserElement, comment)
  1783. if file is None:
  1784. file = sys.stdout
  1785. print_ = file.write
  1786. result: Union[ParseResults, Exception]
  1787. allResults: List[Tuple[str, Union[ParseResults, Exception]]] = []
  1788. comments: List[str] = []
  1789. success = True
  1790. NL = Literal(r"\n").add_parse_action(replace_with("\n")).ignore(quoted_string)
  1791. BOM = "\ufeff"
  1792. for t in tests:
  1793. if comment_specified and comment.matches(t, False) or comments and not t:
  1794. comments.append(
  1795. pyparsing_test.with_line_numbers(t) if with_line_numbers else t
  1796. )
  1797. continue
  1798. if not t:
  1799. continue
  1800. out = [
  1801. "\n" + "\n".join(comments) if comments else "",
  1802. pyparsing_test.with_line_numbers(t) if with_line_numbers else t,
  1803. ]
  1804. comments = []
  1805. try:
  1806. # convert newline marks to actual newlines, and strip leading BOM if present
  1807. t = NL.transform_string(t.lstrip(BOM))
  1808. result = self.parse_string(t, parse_all=parseAll)
  1809. except ParseBaseException as pe:
  1810. fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
  1811. out.append(pe.explain())
  1812. out.append("FAIL: " + str(pe))
  1813. if ParserElement.verbose_stacktrace:
  1814. out.extend(traceback.format_tb(pe.__traceback__))
  1815. success = success and failureTests
  1816. result = pe
  1817. except Exception as exc:
  1818. out.append(f"FAIL-EXCEPTION: {type(exc).__name__}: {exc}")
  1819. if ParserElement.verbose_stacktrace:
  1820. out.extend(traceback.format_tb(exc.__traceback__))
  1821. success = success and failureTests
  1822. result = exc
  1823. else:
  1824. success = success and not failureTests
  1825. if postParse is not None:
  1826. try:
  1827. pp_value = postParse(t, result)
  1828. if pp_value is not None:
  1829. if isinstance(pp_value, ParseResults):
  1830. out.append(pp_value.dump())
  1831. else:
  1832. out.append(str(pp_value))
  1833. else:
  1834. out.append(result.dump())
  1835. except Exception as e:
  1836. out.append(result.dump(full=fullDump))
  1837. out.append(
  1838. f"{postParse.__name__} failed: {type(e).__name__}: {e}"
  1839. )
  1840. else:
  1841. out.append(result.dump(full=fullDump))
  1842. out.append("")
  1843. if printResults:
  1844. print_("\n".join(out))
  1845. allResults.append((t, result))
  1846. return success, allResults
  1847. def create_diagram(
  1848. self,
  1849. output_html: Union[TextIO, Path, str],
  1850. vertical: int = 3,
  1851. show_results_names: bool = False,
  1852. show_groups: bool = False,
  1853. embed: bool = False,
  1854. **kwargs,
  1855. ) -> None:
  1856. """
  1857. Create a railroad diagram for the parser.
  1858. Parameters:
  1859. - ``output_html`` (str or file-like object) - output target for generated
  1860. diagram HTML
  1861. - ``vertical`` (int) - threshold for formatting multiple alternatives vertically
  1862. instead of horizontally (default=3)
  1863. - ``show_results_names`` - bool flag whether diagram should show annotations for
  1864. defined results names
  1865. - ``show_groups`` - bool flag whether groups should be highlighted with an unlabeled surrounding box
  1866. - ``embed`` - bool flag whether generated HTML should omit <HEAD>, <BODY>, and <DOCTYPE> tags to embed
  1867. the resulting HTML in an enclosing HTML source
  1868. - ``head`` - str containing additional HTML to insert into the <HEAD> section of the generated code;
  1869. can be used to insert custom CSS styling
  1870. - ``body`` - str containing additional HTML to insert at the beginning of the <BODY> section of the
  1871. generated code
  1872. Additional diagram-formatting keyword arguments can also be included;
  1873. see railroad.Diagram class.
  1874. """
  1875. try:
  1876. from .diagram import to_railroad, railroad_to_html
  1877. except ImportError as ie:
  1878. raise Exception(
  1879. "must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams"
  1880. ) from ie
  1881. self.streamline()
  1882. railroad = to_railroad(
  1883. self,
  1884. vertical=vertical,
  1885. show_results_names=show_results_names,
  1886. show_groups=show_groups,
  1887. diagram_kwargs=kwargs,
  1888. )
  1889. if isinstance(output_html, (str, Path)):
  1890. with open(output_html, "w", encoding="utf-8") as diag_file:
  1891. diag_file.write(railroad_to_html(railroad, embed=embed, **kwargs))
  1892. else:
  1893. # we were passed a file-like object, just write to it
  1894. output_html.write(railroad_to_html(railroad, embed=embed, **kwargs))
  1895. # Compatibility synonyms
  1896. # fmt: off
  1897. @staticmethod
  1898. @replaced_by_pep8(inline_literals_using)
  1899. def inlineLiteralsUsing(): ...
  1900. @staticmethod
  1901. @replaced_by_pep8(set_default_whitespace_chars)
  1902. def setDefaultWhitespaceChars(): ...
  1903. @replaced_by_pep8(set_results_name)
  1904. def setResultsName(self): ...
  1905. @replaced_by_pep8(set_break)
  1906. def setBreak(self): ...
  1907. @replaced_by_pep8(set_parse_action)
  1908. def setParseAction(self): ...
  1909. @replaced_by_pep8(add_parse_action)
  1910. def addParseAction(self): ...
  1911. @replaced_by_pep8(add_condition)
  1912. def addCondition(self): ...
  1913. @replaced_by_pep8(set_fail_action)
  1914. def setFailAction(self): ...
  1915. @replaced_by_pep8(try_parse)
  1916. def tryParse(self): ...
  1917. @staticmethod
  1918. @replaced_by_pep8(enable_left_recursion)
  1919. def enableLeftRecursion(): ...
  1920. @staticmethod
  1921. @replaced_by_pep8(enable_packrat)
  1922. def enablePackrat(): ...
  1923. @replaced_by_pep8(parse_string)
  1924. def parseString(self): ...
  1925. @replaced_by_pep8(scan_string)
  1926. def scanString(self): ...
  1927. @replaced_by_pep8(transform_string)
  1928. def transformString(self): ...
  1929. @replaced_by_pep8(search_string)
  1930. def searchString(self): ...
  1931. @replaced_by_pep8(ignore_whitespace)
  1932. def ignoreWhitespace(self): ...
  1933. @replaced_by_pep8(leave_whitespace)
  1934. def leaveWhitespace(self): ...
  1935. @replaced_by_pep8(set_whitespace_chars)
  1936. def setWhitespaceChars(self): ...
  1937. @replaced_by_pep8(parse_with_tabs)
  1938. def parseWithTabs(self): ...
  1939. @replaced_by_pep8(set_debug_actions)
  1940. def setDebugActions(self): ...
  1941. @replaced_by_pep8(set_debug)
  1942. def setDebug(self): ...
  1943. @replaced_by_pep8(set_name)
  1944. def setName(self): ...
  1945. @replaced_by_pep8(parse_file)
  1946. def parseFile(self): ...
  1947. @replaced_by_pep8(run_tests)
  1948. def runTests(self): ...
  1949. canParseNext = can_parse_next
  1950. resetCache = reset_cache
  1951. defaultName = default_name
  1952. # fmt: on
  1953. class _PendingSkip(ParserElement):
  1954. # internal placeholder class to hold a place were '...' is added to a parser element,
  1955. # once another ParserElement is added, this placeholder will be replaced with a SkipTo
  1956. def __init__(self, expr: ParserElement, must_skip: bool = False):
  1957. super().__init__()
  1958. self.anchor = expr
  1959. self.must_skip = must_skip
  1960. def _generateDefaultName(self) -> str:
  1961. return str(self.anchor + Empty()).replace("Empty", "...")
  1962. def __add__(self, other) -> "ParserElement":
  1963. skipper = SkipTo(other).set_name("...")("_skipped*")
  1964. if self.must_skip:
  1965. def must_skip(t):
  1966. if not t._skipped or t._skipped.as_list() == [""]:
  1967. del t[0]
  1968. t.pop("_skipped", None)
  1969. def show_skip(t):
  1970. if t._skipped.as_list()[-1:] == [""]:
  1971. t.pop("_skipped")
  1972. t["_skipped"] = "missing <" + repr(self.anchor) + ">"
  1973. return (
  1974. self.anchor + skipper().add_parse_action(must_skip)
  1975. | skipper().add_parse_action(show_skip)
  1976. ) + other
  1977. return self.anchor + skipper + other
  1978. def __repr__(self):
  1979. return self.defaultName
  1980. def parseImpl(self, *args):
  1981. raise Exception(
  1982. "use of `...` expression without following SkipTo target expression"
  1983. )
  1984. class Token(ParserElement):
  1985. """Abstract :class:`ParserElement` subclass, for defining atomic
  1986. matching patterns.
  1987. """
  1988. def __init__(self):
  1989. super().__init__(savelist=False)
  1990. def _generateDefaultName(self) -> str:
  1991. return type(self).__name__
  1992. class NoMatch(Token):
  1993. """
  1994. A token that will never match.
  1995. """
  1996. def __init__(self):
  1997. super().__init__()
  1998. self.mayReturnEmpty = True
  1999. self.mayIndexError = False
  2000. self.errmsg = "Unmatchable token"
  2001. def parseImpl(self, instring, loc, doActions=True):
  2002. raise ParseException(instring, loc, self.errmsg, self)
  2003. class Literal(Token):
  2004. """
  2005. Token to exactly match a specified string.
  2006. Example::
  2007. Literal('blah').parse_string('blah') # -> ['blah']
  2008. Literal('blah').parse_string('blahfooblah') # -> ['blah']
  2009. Literal('blah').parse_string('bla') # -> Exception: Expected "blah"
  2010. For case-insensitive matching, use :class:`CaselessLiteral`.
  2011. For keyword matching (force word break before and after the matched string),
  2012. use :class:`Keyword` or :class:`CaselessKeyword`.
  2013. """
  2014. def __new__(cls, match_string: str = "", *, matchString: str = ""):
  2015. # Performance tuning: select a subclass with optimized parseImpl
  2016. if cls is Literal:
  2017. match_string = matchString or match_string
  2018. if not match_string:
  2019. return super().__new__(Empty)
  2020. if len(match_string) == 1:
  2021. return super().__new__(_SingleCharLiteral)
  2022. # Default behavior
  2023. return super().__new__(cls)
  2024. # Needed to make copy.copy() work correctly if we customize __new__
  2025. def __getnewargs__(self):
  2026. return (self.match,)
  2027. def __init__(self, match_string: str = "", *, matchString: str = ""):
  2028. super().__init__()
  2029. match_string = matchString or match_string
  2030. self.match = match_string
  2031. self.matchLen = len(match_string)
  2032. self.firstMatchChar = match_string[:1]
  2033. self.errmsg = "Expected " + self.name
  2034. self.mayReturnEmpty = False
  2035. self.mayIndexError = False
  2036. def _generateDefaultName(self) -> str:
  2037. return repr(self.match)
  2038. def parseImpl(self, instring, loc, doActions=True):
  2039. if instring[loc] == self.firstMatchChar and instring.startswith(
  2040. self.match, loc
  2041. ):
  2042. return loc + self.matchLen, self.match
  2043. raise ParseException(instring, loc, self.errmsg, self)
  2044. class Empty(Literal):
  2045. """
  2046. An empty token, will always match.
  2047. """
  2048. def __init__(self, match_string="", *, matchString=""):
  2049. super().__init__("")
  2050. self.mayReturnEmpty = True
  2051. self.mayIndexError = False
  2052. def _generateDefaultName(self) -> str:
  2053. return "Empty"
  2054. def parseImpl(self, instring, loc, doActions=True):
  2055. return loc, []
  2056. class _SingleCharLiteral(Literal):
  2057. def parseImpl(self, instring, loc, doActions=True):
  2058. if instring[loc] == self.firstMatchChar:
  2059. return loc + 1, self.match
  2060. raise ParseException(instring, loc, self.errmsg, self)
  2061. ParserElement._literalStringClass = Literal
  2062. class Keyword(Token):
  2063. """
  2064. Token to exactly match a specified string as a keyword, that is,
  2065. it must be immediately preceded and followed by whitespace or
  2066. non-keyword characters. Compare with :class:`Literal`:
  2067. - ``Literal("if")`` will match the leading ``'if'`` in
  2068. ``'ifAndOnlyIf'``.
  2069. - ``Keyword("if")`` will not; it will only match the leading
  2070. ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``
  2071. Accepts two optional constructor arguments in addition to the
  2072. keyword string:
  2073. - ``ident_chars`` is a string of characters that would be valid
  2074. identifier characters, defaulting to all alphanumerics + "_" and
  2075. "$"
  2076. - ``caseless`` allows case-insensitive matching, default is ``False``.
  2077. Example::
  2078. Keyword("start").parse_string("start") # -> ['start']
  2079. Keyword("start").parse_string("starting") # -> Exception
  2080. For case-insensitive matching, use :class:`CaselessKeyword`.
  2081. """
  2082. DEFAULT_KEYWORD_CHARS = alphanums + "_$"
  2083. def __init__(
  2084. self,
  2085. match_string: str = "",
  2086. ident_chars: typing.Optional[str] = None,
  2087. caseless: bool = False,
  2088. *,
  2089. matchString: str = "",
  2090. identChars: typing.Optional[str] = None,
  2091. ):
  2092. super().__init__()
  2093. identChars = identChars or ident_chars
  2094. if identChars is None:
  2095. identChars = Keyword.DEFAULT_KEYWORD_CHARS
  2096. match_string = matchString or match_string
  2097. self.match = match_string
  2098. self.matchLen = len(match_string)
  2099. try:
  2100. self.firstMatchChar = match_string[0]
  2101. except IndexError:
  2102. raise ValueError("null string passed to Keyword; use Empty() instead")
  2103. self.errmsg = f"Expected {type(self).__name__} {self.name}"
  2104. self.mayReturnEmpty = False
  2105. self.mayIndexError = False
  2106. self.caseless = caseless
  2107. if caseless:
  2108. self.caselessmatch = match_string.upper()
  2109. identChars = identChars.upper()
  2110. self.identChars = set(identChars)
  2111. def _generateDefaultName(self) -> str:
  2112. return repr(self.match)
  2113. def parseImpl(self, instring, loc, doActions=True):
  2114. errmsg = self.errmsg
  2115. errloc = loc
  2116. if self.caseless:
  2117. if instring[loc : loc + self.matchLen].upper() == self.caselessmatch:
  2118. if loc == 0 or instring[loc - 1].upper() not in self.identChars:
  2119. if (
  2120. loc >= len(instring) - self.matchLen
  2121. or instring[loc + self.matchLen].upper() not in self.identChars
  2122. ):
  2123. return loc + self.matchLen, self.match
  2124. else:
  2125. # followed by keyword char
  2126. errmsg += ", was immediately followed by keyword character"
  2127. errloc = loc + self.matchLen
  2128. else:
  2129. # preceded by keyword char
  2130. errmsg += ", keyword was immediately preceded by keyword character"
  2131. errloc = loc - 1
  2132. # else no match just raise plain exception
  2133. else:
  2134. if (
  2135. instring[loc] == self.firstMatchChar
  2136. and self.matchLen == 1
  2137. or instring.startswith(self.match, loc)
  2138. ):
  2139. if loc == 0 or instring[loc - 1] not in self.identChars:
  2140. if (
  2141. loc >= len(instring) - self.matchLen
  2142. or instring[loc + self.matchLen] not in self.identChars
  2143. ):
  2144. return loc + self.matchLen, self.match
  2145. else:
  2146. # followed by keyword char
  2147. errmsg += (
  2148. ", keyword was immediately followed by keyword character"
  2149. )
  2150. errloc = loc + self.matchLen
  2151. else:
  2152. # preceded by keyword char
  2153. errmsg += ", keyword was immediately preceded by keyword character"
  2154. errloc = loc - 1
  2155. # else no match just raise plain exception
  2156. raise ParseException(instring, errloc, errmsg, self)
  2157. @staticmethod
  2158. def set_default_keyword_chars(chars) -> None:
  2159. """
  2160. Overrides the default characters used by :class:`Keyword` expressions.
  2161. """
  2162. Keyword.DEFAULT_KEYWORD_CHARS = chars
  2163. setDefaultKeywordChars = set_default_keyword_chars
  2164. class CaselessLiteral(Literal):
  2165. """
  2166. Token to match a specified string, ignoring case of letters.
  2167. Note: the matched results will always be in the case of the given
  2168. match string, NOT the case of the input text.
  2169. Example::
  2170. CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10")
  2171. # -> ['CMD', 'CMD', 'CMD']
  2172. (Contrast with example for :class:`CaselessKeyword`.)
  2173. """
  2174. def __init__(self, match_string: str = "", *, matchString: str = ""):
  2175. match_string = matchString or match_string
  2176. super().__init__(match_string.upper())
  2177. # Preserve the defining literal.
  2178. self.returnString = match_string
  2179. self.errmsg = "Expected " + self.name
  2180. def parseImpl(self, instring, loc, doActions=True):
  2181. if instring[loc : loc + self.matchLen].upper() == self.match:
  2182. return loc + self.matchLen, self.returnString
  2183. raise ParseException(instring, loc, self.errmsg, self)
  2184. class CaselessKeyword(Keyword):
  2185. """
  2186. Caseless version of :class:`Keyword`.
  2187. Example::
  2188. CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10")
  2189. # -> ['CMD', 'CMD']
  2190. (Contrast with example for :class:`CaselessLiteral`.)
  2191. """
  2192. def __init__(
  2193. self,
  2194. match_string: str = "",
  2195. ident_chars: typing.Optional[str] = None,
  2196. *,
  2197. matchString: str = "",
  2198. identChars: typing.Optional[str] = None,
  2199. ):
  2200. identChars = identChars or ident_chars
  2201. match_string = matchString or match_string
  2202. super().__init__(match_string, identChars, caseless=True)
  2203. class CloseMatch(Token):
  2204. """A variation on :class:`Literal` which matches "close" matches,
  2205. that is, strings with at most 'n' mismatching characters.
  2206. :class:`CloseMatch` takes parameters:
  2207. - ``match_string`` - string to be matched
  2208. - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters
  2209. - ``max_mismatches`` - (``default=1``) maximum number of
  2210. mismatches allowed to count as a match
  2211. The results from a successful parse will contain the matched text
  2212. from the input string and the following named results:
  2213. - ``mismatches`` - a list of the positions within the
  2214. match_string where mismatches were found
  2215. - ``original`` - the original match_string used to compare
  2216. against the input string
  2217. If ``mismatches`` is an empty list, then the match was an exact
  2218. match.
  2219. Example::
  2220. patt = CloseMatch("ATCATCGAATGGA")
  2221. patt.parse_string("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
  2222. patt.parse_string("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)
  2223. # exact match
  2224. patt.parse_string("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})
  2225. # close match allowing up to 2 mismatches
  2226. patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2)
  2227. patt.parse_string("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
  2228. """
  2229. def __init__(
  2230. self,
  2231. match_string: str,
  2232. max_mismatches: typing.Optional[int] = None,
  2233. *,
  2234. maxMismatches: int = 1,
  2235. caseless=False,
  2236. ):
  2237. maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches
  2238. super().__init__()
  2239. self.match_string = match_string
  2240. self.maxMismatches = maxMismatches
  2241. self.errmsg = f"Expected {self.match_string!r} (with up to {self.maxMismatches} mismatches)"
  2242. self.caseless = caseless
  2243. self.mayIndexError = False
  2244. self.mayReturnEmpty = False
  2245. def _generateDefaultName(self) -> str:
  2246. return f"{type(self).__name__}:{self.match_string!r}"
  2247. def parseImpl(self, instring, loc, doActions=True):
  2248. start = loc
  2249. instrlen = len(instring)
  2250. maxloc = start + len(self.match_string)
  2251. if maxloc <= instrlen:
  2252. match_string = self.match_string
  2253. match_stringloc = 0
  2254. mismatches = []
  2255. maxMismatches = self.maxMismatches
  2256. for match_stringloc, s_m in enumerate(
  2257. zip(instring[loc:maxloc], match_string)
  2258. ):
  2259. src, mat = s_m
  2260. if self.caseless:
  2261. src, mat = src.lower(), mat.lower()
  2262. if src != mat:
  2263. mismatches.append(match_stringloc)
  2264. if len(mismatches) > maxMismatches:
  2265. break
  2266. else:
  2267. loc = start + match_stringloc + 1
  2268. results = ParseResults([instring[start:loc]])
  2269. results["original"] = match_string
  2270. results["mismatches"] = mismatches
  2271. return loc, results
  2272. raise ParseException(instring, loc, self.errmsg, self)
  2273. class Word(Token):
  2274. """Token for matching words composed of allowed character sets.
  2275. Parameters:
  2276. - ``init_chars`` - string of all characters that should be used to
  2277. match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.;
  2278. if ``body_chars`` is also specified, then this is the string of
  2279. initial characters
  2280. - ``body_chars`` - string of characters that
  2281. can be used for matching after a matched initial character as
  2282. given in ``init_chars``; if omitted, same as the initial characters
  2283. (default=``None``)
  2284. - ``min`` - minimum number of characters to match (default=1)
  2285. - ``max`` - maximum number of characters to match (default=0)
  2286. - ``exact`` - exact number of characters to match (default=0)
  2287. - ``as_keyword`` - match as a keyword (default=``False``)
  2288. - ``exclude_chars`` - characters that might be
  2289. found in the input ``body_chars`` string but which should not be
  2290. accepted for matching ;useful to define a word of all
  2291. printables except for one or two characters, for instance
  2292. (default=``None``)
  2293. :class:`srange` is useful for defining custom character set strings
  2294. for defining :class:`Word` expressions, using range notation from
  2295. regular expression character sets.
  2296. A common mistake is to use :class:`Word` to match a specific literal
  2297. string, as in ``Word("Address")``. Remember that :class:`Word`
  2298. uses the string argument to define *sets* of matchable characters.
  2299. This expression would match "Add", "AAA", "dAred", or any other word
  2300. made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an
  2301. exact literal string, use :class:`Literal` or :class:`Keyword`.
  2302. pyparsing includes helper strings for building Words:
  2303. - :class:`alphas`
  2304. - :class:`nums`
  2305. - :class:`alphanums`
  2306. - :class:`hexnums`
  2307. - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255
  2308. - accented, tilded, umlauted, etc.)
  2309. - :class:`punc8bit` (non-alphabetic characters in ASCII range
  2310. 128-255 - currency, symbols, superscripts, diacriticals, etc.)
  2311. - :class:`printables` (any non-whitespace character)
  2312. ``alphas``, ``nums``, and ``printables`` are also defined in several
  2313. Unicode sets - see :class:`pyparsing_unicode``.
  2314. Example::
  2315. # a word composed of digits
  2316. integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
  2317. # a word with a leading capital, and zero or more lowercase
  2318. capital_word = Word(alphas.upper(), alphas.lower())
  2319. # hostnames are alphanumeric, with leading alpha, and '-'
  2320. hostname = Word(alphas, alphanums + '-')
  2321. # roman numeral (not a strict parser, accepts invalid mix of characters)
  2322. roman = Word("IVXLCDM")
  2323. # any string of non-whitespace characters, except for ','
  2324. csv_value = Word(printables, exclude_chars=",")
  2325. """
  2326. def __init__(
  2327. self,
  2328. init_chars: str = "",
  2329. body_chars: typing.Optional[str] = None,
  2330. min: int = 1,
  2331. max: int = 0,
  2332. exact: int = 0,
  2333. as_keyword: bool = False,
  2334. exclude_chars: typing.Optional[str] = None,
  2335. *,
  2336. initChars: typing.Optional[str] = None,
  2337. bodyChars: typing.Optional[str] = None,
  2338. asKeyword: bool = False,
  2339. excludeChars: typing.Optional[str] = None,
  2340. ):
  2341. initChars = initChars or init_chars
  2342. bodyChars = bodyChars or body_chars
  2343. asKeyword = asKeyword or as_keyword
  2344. excludeChars = excludeChars or exclude_chars
  2345. super().__init__()
  2346. if not initChars:
  2347. raise ValueError(
  2348. f"invalid {type(self).__name__}, initChars cannot be empty string"
  2349. )
  2350. initChars_set = set(initChars)
  2351. if excludeChars:
  2352. excludeChars_set = set(excludeChars)
  2353. initChars_set -= excludeChars_set
  2354. if bodyChars:
  2355. bodyChars = "".join(set(bodyChars) - excludeChars_set)
  2356. self.initChars = initChars_set
  2357. self.initCharsOrig = "".join(sorted(initChars_set))
  2358. if bodyChars:
  2359. self.bodyChars = set(bodyChars)
  2360. self.bodyCharsOrig = "".join(sorted(bodyChars))
  2361. else:
  2362. self.bodyChars = initChars_set
  2363. self.bodyCharsOrig = self.initCharsOrig
  2364. self.maxSpecified = max > 0
  2365. if min < 1:
  2366. raise ValueError(
  2367. "cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted"
  2368. )
  2369. if self.maxSpecified and min > max:
  2370. raise ValueError(
  2371. f"invalid args, if min and max both specified min must be <= max (min={min}, max={max})"
  2372. )
  2373. self.minLen = min
  2374. if max > 0:
  2375. self.maxLen = max
  2376. else:
  2377. self.maxLen = _MAX_INT
  2378. if exact > 0:
  2379. min = max = exact
  2380. self.maxLen = exact
  2381. self.minLen = exact
  2382. self.errmsg = "Expected " + self.name
  2383. self.mayIndexError = False
  2384. self.asKeyword = asKeyword
  2385. if self.asKeyword:
  2386. self.errmsg += " as a keyword"
  2387. # see if we can make a regex for this Word
  2388. if " " not in (self.initChars | self.bodyChars):
  2389. if len(self.initChars) == 1:
  2390. re_leading_fragment = re.escape(self.initCharsOrig)
  2391. else:
  2392. re_leading_fragment = f"[{_collapse_string_to_ranges(self.initChars)}]"
  2393. if self.bodyChars == self.initChars:
  2394. if max == 0 and self.minLen == 1:
  2395. repeat = "+"
  2396. elif max == 1:
  2397. repeat = ""
  2398. else:
  2399. if self.minLen != self.maxLen:
  2400. repeat = f"{{{self.minLen},{'' if self.maxLen == _MAX_INT else self.maxLen}}}"
  2401. else:
  2402. repeat = f"{{{self.minLen}}}"
  2403. self.reString = f"{re_leading_fragment}{repeat}"
  2404. else:
  2405. if max == 1:
  2406. re_body_fragment = ""
  2407. repeat = ""
  2408. else:
  2409. re_body_fragment = f"[{_collapse_string_to_ranges(self.bodyChars)}]"
  2410. if max == 0 and self.minLen == 1:
  2411. repeat = "*"
  2412. elif max == 2:
  2413. repeat = "?" if min <= 1 else ""
  2414. else:
  2415. if min != max:
  2416. repeat = f"{{{min - 1 if min > 0 else ''},{max - 1 if max > 0 else ''}}}"
  2417. else:
  2418. repeat = f"{{{min - 1 if min > 0 else ''}}}"
  2419. self.reString = f"{re_leading_fragment}{re_body_fragment}{repeat}"
  2420. if self.asKeyword:
  2421. self.reString = rf"\b{self.reString}\b"
  2422. try:
  2423. self.re = re.compile(self.reString)
  2424. except re.error:
  2425. self.re = None # type: ignore[assignment]
  2426. else:
  2427. self.re_match = self.re.match
  2428. self.parseImpl = self.parseImpl_regex # type: ignore[assignment]
  2429. def _generateDefaultName(self) -> str:
  2430. def charsAsStr(s):
  2431. max_repr_len = 16
  2432. s = _collapse_string_to_ranges(s, re_escape=False)
  2433. if len(s) > max_repr_len:
  2434. return s[: max_repr_len - 3] + "..."
  2435. else:
  2436. return s
  2437. if self.initChars != self.bodyChars:
  2438. base = f"W:({charsAsStr(self.initChars)}, {charsAsStr(self.bodyChars)})"
  2439. else:
  2440. base = f"W:({charsAsStr(self.initChars)})"
  2441. # add length specification
  2442. if self.minLen > 1 or self.maxLen != _MAX_INT:
  2443. if self.minLen == self.maxLen:
  2444. if self.minLen == 1:
  2445. return base[2:]
  2446. else:
  2447. return base + f"{{{self.minLen}}}"
  2448. elif self.maxLen == _MAX_INT:
  2449. return base + f"{{{self.minLen},...}}"
  2450. else:
  2451. return base + f"{{{self.minLen},{self.maxLen}}}"
  2452. return base
  2453. def parseImpl(self, instring, loc, doActions=True):
  2454. if instring[loc] not in self.initChars:
  2455. raise ParseException(instring, loc, self.errmsg, self)
  2456. start = loc
  2457. loc += 1
  2458. instrlen = len(instring)
  2459. bodychars = self.bodyChars
  2460. maxloc = start + self.maxLen
  2461. maxloc = min(maxloc, instrlen)
  2462. while loc < maxloc and instring[loc] in bodychars:
  2463. loc += 1
  2464. throwException = False
  2465. if loc - start < self.minLen:
  2466. throwException = True
  2467. elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
  2468. throwException = True
  2469. elif self.asKeyword:
  2470. if (
  2471. start > 0
  2472. and instring[start - 1] in bodychars
  2473. or loc < instrlen
  2474. and instring[loc] in bodychars
  2475. ):
  2476. throwException = True
  2477. if throwException:
  2478. raise ParseException(instring, loc, self.errmsg, self)
  2479. return loc, instring[start:loc]
  2480. def parseImpl_regex(self, instring, loc, doActions=True):
  2481. result = self.re_match(instring, loc)
  2482. if not result:
  2483. raise ParseException(instring, loc, self.errmsg, self)
  2484. loc = result.end()
  2485. return loc, result.group()
  2486. class Char(Word):
  2487. """A short-cut class for defining :class:`Word` ``(characters, exact=1)``,
  2488. when defining a match of any single character in a string of
  2489. characters.
  2490. """
  2491. def __init__(
  2492. self,
  2493. charset: str,
  2494. as_keyword: bool = False,
  2495. exclude_chars: typing.Optional[str] = None,
  2496. *,
  2497. asKeyword: bool = False,
  2498. excludeChars: typing.Optional[str] = None,
  2499. ):
  2500. asKeyword = asKeyword or as_keyword
  2501. excludeChars = excludeChars or exclude_chars
  2502. super().__init__(
  2503. charset, exact=1, as_keyword=asKeyword, exclude_chars=excludeChars
  2504. )
  2505. class Regex(Token):
  2506. r"""Token for matching strings that match a given regular
  2507. expression. Defined with string specifying the regular expression in
  2508. a form recognized by the stdlib Python `re module <https://docs.python.org/3/library/re.html>`_.
  2509. If the given regex contains named groups (defined using ``(?P<name>...)``),
  2510. these will be preserved as named :class:`ParseResults`.
  2511. If instead of the Python stdlib ``re`` module you wish to use a different RE module
  2512. (such as the ``regex`` module), you can do so by building your ``Regex`` object with
  2513. a compiled RE that was compiled using ``regex``.
  2514. Example::
  2515. realnum = Regex(r"[+-]?\d+\.\d*")
  2516. # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
  2517. roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
  2518. # named fields in a regex will be returned as named results
  2519. date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
  2520. # the Regex class will accept re's compiled using the regex module
  2521. import regex
  2522. parser = pp.Regex(regex.compile(r'[0-9]'))
  2523. """
  2524. def __init__(
  2525. self,
  2526. pattern: Any,
  2527. flags: Union[re.RegexFlag, int] = 0,
  2528. as_group_list: bool = False,
  2529. as_match: bool = False,
  2530. *,
  2531. asGroupList: bool = False,
  2532. asMatch: bool = False,
  2533. ):
  2534. """The parameters ``pattern`` and ``flags`` are passed
  2535. to the ``re.compile()`` function as-is. See the Python
  2536. `re module <https://docs.python.org/3/library/re.html>`_ module for an
  2537. explanation of the acceptable patterns and flags.
  2538. """
  2539. super().__init__()
  2540. asGroupList = asGroupList or as_group_list
  2541. asMatch = asMatch or as_match
  2542. if isinstance(pattern, str_type):
  2543. if not pattern:
  2544. raise ValueError("null string passed to Regex; use Empty() instead")
  2545. self._re = None
  2546. self.reString = self.pattern = pattern
  2547. self.flags = flags
  2548. elif hasattr(pattern, "pattern") and hasattr(pattern, "match"):
  2549. self._re = pattern
  2550. self.pattern = self.reString = pattern.pattern
  2551. self.flags = flags
  2552. else:
  2553. raise TypeError(
  2554. "Regex may only be constructed with a string or a compiled RE object"
  2555. )
  2556. self.errmsg = "Expected " + self.name
  2557. self.mayIndexError = False
  2558. self.asGroupList = asGroupList
  2559. self.asMatch = asMatch
  2560. if self.asGroupList:
  2561. self.parseImpl = self.parseImplAsGroupList # type: ignore [assignment]
  2562. if self.asMatch:
  2563. self.parseImpl = self.parseImplAsMatch # type: ignore [assignment]
  2564. @cached_property
  2565. def re(self):
  2566. if self._re:
  2567. return self._re
  2568. else:
  2569. try:
  2570. return re.compile(self.pattern, self.flags)
  2571. except re.error:
  2572. raise ValueError(f"invalid pattern ({self.pattern!r}) passed to Regex")
  2573. @cached_property
  2574. def re_match(self):
  2575. return self.re.match
  2576. @cached_property
  2577. def mayReturnEmpty(self):
  2578. return self.re_match("") is not None
  2579. def _generateDefaultName(self) -> str:
  2580. return "Re:({})".format(repr(self.pattern).replace("\\\\", "\\"))
  2581. def parseImpl(self, instring, loc, doActions=True):
  2582. result = self.re_match(instring, loc)
  2583. if not result:
  2584. raise ParseException(instring, loc, self.errmsg, self)
  2585. loc = result.end()
  2586. ret = ParseResults(result.group())
  2587. d = result.groupdict()
  2588. if d:
  2589. for k, v in d.items():
  2590. ret[k] = v
  2591. return loc, ret
  2592. def parseImplAsGroupList(self, instring, loc, doActions=True):
  2593. result = self.re_match(instring, loc)
  2594. if not result:
  2595. raise ParseException(instring, loc, self.errmsg, self)
  2596. loc = result.end()
  2597. ret = result.groups()
  2598. return loc, ret
  2599. def parseImplAsMatch(self, instring, loc, doActions=True):
  2600. result = self.re_match(instring, loc)
  2601. if not result:
  2602. raise ParseException(instring, loc, self.errmsg, self)
  2603. loc = result.end()
  2604. ret = result
  2605. return loc, ret
  2606. def sub(self, repl: str) -> ParserElement:
  2607. r"""
  2608. Return :class:`Regex` with an attached parse action to transform the parsed
  2609. result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
  2610. Example::
  2611. make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>")
  2612. print(make_html.transform_string("h1:main title:"))
  2613. # prints "<h1>main title</h1>"
  2614. """
  2615. if self.asGroupList:
  2616. raise TypeError("cannot use sub() with Regex(as_group_list=True)")
  2617. if self.asMatch and callable(repl):
  2618. raise TypeError(
  2619. "cannot use sub() with a callable with Regex(as_match=True)"
  2620. )
  2621. if self.asMatch:
  2622. def pa(tokens):
  2623. return tokens[0].expand(repl)
  2624. else:
  2625. def pa(tokens):
  2626. return self.re.sub(repl, tokens[0])
  2627. return self.add_parse_action(pa)
  2628. class QuotedString(Token):
  2629. r"""
  2630. Token for matching strings that are delimited by quoting characters.
  2631. Defined with the following parameters:
  2632. - ``quote_char`` - string of one or more characters defining the
  2633. quote delimiting string
  2634. - ``esc_char`` - character to re_escape quotes, typically backslash
  2635. (default= ``None``)
  2636. - ``esc_quote`` - special quote sequence to re_escape an embedded quote
  2637. string (such as SQL's ``""`` to re_escape an embedded ``"``)
  2638. (default= ``None``)
  2639. - ``multiline`` - boolean indicating whether quotes can span
  2640. multiple lines (default= ``False``)
  2641. - ``unquote_results`` - boolean indicating whether the matched text
  2642. should be unquoted (default= ``True``)
  2643. - ``end_quote_char`` - string of one or more characters defining the
  2644. end of the quote delimited string (default= ``None`` => same as
  2645. quote_char)
  2646. - ``convert_whitespace_escapes`` - convert escaped whitespace
  2647. (``'\t'``, ``'\n'``, etc.) to actual whitespace
  2648. (default= ``True``)
  2649. Example::
  2650. qs = QuotedString('"')
  2651. print(qs.search_string('lsjdf "This is the quote" sldjf'))
  2652. complex_qs = QuotedString('{{', end_quote_char='}}')
  2653. print(complex_qs.search_string('lsjdf {{This is the "quote"}} sldjf'))
  2654. sql_qs = QuotedString('"', esc_quote='""')
  2655. print(sql_qs.search_string('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
  2656. prints::
  2657. [['This is the quote']]
  2658. [['This is the "quote"']]
  2659. [['This is the quote with "embedded" quotes']]
  2660. """
  2661. ws_map = dict(((r"\t", "\t"), (r"\n", "\n"), (r"\f", "\f"), (r"\r", "\r")))
  2662. def __init__(
  2663. self,
  2664. quote_char: str = "",
  2665. esc_char: typing.Optional[str] = None,
  2666. esc_quote: typing.Optional[str] = None,
  2667. multiline: bool = False,
  2668. unquote_results: bool = True,
  2669. end_quote_char: typing.Optional[str] = None,
  2670. convert_whitespace_escapes: bool = True,
  2671. *,
  2672. quoteChar: str = "",
  2673. escChar: typing.Optional[str] = None,
  2674. escQuote: typing.Optional[str] = None,
  2675. unquoteResults: bool = True,
  2676. endQuoteChar: typing.Optional[str] = None,
  2677. convertWhitespaceEscapes: bool = True,
  2678. ):
  2679. super().__init__()
  2680. esc_char = escChar or esc_char
  2681. esc_quote = escQuote or esc_quote
  2682. unquote_results = unquoteResults and unquote_results
  2683. end_quote_char = endQuoteChar or end_quote_char
  2684. convert_whitespace_escapes = (
  2685. convertWhitespaceEscapes and convert_whitespace_escapes
  2686. )
  2687. quote_char = quoteChar or quote_char
  2688. # remove white space from quote chars
  2689. quote_char = quote_char.strip()
  2690. if not quote_char:
  2691. raise ValueError("quote_char cannot be the empty string")
  2692. if end_quote_char is None:
  2693. end_quote_char = quote_char
  2694. else:
  2695. end_quote_char = end_quote_char.strip()
  2696. if not end_quote_char:
  2697. raise ValueError("end_quote_char cannot be the empty string")
  2698. self.quote_char: str = quote_char
  2699. self.quote_char_len: int = len(quote_char)
  2700. self.first_quote_char: str = quote_char[0]
  2701. self.end_quote_char: str = end_quote_char
  2702. self.end_quote_char_len: int = len(end_quote_char)
  2703. self.esc_char: str = esc_char or ""
  2704. self.has_esc_char: bool = esc_char is not None
  2705. self.esc_quote: str = esc_quote or ""
  2706. self.unquote_results: bool = unquote_results
  2707. self.convert_whitespace_escapes: bool = convert_whitespace_escapes
  2708. self.multiline = multiline
  2709. self.re_flags = re.RegexFlag(0)
  2710. # fmt: off
  2711. # build up re pattern for the content between the quote delimiters
  2712. inner_pattern = []
  2713. if esc_quote:
  2714. inner_pattern.append(rf"(?:{re.escape(esc_quote)})")
  2715. if esc_char:
  2716. inner_pattern.append(rf"(?:{re.escape(esc_char)}.)")
  2717. if len(self.end_quote_char) > 1:
  2718. inner_pattern.append(
  2719. "(?:"
  2720. + "|".join(
  2721. f"(?:{re.escape(self.end_quote_char[:i])}(?!{re.escape(self.end_quote_char[i:])}))"
  2722. for i in range(len(self.end_quote_char) - 1, 0, -1)
  2723. )
  2724. + ")"
  2725. )
  2726. if self.multiline:
  2727. self.re_flags |= re.MULTILINE | re.DOTALL
  2728. inner_pattern.append(
  2729. rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}"
  2730. rf"{(_escape_regex_range_chars(esc_char) if self.has_esc_char else '')}])"
  2731. )
  2732. else:
  2733. inner_pattern.append(
  2734. rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}\n\r"
  2735. rf"{(_escape_regex_range_chars(esc_char) if self.has_esc_char else '')}])"
  2736. )
  2737. self.pattern = "".join(
  2738. [
  2739. re.escape(self.quote_char),
  2740. "(?:",
  2741. '|'.join(inner_pattern),
  2742. ")*",
  2743. re.escape(self.end_quote_char),
  2744. ]
  2745. )
  2746. if self.unquote_results:
  2747. if self.convert_whitespace_escapes:
  2748. self.unquote_scan_re = re.compile(
  2749. rf"({'|'.join(re.escape(k) for k in self.ws_map)})"
  2750. rf"|({re.escape(self.esc_char)}.)"
  2751. rf"|(\n|.)",
  2752. flags=self.re_flags,
  2753. )
  2754. else:
  2755. self.unquote_scan_re = re.compile(
  2756. rf"({re.escape(self.esc_char)}.)"
  2757. rf"|(\n|.)",
  2758. flags=self.re_flags
  2759. )
  2760. # fmt: on
  2761. try:
  2762. self.re = re.compile(self.pattern, self.re_flags)
  2763. self.reString = self.pattern
  2764. self.re_match = self.re.match
  2765. except re.error:
  2766. raise ValueError(f"invalid pattern {self.pattern!r} passed to Regex")
  2767. self.errmsg = "Expected " + self.name
  2768. self.mayIndexError = False
  2769. self.mayReturnEmpty = True
  2770. def _generateDefaultName(self) -> str:
  2771. if self.quote_char == self.end_quote_char and isinstance(
  2772. self.quote_char, str_type
  2773. ):
  2774. return f"string enclosed in {self.quote_char!r}"
  2775. return f"quoted string, starting with {self.quote_char} ending with {self.end_quote_char}"
  2776. def parseImpl(self, instring, loc, doActions=True):
  2777. # check first character of opening quote to see if that is a match
  2778. # before doing the more complicated regex match
  2779. result = (
  2780. instring[loc] == self.first_quote_char
  2781. and self.re_match(instring, loc)
  2782. or None
  2783. )
  2784. if not result:
  2785. raise ParseException(instring, loc, self.errmsg, self)
  2786. # get ending loc and matched string from regex matching result
  2787. loc = result.end()
  2788. ret = result.group()
  2789. if self.unquote_results:
  2790. # strip off quotes
  2791. ret = ret[self.quote_char_len : -self.end_quote_char_len]
  2792. if isinstance(ret, str_type):
  2793. # fmt: off
  2794. if self.convert_whitespace_escapes:
  2795. # as we iterate over matches in the input string,
  2796. # collect from whichever match group of the unquote_scan_re
  2797. # regex matches (only 1 group will match at any given time)
  2798. ret = "".join(
  2799. # match group 1 matches \t, \n, etc.
  2800. self.ws_map[match.group(1)] if match.group(1)
  2801. # match group 2 matches escaped characters
  2802. else match.group(2)[-1] if match.group(2)
  2803. # match group 3 matches any character
  2804. else match.group(3)
  2805. for match in self.unquote_scan_re.finditer(ret)
  2806. )
  2807. else:
  2808. ret = "".join(
  2809. # match group 1 matches escaped characters
  2810. match.group(1)[-1] if match.group(1)
  2811. # match group 2 matches any character
  2812. else match.group(2)
  2813. for match in self.unquote_scan_re.finditer(ret)
  2814. )
  2815. # fmt: on
  2816. # replace escaped quotes
  2817. if self.esc_quote:
  2818. ret = ret.replace(self.esc_quote, self.end_quote_char)
  2819. return loc, ret
  2820. class CharsNotIn(Token):
  2821. """Token for matching words composed of characters *not* in a given
  2822. set (will include whitespace in matched characters if not listed in
  2823. the provided exclusion set - see example). Defined with string
  2824. containing all disallowed characters, and an optional minimum,
  2825. maximum, and/or exact length. The default value for ``min`` is
  2826. 1 (a minimum value < 1 is not valid); the default values for
  2827. ``max`` and ``exact`` are 0, meaning no maximum or exact
  2828. length restriction.
  2829. Example::
  2830. # define a comma-separated-value as anything that is not a ','
  2831. csv_value = CharsNotIn(',')
  2832. print(DelimitedList(csv_value).parse_string("dkls,lsdkjf,s12 34,@!#,213"))
  2833. prints::
  2834. ['dkls', 'lsdkjf', 's12 34', '@!#', '213']
  2835. """
  2836. def __init__(
  2837. self,
  2838. not_chars: str = "",
  2839. min: int = 1,
  2840. max: int = 0,
  2841. exact: int = 0,
  2842. *,
  2843. notChars: str = "",
  2844. ):
  2845. super().__init__()
  2846. self.skipWhitespace = False
  2847. self.notChars = not_chars or notChars
  2848. self.notCharsSet = set(self.notChars)
  2849. if min < 1:
  2850. raise ValueError(
  2851. "cannot specify a minimum length < 1; use "
  2852. "Opt(CharsNotIn()) if zero-length char group is permitted"
  2853. )
  2854. self.minLen = min
  2855. if max > 0:
  2856. self.maxLen = max
  2857. else:
  2858. self.maxLen = _MAX_INT
  2859. if exact > 0:
  2860. self.maxLen = exact
  2861. self.minLen = exact
  2862. self.errmsg = "Expected " + self.name
  2863. self.mayReturnEmpty = self.minLen == 0
  2864. self.mayIndexError = False
  2865. def _generateDefaultName(self) -> str:
  2866. not_chars_str = _collapse_string_to_ranges(self.notChars)
  2867. if len(not_chars_str) > 16:
  2868. return f"!W:({self.notChars[: 16 - 3]}...)"
  2869. else:
  2870. return f"!W:({self.notChars})"
  2871. def parseImpl(self, instring, loc, doActions=True):
  2872. notchars = self.notCharsSet
  2873. if instring[loc] in notchars:
  2874. raise ParseException(instring, loc, self.errmsg, self)
  2875. start = loc
  2876. loc += 1
  2877. maxlen = min(start + self.maxLen, len(instring))
  2878. while loc < maxlen and instring[loc] not in notchars:
  2879. loc += 1
  2880. if loc - start < self.minLen:
  2881. raise ParseException(instring, loc, self.errmsg, self)
  2882. return loc, instring[start:loc]
  2883. class White(Token):
  2884. """Special matching class for matching whitespace. Normally,
  2885. whitespace is ignored by pyparsing grammars. This class is included
  2886. when some whitespace structures are significant. Define with
  2887. a string containing the whitespace characters to be matched; default
  2888. is ``" \\t\\r\\n"``. Also takes optional ``min``,
  2889. ``max``, and ``exact`` arguments, as defined for the
  2890. :class:`Word` class.
  2891. """
  2892. whiteStrs = {
  2893. " ": "<SP>",
  2894. "\t": "<TAB>",
  2895. "\n": "<LF>",
  2896. "\r": "<CR>",
  2897. "\f": "<FF>",
  2898. "\u00A0": "<NBSP>",
  2899. "\u1680": "<OGHAM_SPACE_MARK>",
  2900. "\u180E": "<MONGOLIAN_VOWEL_SEPARATOR>",
  2901. "\u2000": "<EN_QUAD>",
  2902. "\u2001": "<EM_QUAD>",
  2903. "\u2002": "<EN_SPACE>",
  2904. "\u2003": "<EM_SPACE>",
  2905. "\u2004": "<THREE-PER-EM_SPACE>",
  2906. "\u2005": "<FOUR-PER-EM_SPACE>",
  2907. "\u2006": "<SIX-PER-EM_SPACE>",
  2908. "\u2007": "<FIGURE_SPACE>",
  2909. "\u2008": "<PUNCTUATION_SPACE>",
  2910. "\u2009": "<THIN_SPACE>",
  2911. "\u200A": "<HAIR_SPACE>",
  2912. "\u200B": "<ZERO_WIDTH_SPACE>",
  2913. "\u202F": "<NNBSP>",
  2914. "\u205F": "<MMSP>",
  2915. "\u3000": "<IDEOGRAPHIC_SPACE>",
  2916. }
  2917. def __init__(self, ws: str = " \t\r\n", min: int = 1, max: int = 0, exact: int = 0):
  2918. super().__init__()
  2919. self.matchWhite = ws
  2920. self.set_whitespace_chars(
  2921. "".join(c for c in self.whiteStrs if c not in self.matchWhite),
  2922. copy_defaults=True,
  2923. )
  2924. # self.leave_whitespace()
  2925. self.mayReturnEmpty = True
  2926. self.errmsg = "Expected " + self.name
  2927. self.minLen = min
  2928. if max > 0:
  2929. self.maxLen = max
  2930. else:
  2931. self.maxLen = _MAX_INT
  2932. if exact > 0:
  2933. self.maxLen = exact
  2934. self.minLen = exact
  2935. def _generateDefaultName(self) -> str:
  2936. return "".join(White.whiteStrs[c] for c in self.matchWhite)
  2937. def parseImpl(self, instring, loc, doActions=True):
  2938. if instring[loc] not in self.matchWhite:
  2939. raise ParseException(instring, loc, self.errmsg, self)
  2940. start = loc
  2941. loc += 1
  2942. maxloc = start + self.maxLen
  2943. maxloc = min(maxloc, len(instring))
  2944. while loc < maxloc and instring[loc] in self.matchWhite:
  2945. loc += 1
  2946. if loc - start < self.minLen:
  2947. raise ParseException(instring, loc, self.errmsg, self)
  2948. return loc, instring[start:loc]
  2949. class PositionToken(Token):
  2950. def __init__(self):
  2951. super().__init__()
  2952. self.mayReturnEmpty = True
  2953. self.mayIndexError = False
  2954. class GoToColumn(PositionToken):
  2955. """Token to advance to a specific column of input text; useful for
  2956. tabular report scraping.
  2957. """
  2958. def __init__(self, colno: int):
  2959. super().__init__()
  2960. self.col = colno
  2961. def preParse(self, instring: str, loc: int) -> int:
  2962. if col(loc, instring) != self.col:
  2963. instrlen = len(instring)
  2964. if self.ignoreExprs:
  2965. loc = self._skipIgnorables(instring, loc)
  2966. while (
  2967. loc < instrlen
  2968. and instring[loc].isspace()
  2969. and col(loc, instring) != self.col
  2970. ):
  2971. loc += 1
  2972. return loc
  2973. def parseImpl(self, instring, loc, doActions=True):
  2974. thiscol = col(loc, instring)
  2975. if thiscol > self.col:
  2976. raise ParseException(instring, loc, "Text not in expected column", self)
  2977. newloc = loc + self.col - thiscol
  2978. ret = instring[loc:newloc]
  2979. return newloc, ret
  2980. class LineStart(PositionToken):
  2981. r"""Matches if current position is at the beginning of a line within
  2982. the parse string
  2983. Example::
  2984. test = '''\
  2985. AAA this line
  2986. AAA and this line
  2987. AAA but not this one
  2988. B AAA and definitely not this one
  2989. '''
  2990. for t in (LineStart() + 'AAA' + rest_of_line).search_string(test):
  2991. print(t)
  2992. prints::
  2993. ['AAA', ' this line']
  2994. ['AAA', ' and this line']
  2995. """
  2996. def __init__(self):
  2997. super().__init__()
  2998. self.leave_whitespace()
  2999. self.orig_whiteChars = set() | self.whiteChars
  3000. self.whiteChars.discard("\n")
  3001. self.skipper = Empty().set_whitespace_chars(self.whiteChars)
  3002. self.errmsg = "Expected start of line"
  3003. def preParse(self, instring: str, loc: int) -> int:
  3004. if loc == 0:
  3005. return loc
  3006. else:
  3007. ret = self.skipper.preParse(instring, loc)
  3008. if "\n" in self.orig_whiteChars:
  3009. while instring[ret : ret + 1] == "\n":
  3010. ret = self.skipper.preParse(instring, ret + 1)
  3011. return ret
  3012. def parseImpl(self, instring, loc, doActions=True):
  3013. if col(loc, instring) == 1:
  3014. return loc, []
  3015. raise ParseException(instring, loc, self.errmsg, self)
  3016. class LineEnd(PositionToken):
  3017. """Matches if current position is at the end of a line within the
  3018. parse string
  3019. """
  3020. def __init__(self):
  3021. super().__init__()
  3022. self.whiteChars.discard("\n")
  3023. self.set_whitespace_chars(self.whiteChars, copy_defaults=False)
  3024. self.errmsg = "Expected end of line"
  3025. def parseImpl(self, instring, loc, doActions=True):
  3026. if loc < len(instring):
  3027. if instring[loc] == "\n":
  3028. return loc + 1, "\n"
  3029. else:
  3030. raise ParseException(instring, loc, self.errmsg, self)
  3031. elif loc == len(instring):
  3032. return loc + 1, []
  3033. else:
  3034. raise ParseException(instring, loc, self.errmsg, self)
  3035. class StringStart(PositionToken):
  3036. """Matches if current position is at the beginning of the parse
  3037. string
  3038. """
  3039. def __init__(self):
  3040. super().__init__()
  3041. self.errmsg = "Expected start of text"
  3042. def parseImpl(self, instring, loc, doActions=True):
  3043. if loc != 0:
  3044. # see if entire string up to here is just whitespace and ignoreables
  3045. if loc != self.preParse(instring, 0):
  3046. raise ParseException(instring, loc, self.errmsg, self)
  3047. return loc, []
  3048. class StringEnd(PositionToken):
  3049. """
  3050. Matches if current position is at the end of the parse string
  3051. """
  3052. def __init__(self):
  3053. super().__init__()
  3054. self.errmsg = "Expected end of text"
  3055. def parseImpl(self, instring, loc, doActions=True):
  3056. if loc < len(instring):
  3057. raise ParseException(instring, loc, self.errmsg, self)
  3058. elif loc == len(instring):
  3059. return loc + 1, []
  3060. elif loc > len(instring):
  3061. return loc, []
  3062. else:
  3063. raise ParseException(instring, loc, self.errmsg, self)
  3064. class WordStart(PositionToken):
  3065. """Matches if the current position is at the beginning of a
  3066. :class:`Word`, and is not preceded by any character in a given
  3067. set of ``word_chars`` (default= ``printables``). To emulate the
  3068. ``\b`` behavior of regular expressions, use
  3069. ``WordStart(alphanums)``. ``WordStart`` will also match at
  3070. the beginning of the string being parsed, or at the beginning of
  3071. a line.
  3072. """
  3073. def __init__(self, word_chars: str = printables, *, wordChars: str = printables):
  3074. wordChars = word_chars if wordChars == printables else wordChars
  3075. super().__init__()
  3076. self.wordChars = set(wordChars)
  3077. self.errmsg = "Not at the start of a word"
  3078. def parseImpl(self, instring, loc, doActions=True):
  3079. if loc != 0:
  3080. if (
  3081. instring[loc - 1] in self.wordChars
  3082. or instring[loc] not in self.wordChars
  3083. ):
  3084. raise ParseException(instring, loc, self.errmsg, self)
  3085. return loc, []
  3086. class WordEnd(PositionToken):
  3087. """Matches if the current position is at the end of a :class:`Word`,
  3088. and is not followed by any character in a given set of ``word_chars``
  3089. (default= ``printables``). To emulate the ``\b`` behavior of
  3090. regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``
  3091. will also match at the end of the string being parsed, or at the end
  3092. of a line.
  3093. """
  3094. def __init__(self, word_chars: str = printables, *, wordChars: str = printables):
  3095. wordChars = word_chars if wordChars == printables else wordChars
  3096. super().__init__()
  3097. self.wordChars = set(wordChars)
  3098. self.skipWhitespace = False
  3099. self.errmsg = "Not at the end of a word"
  3100. def parseImpl(self, instring, loc, doActions=True):
  3101. instrlen = len(instring)
  3102. if instrlen > 0 and loc < instrlen:
  3103. if (
  3104. instring[loc] in self.wordChars
  3105. or instring[loc - 1] not in self.wordChars
  3106. ):
  3107. raise ParseException(instring, loc, self.errmsg, self)
  3108. return loc, []
  3109. class ParseExpression(ParserElement):
  3110. """Abstract subclass of ParserElement, for combining and
  3111. post-processing parsed tokens.
  3112. """
  3113. def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):
  3114. super().__init__(savelist)
  3115. self.exprs: List[ParserElement]
  3116. if isinstance(exprs, _generatorType):
  3117. exprs = list(exprs)
  3118. if isinstance(exprs, str_type):
  3119. self.exprs = [self._literalStringClass(exprs)]
  3120. elif isinstance(exprs, ParserElement):
  3121. self.exprs = [exprs]
  3122. elif isinstance(exprs, Iterable):
  3123. exprs = list(exprs)
  3124. # if sequence of strings provided, wrap with Literal
  3125. if any(isinstance(expr, str_type) for expr in exprs):
  3126. exprs = (
  3127. self._literalStringClass(e) if isinstance(e, str_type) else e
  3128. for e in exprs
  3129. )
  3130. self.exprs = list(exprs)
  3131. else:
  3132. try:
  3133. self.exprs = list(exprs)
  3134. except TypeError:
  3135. self.exprs = [exprs]
  3136. self.callPreparse = False
  3137. def recurse(self) -> List[ParserElement]:
  3138. return self.exprs[:]
  3139. def append(self, other) -> ParserElement:
  3140. self.exprs.append(other)
  3141. self._defaultName = None
  3142. return self
  3143. def leave_whitespace(self, recursive: bool = True) -> ParserElement:
  3144. """
  3145. Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
  3146. all contained expressions.
  3147. """
  3148. super().leave_whitespace(recursive)
  3149. if recursive:
  3150. self.exprs = [e.copy() for e in self.exprs]
  3151. for e in self.exprs:
  3152. e.leave_whitespace(recursive)
  3153. return self
  3154. def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
  3155. """
  3156. Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
  3157. all contained expressions.
  3158. """
  3159. super().ignore_whitespace(recursive)
  3160. if recursive:
  3161. self.exprs = [e.copy() for e in self.exprs]
  3162. for e in self.exprs:
  3163. e.ignore_whitespace(recursive)
  3164. return self
  3165. def ignore(self, other) -> ParserElement:
  3166. if isinstance(other, Suppress):
  3167. if other not in self.ignoreExprs:
  3168. super().ignore(other)
  3169. for e in self.exprs:
  3170. e.ignore(self.ignoreExprs[-1])
  3171. else:
  3172. super().ignore(other)
  3173. for e in self.exprs:
  3174. e.ignore(self.ignoreExprs[-1])
  3175. return self
  3176. def _generateDefaultName(self) -> str:
  3177. return f"{self.__class__.__name__}:({str(self.exprs)})"
  3178. def streamline(self) -> ParserElement:
  3179. if self.streamlined:
  3180. return self
  3181. super().streamline()
  3182. for e in self.exprs:
  3183. e.streamline()
  3184. # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)``
  3185. # but only if there are no parse actions or resultsNames on the nested And's
  3186. # (likewise for :class:`Or`'s and :class:`MatchFirst`'s)
  3187. if len(self.exprs) == 2:
  3188. other = self.exprs[0]
  3189. if (
  3190. isinstance(other, self.__class__)
  3191. and not other.parseAction
  3192. and other.resultsName is None
  3193. and not other.debug
  3194. ):
  3195. self.exprs = other.exprs[:] + [self.exprs[1]]
  3196. self._defaultName = None
  3197. self.mayReturnEmpty |= other.mayReturnEmpty
  3198. self.mayIndexError |= other.mayIndexError
  3199. other = self.exprs[-1]
  3200. if (
  3201. isinstance(other, self.__class__)
  3202. and not other.parseAction
  3203. and other.resultsName is None
  3204. and not other.debug
  3205. ):
  3206. self.exprs = self.exprs[:-1] + other.exprs[:]
  3207. self._defaultName = None
  3208. self.mayReturnEmpty |= other.mayReturnEmpty
  3209. self.mayIndexError |= other.mayIndexError
  3210. self.errmsg = "Expected " + str(self)
  3211. return self
  3212. def validate(self, validateTrace=None) -> None:
  3213. warnings.warn(
  3214. "ParserElement.validate() is deprecated, and should not be used to check for left recursion",
  3215. DeprecationWarning,
  3216. stacklevel=2,
  3217. )
  3218. tmp = (validateTrace if validateTrace is not None else [])[:] + [self]
  3219. for e in self.exprs:
  3220. e.validate(tmp)
  3221. self._checkRecursion([])
  3222. def copy(self) -> ParserElement:
  3223. ret = super().copy()
  3224. ret = typing.cast(ParseExpression, ret)
  3225. ret.exprs = [e.copy() for e in self.exprs]
  3226. return ret
  3227. def _setResultsName(self, name, listAllMatches=False):
  3228. if (
  3229. __diag__.warn_ungrouped_named_tokens_in_collection
  3230. and Diagnostics.warn_ungrouped_named_tokens_in_collection
  3231. not in self.suppress_warnings_
  3232. ):
  3233. for e in self.exprs:
  3234. if (
  3235. isinstance(e, ParserElement)
  3236. and e.resultsName
  3237. and Diagnostics.warn_ungrouped_named_tokens_in_collection
  3238. not in e.suppress_warnings_
  3239. ):
  3240. warnings.warn(
  3241. "{}: setting results name {!r} on {} expression "
  3242. "collides with {!r} on contained expression".format(
  3243. "warn_ungrouped_named_tokens_in_collection",
  3244. name,
  3245. type(self).__name__,
  3246. e.resultsName,
  3247. ),
  3248. stacklevel=3,
  3249. )
  3250. return super()._setResultsName(name, listAllMatches)
  3251. # Compatibility synonyms
  3252. # fmt: off
  3253. @replaced_by_pep8(leave_whitespace)
  3254. def leaveWhitespace(self): ...
  3255. @replaced_by_pep8(ignore_whitespace)
  3256. def ignoreWhitespace(self): ...
  3257. # fmt: on
  3258. class And(ParseExpression):
  3259. """
  3260. Requires all given :class:`ParseExpression` s to be found in the given order.
  3261. Expressions may be separated by whitespace.
  3262. May be constructed using the ``'+'`` operator.
  3263. May also be constructed using the ``'-'`` operator, which will
  3264. suppress backtracking.
  3265. Example::
  3266. integer = Word(nums)
  3267. name_expr = Word(alphas)[1, ...]
  3268. expr = And([integer("id"), name_expr("name"), integer("age")])
  3269. # more easily written as:
  3270. expr = integer("id") + name_expr("name") + integer("age")
  3271. """
  3272. class _ErrorStop(Empty):
  3273. def __init__(self, *args, **kwargs):
  3274. super().__init__(*args, **kwargs)
  3275. self.leave_whitespace()
  3276. def _generateDefaultName(self) -> str:
  3277. return "-"
  3278. def __init__(
  3279. self, exprs_arg: typing.Iterable[ParserElement], savelist: bool = True
  3280. ):
  3281. exprs: List[ParserElement] = list(exprs_arg)
  3282. if exprs and Ellipsis in exprs:
  3283. tmp = []
  3284. for i, expr in enumerate(exprs):
  3285. if expr is Ellipsis:
  3286. if i < len(exprs) - 1:
  3287. skipto_arg: ParserElement = typing.cast(
  3288. ParseExpression, (Empty() + exprs[i + 1])
  3289. ).exprs[-1]
  3290. tmp.append(SkipTo(skipto_arg)("_skipped*"))
  3291. else:
  3292. raise Exception(
  3293. "cannot construct And with sequence ending in ..."
  3294. )
  3295. else:
  3296. tmp.append(expr)
  3297. exprs[:] = tmp
  3298. super().__init__(exprs, savelist)
  3299. if self.exprs:
  3300. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3301. if not isinstance(self.exprs[0], White):
  3302. self.set_whitespace_chars(
  3303. self.exprs[0].whiteChars,
  3304. copy_defaults=self.exprs[0].copyDefaultWhiteChars,
  3305. )
  3306. self.skipWhitespace = self.exprs[0].skipWhitespace
  3307. else:
  3308. self.skipWhitespace = False
  3309. else:
  3310. self.mayReturnEmpty = True
  3311. self.callPreparse = True
  3312. def streamline(self) -> ParserElement:
  3313. # collapse any _PendingSkip's
  3314. if self.exprs:
  3315. if any(
  3316. isinstance(e, ParseExpression)
  3317. and e.exprs
  3318. and isinstance(e.exprs[-1], _PendingSkip)
  3319. for e in self.exprs[:-1]
  3320. ):
  3321. deleted_expr_marker = NoMatch()
  3322. for i, e in enumerate(self.exprs[:-1]):
  3323. if e is deleted_expr_marker:
  3324. continue
  3325. if (
  3326. isinstance(e, ParseExpression)
  3327. and e.exprs
  3328. and isinstance(e.exprs[-1], _PendingSkip)
  3329. ):
  3330. e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]
  3331. self.exprs[i + 1] = deleted_expr_marker
  3332. self.exprs = [e for e in self.exprs if e is not deleted_expr_marker]
  3333. super().streamline()
  3334. # link any IndentedBlocks to the prior expression
  3335. prev: ParserElement
  3336. cur: ParserElement
  3337. for prev, cur in zip(self.exprs, self.exprs[1:]):
  3338. # traverse cur or any first embedded expr of cur looking for an IndentedBlock
  3339. # (but watch out for recursive grammar)
  3340. seen = set()
  3341. while True:
  3342. if id(cur) in seen:
  3343. break
  3344. seen.add(id(cur))
  3345. if isinstance(cur, IndentedBlock):
  3346. prev.add_parse_action(
  3347. lambda s, l, t, cur_=cur: setattr(
  3348. cur_, "parent_anchor", col(l, s)
  3349. )
  3350. )
  3351. break
  3352. subs = cur.recurse()
  3353. next_first = next(iter(subs), None)
  3354. if next_first is None:
  3355. break
  3356. cur = typing.cast(ParserElement, next_first)
  3357. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3358. return self
  3359. def parseImpl(self, instring, loc, doActions=True):
  3360. # pass False as callPreParse arg to _parse for first element, since we already
  3361. # pre-parsed the string as part of our And pre-parsing
  3362. loc, resultlist = self.exprs[0]._parse(
  3363. instring, loc, doActions, callPreParse=False
  3364. )
  3365. errorStop = False
  3366. for e in self.exprs[1:]:
  3367. # if isinstance(e, And._ErrorStop):
  3368. if type(e) is And._ErrorStop:
  3369. errorStop = True
  3370. continue
  3371. if errorStop:
  3372. try:
  3373. loc, exprtokens = e._parse(instring, loc, doActions)
  3374. except ParseSyntaxException:
  3375. raise
  3376. except ParseBaseException as pe:
  3377. pe.__traceback__ = None
  3378. raise ParseSyntaxException._from_exception(pe)
  3379. except IndexError:
  3380. raise ParseSyntaxException(
  3381. instring, len(instring), self.errmsg, self
  3382. )
  3383. else:
  3384. loc, exprtokens = e._parse(instring, loc, doActions)
  3385. resultlist += exprtokens
  3386. return loc, resultlist
  3387. def __iadd__(self, other):
  3388. if isinstance(other, str_type):
  3389. other = self._literalStringClass(other)
  3390. if not isinstance(other, ParserElement):
  3391. return NotImplemented
  3392. return self.append(other) # And([self, other])
  3393. def _checkRecursion(self, parseElementList):
  3394. subRecCheckList = parseElementList[:] + [self]
  3395. for e in self.exprs:
  3396. e._checkRecursion(subRecCheckList)
  3397. if not e.mayReturnEmpty:
  3398. break
  3399. def _generateDefaultName(self) -> str:
  3400. inner = " ".join(str(e) for e in self.exprs)
  3401. # strip off redundant inner {}'s
  3402. while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
  3403. inner = inner[1:-1]
  3404. return "{" + inner + "}"
  3405. class Or(ParseExpression):
  3406. """Requires that at least one :class:`ParseExpression` is found. If
  3407. two expressions match, the expression that matches the longest
  3408. string will be used. May be constructed using the ``'^'``
  3409. operator.
  3410. Example::
  3411. # construct Or using '^' operator
  3412. number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
  3413. print(number.search_string("123 3.1416 789"))
  3414. prints::
  3415. [['123'], ['3.1416'], ['789']]
  3416. """
  3417. def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):
  3418. super().__init__(exprs, savelist)
  3419. if self.exprs:
  3420. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3421. self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)
  3422. else:
  3423. self.mayReturnEmpty = True
  3424. def streamline(self) -> ParserElement:
  3425. super().streamline()
  3426. if self.exprs:
  3427. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3428. self.saveAsList = any(e.saveAsList for e in self.exprs)
  3429. self.skipWhitespace = all(
  3430. e.skipWhitespace and not isinstance(e, White) for e in self.exprs
  3431. )
  3432. else:
  3433. self.saveAsList = False
  3434. return self
  3435. def parseImpl(self, instring, loc, doActions=True):
  3436. maxExcLoc = -1
  3437. maxException = None
  3438. matches = []
  3439. fatals = []
  3440. if all(e.callPreparse for e in self.exprs):
  3441. loc = self.preParse(instring, loc)
  3442. for e in self.exprs:
  3443. try:
  3444. loc2 = e.try_parse(instring, loc, raise_fatal=True)
  3445. except ParseFatalException as pfe:
  3446. pfe.__traceback__ = None
  3447. pfe.parser_element = e
  3448. fatals.append(pfe)
  3449. maxException = None
  3450. maxExcLoc = -1
  3451. except ParseException as err:
  3452. if not fatals:
  3453. err.__traceback__ = None
  3454. if err.loc > maxExcLoc:
  3455. maxException = err
  3456. maxExcLoc = err.loc
  3457. except IndexError:
  3458. if len(instring) > maxExcLoc:
  3459. maxException = ParseException(
  3460. instring, len(instring), e.errmsg, self
  3461. )
  3462. maxExcLoc = len(instring)
  3463. else:
  3464. # save match among all matches, to retry longest to shortest
  3465. matches.append((loc2, e))
  3466. if matches:
  3467. # re-evaluate all matches in descending order of length of match, in case attached actions
  3468. # might change whether or how much they match of the input.
  3469. matches.sort(key=itemgetter(0), reverse=True)
  3470. if not doActions:
  3471. # no further conditions or parse actions to change the selection of
  3472. # alternative, so the first match will be the best match
  3473. best_expr = matches[0][1]
  3474. return best_expr._parse(instring, loc, doActions)
  3475. longest = -1, None
  3476. for loc1, expr1 in matches:
  3477. if loc1 <= longest[0]:
  3478. # already have a longer match than this one will deliver, we are done
  3479. return longest
  3480. try:
  3481. loc2, toks = expr1._parse(instring, loc, doActions)
  3482. except ParseException as err:
  3483. err.__traceback__ = None
  3484. if err.loc > maxExcLoc:
  3485. maxException = err
  3486. maxExcLoc = err.loc
  3487. else:
  3488. if loc2 >= loc1:
  3489. return loc2, toks
  3490. # didn't match as much as before
  3491. elif loc2 > longest[0]:
  3492. longest = loc2, toks
  3493. if longest != (-1, None):
  3494. return longest
  3495. if fatals:
  3496. if len(fatals) > 1:
  3497. fatals.sort(key=lambda e: -e.loc)
  3498. if fatals[0].loc == fatals[1].loc:
  3499. fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element))))
  3500. max_fatal = fatals[0]
  3501. raise max_fatal
  3502. if maxException is not None:
  3503. # infer from this check that all alternatives failed at the current position
  3504. # so emit this collective error message instead of any single error message
  3505. if maxExcLoc == loc:
  3506. maxException.msg = self.errmsg
  3507. raise maxException
  3508. else:
  3509. raise ParseException(
  3510. instring, loc, "no defined alternatives to match", self
  3511. )
  3512. def __ixor__(self, other):
  3513. if isinstance(other, str_type):
  3514. other = self._literalStringClass(other)
  3515. if not isinstance(other, ParserElement):
  3516. return NotImplemented
  3517. return self.append(other) # Or([self, other])
  3518. def _generateDefaultName(self) -> str:
  3519. return "{" + " ^ ".join(str(e) for e in self.exprs) + "}"
  3520. def _setResultsName(self, name, listAllMatches=False):
  3521. if (
  3522. __diag__.warn_multiple_tokens_in_named_alternation
  3523. and Diagnostics.warn_multiple_tokens_in_named_alternation
  3524. not in self.suppress_warnings_
  3525. ):
  3526. if any(
  3527. isinstance(e, And)
  3528. and Diagnostics.warn_multiple_tokens_in_named_alternation
  3529. not in e.suppress_warnings_
  3530. for e in self.exprs
  3531. ):
  3532. warnings.warn(
  3533. "{}: setting results name {!r} on {} expression "
  3534. "will return a list of all parsed tokens in an And alternative, "
  3535. "in prior versions only the first token was returned; enclose "
  3536. "contained argument in Group".format(
  3537. "warn_multiple_tokens_in_named_alternation",
  3538. name,
  3539. type(self).__name__,
  3540. ),
  3541. stacklevel=3,
  3542. )
  3543. return super()._setResultsName(name, listAllMatches)
  3544. class MatchFirst(ParseExpression):
  3545. """Requires that at least one :class:`ParseExpression` is found. If
  3546. more than one expression matches, the first one listed is the one that will
  3547. match. May be constructed using the ``'|'`` operator.
  3548. Example::
  3549. # construct MatchFirst using '|' operator
  3550. # watch the order of expressions to match
  3551. number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
  3552. print(number.search_string("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']]
  3553. # put more selective expression first
  3554. number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
  3555. print(number.search_string("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']]
  3556. """
  3557. def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):
  3558. super().__init__(exprs, savelist)
  3559. if self.exprs:
  3560. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3561. self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)
  3562. else:
  3563. self.mayReturnEmpty = True
  3564. def streamline(self) -> ParserElement:
  3565. if self.streamlined:
  3566. return self
  3567. super().streamline()
  3568. if self.exprs:
  3569. self.saveAsList = any(e.saveAsList for e in self.exprs)
  3570. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3571. self.skipWhitespace = all(
  3572. e.skipWhitespace and not isinstance(e, White) for e in self.exprs
  3573. )
  3574. else:
  3575. self.saveAsList = False
  3576. self.mayReturnEmpty = True
  3577. return self
  3578. def parseImpl(self, instring, loc, doActions=True):
  3579. maxExcLoc = -1
  3580. maxException = None
  3581. for e in self.exprs:
  3582. try:
  3583. return e._parse(
  3584. instring,
  3585. loc,
  3586. doActions,
  3587. )
  3588. except ParseFatalException as pfe:
  3589. pfe.__traceback__ = None
  3590. pfe.parser_element = e
  3591. raise
  3592. except ParseException as err:
  3593. if err.loc > maxExcLoc:
  3594. maxException = err
  3595. maxExcLoc = err.loc
  3596. except IndexError:
  3597. if len(instring) > maxExcLoc:
  3598. maxException = ParseException(
  3599. instring, len(instring), e.errmsg, self
  3600. )
  3601. maxExcLoc = len(instring)
  3602. if maxException is not None:
  3603. # infer from this check that all alternatives failed at the current position
  3604. # so emit this collective error message instead of any individual error message
  3605. if maxExcLoc == loc:
  3606. maxException.msg = self.errmsg
  3607. raise maxException
  3608. else:
  3609. raise ParseException(
  3610. instring, loc, "no defined alternatives to match", self
  3611. )
  3612. def __ior__(self, other):
  3613. if isinstance(other, str_type):
  3614. other = self._literalStringClass(other)
  3615. if not isinstance(other, ParserElement):
  3616. return NotImplemented
  3617. return self.append(other) # MatchFirst([self, other])
  3618. def _generateDefaultName(self) -> str:
  3619. return "{" + " | ".join(str(e) for e in self.exprs) + "}"
  3620. def _setResultsName(self, name, listAllMatches=False):
  3621. if (
  3622. __diag__.warn_multiple_tokens_in_named_alternation
  3623. and Diagnostics.warn_multiple_tokens_in_named_alternation
  3624. not in self.suppress_warnings_
  3625. ):
  3626. if any(
  3627. isinstance(e, And)
  3628. and Diagnostics.warn_multiple_tokens_in_named_alternation
  3629. not in e.suppress_warnings_
  3630. for e in self.exprs
  3631. ):
  3632. warnings.warn(
  3633. "{}: setting results name {!r} on {} expression "
  3634. "will return a list of all parsed tokens in an And alternative, "
  3635. "in prior versions only the first token was returned; enclose "
  3636. "contained argument in Group".format(
  3637. "warn_multiple_tokens_in_named_alternation",
  3638. name,
  3639. type(self).__name__,
  3640. ),
  3641. stacklevel=3,
  3642. )
  3643. return super()._setResultsName(name, listAllMatches)
  3644. class Each(ParseExpression):
  3645. """Requires all given :class:`ParseExpression` s to be found, but in
  3646. any order. Expressions may be separated by whitespace.
  3647. May be constructed using the ``'&'`` operator.
  3648. Example::
  3649. color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
  3650. shape_type = one_of("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
  3651. integer = Word(nums)
  3652. shape_attr = "shape:" + shape_type("shape")
  3653. posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
  3654. color_attr = "color:" + color("color")
  3655. size_attr = "size:" + integer("size")
  3656. # use Each (using operator '&') to accept attributes in any order
  3657. # (shape and posn are required, color and size are optional)
  3658. shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr)
  3659. shape_spec.run_tests('''
  3660. shape: SQUARE color: BLACK posn: 100, 120
  3661. shape: CIRCLE size: 50 color: BLUE posn: 50,80
  3662. color:GREEN size:20 shape:TRIANGLE posn:20,40
  3663. '''
  3664. )
  3665. prints::
  3666. shape: SQUARE color: BLACK posn: 100, 120
  3667. ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
  3668. - color: BLACK
  3669. - posn: ['100', ',', '120']
  3670. - x: 100
  3671. - y: 120
  3672. - shape: SQUARE
  3673. shape: CIRCLE size: 50 color: BLUE posn: 50,80
  3674. ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
  3675. - color: BLUE
  3676. - posn: ['50', ',', '80']
  3677. - x: 50
  3678. - y: 80
  3679. - shape: CIRCLE
  3680. - size: 50
  3681. color: GREEN size: 20 shape: TRIANGLE posn: 20,40
  3682. ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
  3683. - color: GREEN
  3684. - posn: ['20', ',', '40']
  3685. - x: 20
  3686. - y: 40
  3687. - shape: TRIANGLE
  3688. - size: 20
  3689. """
  3690. def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = True):
  3691. super().__init__(exprs, savelist)
  3692. if self.exprs:
  3693. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3694. else:
  3695. self.mayReturnEmpty = True
  3696. self.skipWhitespace = True
  3697. self.initExprGroups = True
  3698. self.saveAsList = True
  3699. def __iand__(self, other):
  3700. if isinstance(other, str_type):
  3701. other = self._literalStringClass(other)
  3702. if not isinstance(other, ParserElement):
  3703. return NotImplemented
  3704. return self.append(other) # Each([self, other])
  3705. def streamline(self) -> ParserElement:
  3706. super().streamline()
  3707. if self.exprs:
  3708. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3709. else:
  3710. self.mayReturnEmpty = True
  3711. return self
  3712. def parseImpl(self, instring, loc, doActions=True):
  3713. if self.initExprGroups:
  3714. self.opt1map = dict(
  3715. (id(e.expr), e) for e in self.exprs if isinstance(e, Opt)
  3716. )
  3717. opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)]
  3718. opt2 = [
  3719. e
  3720. for e in self.exprs
  3721. if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore))
  3722. ]
  3723. self.optionals = opt1 + opt2
  3724. self.multioptionals = [
  3725. e.expr.set_results_name(e.resultsName, list_all_matches=True)
  3726. for e in self.exprs
  3727. if isinstance(e, _MultipleMatch)
  3728. ]
  3729. self.multirequired = [
  3730. e.expr.set_results_name(e.resultsName, list_all_matches=True)
  3731. for e in self.exprs
  3732. if isinstance(e, OneOrMore)
  3733. ]
  3734. self.required = [
  3735. e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore))
  3736. ]
  3737. self.required += self.multirequired
  3738. self.initExprGroups = False
  3739. tmpLoc = loc
  3740. tmpReqd = self.required[:]
  3741. tmpOpt = self.optionals[:]
  3742. multis = self.multioptionals[:]
  3743. matchOrder = []
  3744. keepMatching = True
  3745. failed = []
  3746. fatals = []
  3747. while keepMatching:
  3748. tmpExprs = tmpReqd + tmpOpt + multis
  3749. failed.clear()
  3750. fatals.clear()
  3751. for e in tmpExprs:
  3752. try:
  3753. tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True)
  3754. except ParseFatalException as pfe:
  3755. pfe.__traceback__ = None
  3756. pfe.parser_element = e
  3757. fatals.append(pfe)
  3758. failed.append(e)
  3759. except ParseException:
  3760. failed.append(e)
  3761. else:
  3762. matchOrder.append(self.opt1map.get(id(e), e))
  3763. if e in tmpReqd:
  3764. tmpReqd.remove(e)
  3765. elif e in tmpOpt:
  3766. tmpOpt.remove(e)
  3767. if len(failed) == len(tmpExprs):
  3768. keepMatching = False
  3769. # look for any ParseFatalExceptions
  3770. if fatals:
  3771. if len(fatals) > 1:
  3772. fatals.sort(key=lambda e: -e.loc)
  3773. if fatals[0].loc == fatals[1].loc:
  3774. fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element))))
  3775. max_fatal = fatals[0]
  3776. raise max_fatal
  3777. if tmpReqd:
  3778. missing = ", ".join([str(e) for e in tmpReqd])
  3779. raise ParseException(
  3780. instring,
  3781. loc,
  3782. f"Missing one or more required elements ({missing})",
  3783. )
  3784. # add any unmatched Opts, in case they have default values defined
  3785. matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt]
  3786. total_results = ParseResults([])
  3787. for e in matchOrder:
  3788. loc, results = e._parse(instring, loc, doActions)
  3789. total_results += results
  3790. return loc, total_results
  3791. def _generateDefaultName(self) -> str:
  3792. return "{" + " & ".join(str(e) for e in self.exprs) + "}"
  3793. class ParseElementEnhance(ParserElement):
  3794. """Abstract subclass of :class:`ParserElement`, for combining and
  3795. post-processing parsed tokens.
  3796. """
  3797. def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):
  3798. super().__init__(savelist)
  3799. if isinstance(expr, str_type):
  3800. expr_str = typing.cast(str, expr)
  3801. if issubclass(self._literalStringClass, Token):
  3802. expr = self._literalStringClass(expr_str) # type: ignore[call-arg]
  3803. elif issubclass(type(self), self._literalStringClass):
  3804. expr = Literal(expr_str)
  3805. else:
  3806. expr = self._literalStringClass(Literal(expr_str)) # type: ignore[assignment, call-arg]
  3807. expr = typing.cast(ParserElement, expr)
  3808. self.expr = expr
  3809. if expr is not None:
  3810. self.mayIndexError = expr.mayIndexError
  3811. self.mayReturnEmpty = expr.mayReturnEmpty
  3812. self.set_whitespace_chars(
  3813. expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars
  3814. )
  3815. self.skipWhitespace = expr.skipWhitespace
  3816. self.saveAsList = expr.saveAsList
  3817. self.callPreparse = expr.callPreparse
  3818. self.ignoreExprs.extend(expr.ignoreExprs)
  3819. def recurse(self) -> List[ParserElement]:
  3820. return [self.expr] if self.expr is not None else []
  3821. def parseImpl(self, instring, loc, doActions=True):
  3822. if self.expr is not None:
  3823. try:
  3824. return self.expr._parse(instring, loc, doActions, callPreParse=False)
  3825. except ParseBaseException as pbe:
  3826. if not isinstance(self, Forward) or self.customName is not None:
  3827. pbe.msg = self.errmsg
  3828. raise
  3829. else:
  3830. raise ParseException(instring, loc, "No expression defined", self)
  3831. def leave_whitespace(self, recursive: bool = True) -> ParserElement:
  3832. super().leave_whitespace(recursive)
  3833. if recursive:
  3834. if self.expr is not None:
  3835. self.expr = self.expr.copy()
  3836. self.expr.leave_whitespace(recursive)
  3837. return self
  3838. def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
  3839. super().ignore_whitespace(recursive)
  3840. if recursive:
  3841. if self.expr is not None:
  3842. self.expr = self.expr.copy()
  3843. self.expr.ignore_whitespace(recursive)
  3844. return self
  3845. def ignore(self, other) -> ParserElement:
  3846. if isinstance(other, Suppress):
  3847. if other not in self.ignoreExprs:
  3848. super().ignore(other)
  3849. if self.expr is not None:
  3850. self.expr.ignore(self.ignoreExprs[-1])
  3851. else:
  3852. super().ignore(other)
  3853. if self.expr is not None:
  3854. self.expr.ignore(self.ignoreExprs[-1])
  3855. return self
  3856. def streamline(self) -> ParserElement:
  3857. super().streamline()
  3858. if self.expr is not None:
  3859. self.expr.streamline()
  3860. return self
  3861. def _checkRecursion(self, parseElementList):
  3862. if self in parseElementList:
  3863. raise RecursiveGrammarException(parseElementList + [self])
  3864. subRecCheckList = parseElementList[:] + [self]
  3865. if self.expr is not None:
  3866. self.expr._checkRecursion(subRecCheckList)
  3867. def validate(self, validateTrace=None) -> None:
  3868. warnings.warn(
  3869. "ParserElement.validate() is deprecated, and should not be used to check for left recursion",
  3870. DeprecationWarning,
  3871. stacklevel=2,
  3872. )
  3873. if validateTrace is None:
  3874. validateTrace = []
  3875. tmp = validateTrace[:] + [self]
  3876. if self.expr is not None:
  3877. self.expr.validate(tmp)
  3878. self._checkRecursion([])
  3879. def _generateDefaultName(self) -> str:
  3880. return f"{self.__class__.__name__}:({str(self.expr)})"
  3881. # Compatibility synonyms
  3882. # fmt: off
  3883. @replaced_by_pep8(leave_whitespace)
  3884. def leaveWhitespace(self): ...
  3885. @replaced_by_pep8(ignore_whitespace)
  3886. def ignoreWhitespace(self): ...
  3887. # fmt: on
  3888. class IndentedBlock(ParseElementEnhance):
  3889. """
  3890. Expression to match one or more expressions at a given indentation level.
  3891. Useful for parsing text where structure is implied by indentation (like Python source code).
  3892. """
  3893. class _Indent(Empty):
  3894. def __init__(self, ref_col: int):
  3895. super().__init__()
  3896. self.errmsg = f"expected indent at column {ref_col}"
  3897. self.add_condition(lambda s, l, t: col(l, s) == ref_col)
  3898. class _IndentGreater(Empty):
  3899. def __init__(self, ref_col: int):
  3900. super().__init__()
  3901. self.errmsg = f"expected indent at column greater than {ref_col}"
  3902. self.add_condition(lambda s, l, t: col(l, s) > ref_col)
  3903. def __init__(
  3904. self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True
  3905. ):
  3906. super().__init__(expr, savelist=True)
  3907. # if recursive:
  3908. # raise NotImplementedError("IndentedBlock with recursive is not implemented")
  3909. self._recursive = recursive
  3910. self._grouped = grouped
  3911. self.parent_anchor = 1
  3912. def parseImpl(self, instring, loc, doActions=True):
  3913. # advance parse position to non-whitespace by using an Empty()
  3914. # this should be the column to be used for all subsequent indented lines
  3915. anchor_loc = Empty().preParse(instring, loc)
  3916. # see if self.expr matches at the current location - if not it will raise an exception
  3917. # and no further work is necessary
  3918. self.expr.try_parse(instring, anchor_loc, do_actions=doActions)
  3919. indent_col = col(anchor_loc, instring)
  3920. peer_detect_expr = self._Indent(indent_col)
  3921. inner_expr = Empty() + peer_detect_expr + self.expr
  3922. if self._recursive:
  3923. sub_indent = self._IndentGreater(indent_col)
  3924. nested_block = IndentedBlock(
  3925. self.expr, recursive=self._recursive, grouped=self._grouped
  3926. )
  3927. nested_block.set_debug(self.debug)
  3928. nested_block.parent_anchor = indent_col
  3929. inner_expr += Opt(sub_indent + nested_block)
  3930. inner_expr.set_name(f"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}")
  3931. block = OneOrMore(inner_expr)
  3932. trailing_undent = self._Indent(self.parent_anchor) | StringEnd()
  3933. if self._grouped:
  3934. wrapper = Group
  3935. else:
  3936. wrapper = lambda expr: expr
  3937. return (wrapper(block) + Optional(trailing_undent)).parseImpl(
  3938. instring, anchor_loc, doActions
  3939. )
  3940. class AtStringStart(ParseElementEnhance):
  3941. """Matches if expression matches at the beginning of the parse
  3942. string::
  3943. AtStringStart(Word(nums)).parse_string("123")
  3944. # prints ["123"]
  3945. AtStringStart(Word(nums)).parse_string(" 123")
  3946. # raises ParseException
  3947. """
  3948. def __init__(self, expr: Union[ParserElement, str]):
  3949. super().__init__(expr)
  3950. self.callPreparse = False
  3951. def parseImpl(self, instring, loc, doActions=True):
  3952. if loc != 0:
  3953. raise ParseException(instring, loc, "not found at string start")
  3954. return super().parseImpl(instring, loc, doActions)
  3955. class AtLineStart(ParseElementEnhance):
  3956. r"""Matches if an expression matches at the beginning of a line within
  3957. the parse string
  3958. Example::
  3959. test = '''\
  3960. AAA this line
  3961. AAA and this line
  3962. AAA but not this one
  3963. B AAA and definitely not this one
  3964. '''
  3965. for t in (AtLineStart('AAA') + rest_of_line).search_string(test):
  3966. print(t)
  3967. prints::
  3968. ['AAA', ' this line']
  3969. ['AAA', ' and this line']
  3970. """
  3971. def __init__(self, expr: Union[ParserElement, str]):
  3972. super().__init__(expr)
  3973. self.callPreparse = False
  3974. def parseImpl(self, instring, loc, doActions=True):
  3975. if col(loc, instring) != 1:
  3976. raise ParseException(instring, loc, "not found at line start")
  3977. return super().parseImpl(instring, loc, doActions)
  3978. class FollowedBy(ParseElementEnhance):
  3979. """Lookahead matching of the given parse expression.
  3980. ``FollowedBy`` does *not* advance the parsing position within
  3981. the input string, it only verifies that the specified parse
  3982. expression matches at the current position. ``FollowedBy``
  3983. always returns a null token list. If any results names are defined
  3984. in the lookahead expression, those *will* be returned for access by
  3985. name.
  3986. Example::
  3987. # use FollowedBy to match a label only if it is followed by a ':'
  3988. data_word = Word(alphas)
  3989. label = data_word + FollowedBy(':')
  3990. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
  3991. attr_expr[1, ...].parse_string("shape: SQUARE color: BLACK posn: upper left").pprint()
  3992. prints::
  3993. [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
  3994. """
  3995. def __init__(self, expr: Union[ParserElement, str]):
  3996. super().__init__(expr)
  3997. self.mayReturnEmpty = True
  3998. def parseImpl(self, instring, loc, doActions=True):
  3999. # by using self._expr.parse and deleting the contents of the returned ParseResults list
  4000. # we keep any named results that were defined in the FollowedBy expression
  4001. _, ret = self.expr._parse(instring, loc, doActions=doActions)
  4002. del ret[:]
  4003. return loc, ret
  4004. class PrecededBy(ParseElementEnhance):
  4005. """Lookbehind matching of the given parse expression.
  4006. ``PrecededBy`` does not advance the parsing position within the
  4007. input string, it only verifies that the specified parse expression
  4008. matches prior to the current position. ``PrecededBy`` always
  4009. returns a null token list, but if a results name is defined on the
  4010. given expression, it is returned.
  4011. Parameters:
  4012. - ``expr`` - expression that must match prior to the current parse
  4013. location
  4014. - ``retreat`` - (default= ``None``) - (int) maximum number of characters
  4015. to lookbehind prior to the current parse location
  4016. If the lookbehind expression is a string, :class:`Literal`,
  4017. :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn`
  4018. with a specified exact or maximum length, then the retreat
  4019. parameter is not required. Otherwise, retreat must be specified to
  4020. give a maximum number of characters to look back from
  4021. the current parse position for a lookbehind match.
  4022. Example::
  4023. # VB-style variable names with type prefixes
  4024. int_var = PrecededBy("#") + pyparsing_common.identifier
  4025. str_var = PrecededBy("$") + pyparsing_common.identifier
  4026. """
  4027. def __init__(
  4028. self, expr: Union[ParserElement, str], retreat: typing.Optional[int] = None
  4029. ):
  4030. super().__init__(expr)
  4031. self.expr = self.expr().leave_whitespace()
  4032. self.mayReturnEmpty = True
  4033. self.mayIndexError = False
  4034. self.exact = False
  4035. if isinstance(expr, str_type):
  4036. expr = typing.cast(str, expr)
  4037. retreat = len(expr)
  4038. self.exact = True
  4039. elif isinstance(expr, (Literal, Keyword)):
  4040. retreat = expr.matchLen
  4041. self.exact = True
  4042. elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:
  4043. retreat = expr.maxLen
  4044. self.exact = True
  4045. elif isinstance(expr, PositionToken):
  4046. retreat = 0
  4047. self.exact = True
  4048. self.retreat = retreat
  4049. self.errmsg = "not preceded by " + str(expr)
  4050. self.skipWhitespace = False
  4051. self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))
  4052. def parseImpl(self, instring, loc=0, doActions=True):
  4053. if self.exact:
  4054. if loc < self.retreat:
  4055. raise ParseException(instring, loc, self.errmsg)
  4056. start = loc - self.retreat
  4057. _, ret = self.expr._parse(instring, start)
  4058. else:
  4059. # retreat specified a maximum lookbehind window, iterate
  4060. test_expr = self.expr + StringEnd()
  4061. instring_slice = instring[max(0, loc - self.retreat) : loc]
  4062. last_expr = ParseException(instring, loc, self.errmsg)
  4063. for offset in range(1, min(loc, self.retreat + 1) + 1):
  4064. try:
  4065. # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))
  4066. _, ret = test_expr._parse(
  4067. instring_slice, len(instring_slice) - offset
  4068. )
  4069. except ParseBaseException as pbe:
  4070. last_expr = pbe
  4071. else:
  4072. break
  4073. else:
  4074. raise last_expr
  4075. return loc, ret
  4076. class Located(ParseElementEnhance):
  4077. """
  4078. Decorates a returned token with its starting and ending
  4079. locations in the input string.
  4080. This helper adds the following results names:
  4081. - ``locn_start`` - location where matched expression begins
  4082. - ``locn_end`` - location where matched expression ends
  4083. - ``value`` - the actual parsed results
  4084. Be careful if the input text contains ``<TAB>`` characters, you
  4085. may want to call :class:`ParserElement.parse_with_tabs`
  4086. Example::
  4087. wd = Word(alphas)
  4088. for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"):
  4089. print(match)
  4090. prints::
  4091. [0, ['ljsdf'], 5]
  4092. [8, ['lksdjjf'], 15]
  4093. [18, ['lkkjj'], 23]
  4094. """
  4095. def parseImpl(self, instring, loc, doActions=True):
  4096. start = loc
  4097. loc, tokens = self.expr._parse(instring, start, doActions, callPreParse=False)
  4098. ret_tokens = ParseResults([start, tokens, loc])
  4099. ret_tokens["locn_start"] = start
  4100. ret_tokens["value"] = tokens
  4101. ret_tokens["locn_end"] = loc
  4102. if self.resultsName:
  4103. # must return as a list, so that the name will be attached to the complete group
  4104. return loc, [ret_tokens]
  4105. else:
  4106. return loc, ret_tokens
  4107. class NotAny(ParseElementEnhance):
  4108. """
  4109. Lookahead to disallow matching with the given parse expression.
  4110. ``NotAny`` does *not* advance the parsing position within the
  4111. input string, it only verifies that the specified parse expression
  4112. does *not* match at the current position. Also, ``NotAny`` does
  4113. *not* skip over leading whitespace. ``NotAny`` always returns
  4114. a null token list. May be constructed using the ``'~'`` operator.
  4115. Example::
  4116. AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split())
  4117. # take care not to mistake keywords for identifiers
  4118. ident = ~(AND | OR | NOT) + Word(alphas)
  4119. boolean_term = Opt(NOT) + ident
  4120. # very crude boolean expression - to support parenthesis groups and
  4121. # operation hierarchy, use infix_notation
  4122. boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...]
  4123. # integers that are followed by "." are actually floats
  4124. integer = Word(nums) + ~Char(".")
  4125. """
  4126. def __init__(self, expr: Union[ParserElement, str]):
  4127. super().__init__(expr)
  4128. # do NOT use self.leave_whitespace(), don't want to propagate to exprs
  4129. # self.leave_whitespace()
  4130. self.skipWhitespace = False
  4131. self.mayReturnEmpty = True
  4132. self.errmsg = "Found unwanted token, " + str(self.expr)
  4133. def parseImpl(self, instring, loc, doActions=True):
  4134. if self.expr.can_parse_next(instring, loc, do_actions=doActions):
  4135. raise ParseException(instring, loc, self.errmsg, self)
  4136. return loc, []
  4137. def _generateDefaultName(self) -> str:
  4138. return "~{" + str(self.expr) + "}"
  4139. class _MultipleMatch(ParseElementEnhance):
  4140. def __init__(
  4141. self,
  4142. expr: Union[str, ParserElement],
  4143. stop_on: typing.Optional[Union[ParserElement, str]] = None,
  4144. *,
  4145. stopOn: typing.Optional[Union[ParserElement, str]] = None,
  4146. ):
  4147. super().__init__(expr)
  4148. stopOn = stopOn or stop_on
  4149. self.saveAsList = True
  4150. ender = stopOn
  4151. if isinstance(ender, str_type):
  4152. ender = self._literalStringClass(ender)
  4153. self.stopOn(ender)
  4154. def stopOn(self, ender) -> ParserElement:
  4155. if isinstance(ender, str_type):
  4156. ender = self._literalStringClass(ender)
  4157. self.not_ender = ~ender if ender is not None else None
  4158. return self
  4159. def parseImpl(self, instring, loc, doActions=True):
  4160. self_expr_parse = self.expr._parse
  4161. self_skip_ignorables = self._skipIgnorables
  4162. check_ender = self.not_ender is not None
  4163. if check_ender:
  4164. try_not_ender = self.not_ender.try_parse
  4165. # must be at least one (but first see if we are the stopOn sentinel;
  4166. # if so, fail)
  4167. if check_ender:
  4168. try_not_ender(instring, loc)
  4169. loc, tokens = self_expr_parse(instring, loc, doActions)
  4170. try:
  4171. hasIgnoreExprs = not not self.ignoreExprs
  4172. while 1:
  4173. if check_ender:
  4174. try_not_ender(instring, loc)
  4175. if hasIgnoreExprs:
  4176. preloc = self_skip_ignorables(instring, loc)
  4177. else:
  4178. preloc = loc
  4179. loc, tmptokens = self_expr_parse(instring, preloc, doActions)
  4180. tokens += tmptokens
  4181. except (ParseException, IndexError):
  4182. pass
  4183. return loc, tokens
  4184. def _setResultsName(self, name, listAllMatches=False):
  4185. if (
  4186. __diag__.warn_ungrouped_named_tokens_in_collection
  4187. and Diagnostics.warn_ungrouped_named_tokens_in_collection
  4188. not in self.suppress_warnings_
  4189. ):
  4190. for e in [self.expr] + self.expr.recurse():
  4191. if (
  4192. isinstance(e, ParserElement)
  4193. and e.resultsName
  4194. and Diagnostics.warn_ungrouped_named_tokens_in_collection
  4195. not in e.suppress_warnings_
  4196. ):
  4197. warnings.warn(
  4198. "{}: setting results name {!r} on {} expression "
  4199. "collides with {!r} on contained expression".format(
  4200. "warn_ungrouped_named_tokens_in_collection",
  4201. name,
  4202. type(self).__name__,
  4203. e.resultsName,
  4204. ),
  4205. stacklevel=3,
  4206. )
  4207. return super()._setResultsName(name, listAllMatches)
  4208. class OneOrMore(_MultipleMatch):
  4209. """
  4210. Repetition of one or more of the given expression.
  4211. Parameters:
  4212. - ``expr`` - expression that must match one or more times
  4213. - ``stop_on`` - (default= ``None``) - expression for a terminating sentinel
  4214. (only required if the sentinel would ordinarily match the repetition
  4215. expression)
  4216. Example::
  4217. data_word = Word(alphas)
  4218. label = data_word + FollowedBy(':')
  4219. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join))
  4220. text = "shape: SQUARE posn: upper left color: BLACK"
  4221. attr_expr[1, ...].parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]
  4222. # use stop_on attribute for OneOrMore to avoid reading label string as part of the data
  4223. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
  4224. OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
  4225. # could also be written as
  4226. (attr_expr * (1,)).parse_string(text).pprint()
  4227. """
  4228. def _generateDefaultName(self) -> str:
  4229. return "{" + str(self.expr) + "}..."
  4230. class ZeroOrMore(_MultipleMatch):
  4231. """
  4232. Optional repetition of zero or more of the given expression.
  4233. Parameters:
  4234. - ``expr`` - expression that must match zero or more times
  4235. - ``stop_on`` - expression for a terminating sentinel
  4236. (only required if the sentinel would ordinarily match the repetition
  4237. expression) - (default= ``None``)
  4238. Example: similar to :class:`OneOrMore`
  4239. """
  4240. def __init__(
  4241. self,
  4242. expr: Union[str, ParserElement],
  4243. stop_on: typing.Optional[Union[ParserElement, str]] = None,
  4244. *,
  4245. stopOn: typing.Optional[Union[ParserElement, str]] = None,
  4246. ):
  4247. super().__init__(expr, stopOn=stopOn or stop_on)
  4248. self.mayReturnEmpty = True
  4249. def parseImpl(self, instring, loc, doActions=True):
  4250. try:
  4251. return super().parseImpl(instring, loc, doActions)
  4252. except (ParseException, IndexError):
  4253. return loc, ParseResults([], name=self.resultsName)
  4254. def _generateDefaultName(self) -> str:
  4255. return "[" + str(self.expr) + "]..."
  4256. class DelimitedList(ParseElementEnhance):
  4257. def __init__(
  4258. self,
  4259. expr: Union[str, ParserElement],
  4260. delim: Union[str, ParserElement] = ",",
  4261. combine: bool = False,
  4262. min: typing.Optional[int] = None,
  4263. max: typing.Optional[int] = None,
  4264. *,
  4265. allow_trailing_delim: bool = False,
  4266. ):
  4267. """Helper to define a delimited list of expressions - the delimiter
  4268. defaults to ','. By default, the list elements and delimiters can
  4269. have intervening whitespace, and comments, but this can be
  4270. overridden by passing ``combine=True`` in the constructor. If
  4271. ``combine`` is set to ``True``, the matching tokens are
  4272. returned as a single token string, with the delimiters included;
  4273. otherwise, the matching tokens are returned as a list of tokens,
  4274. with the delimiters suppressed.
  4275. If ``allow_trailing_delim`` is set to True, then the list may end with
  4276. a delimiter.
  4277. Example::
  4278. DelimitedList(Word(alphas)).parse_string("aa,bb,cc") # -> ['aa', 'bb', 'cc']
  4279. DelimitedList(Word(hexnums), delim=':', combine=True).parse_string("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
  4280. """
  4281. if isinstance(expr, str_type):
  4282. expr = ParserElement._literalStringClass(expr)
  4283. expr = typing.cast(ParserElement, expr)
  4284. if min is not None:
  4285. if min < 1:
  4286. raise ValueError("min must be greater than 0")
  4287. if max is not None:
  4288. if min is not None and max < min:
  4289. raise ValueError("max must be greater than, or equal to min")
  4290. self.content = expr
  4291. self.raw_delim = str(delim)
  4292. self.delim = delim
  4293. self.combine = combine
  4294. if not combine:
  4295. self.delim = Suppress(delim)
  4296. self.min = min or 1
  4297. self.max = max
  4298. self.allow_trailing_delim = allow_trailing_delim
  4299. delim_list_expr = self.content + (self.delim + self.content) * (
  4300. self.min - 1,
  4301. None if self.max is None else self.max - 1,
  4302. )
  4303. if self.allow_trailing_delim:
  4304. delim_list_expr += Opt(self.delim)
  4305. if self.combine:
  4306. delim_list_expr = Combine(delim_list_expr)
  4307. super().__init__(delim_list_expr, savelist=True)
  4308. def _generateDefaultName(self) -> str:
  4309. return "{0} [{1} {0}]...".format(self.content.streamline(), self.raw_delim)
  4310. class _NullToken:
  4311. def __bool__(self):
  4312. return False
  4313. def __str__(self):
  4314. return ""
  4315. class Opt(ParseElementEnhance):
  4316. """
  4317. Optional matching of the given expression.
  4318. Parameters:
  4319. - ``expr`` - expression that must match zero or more times
  4320. - ``default`` (optional) - value to be returned if the optional expression is not found.
  4321. Example::
  4322. # US postal code can be a 5-digit zip, plus optional 4-digit qualifier
  4323. zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))
  4324. zip.run_tests('''
  4325. # traditional ZIP code
  4326. 12345
  4327. # ZIP+4 form
  4328. 12101-0001
  4329. # invalid ZIP
  4330. 98765-
  4331. ''')
  4332. prints::
  4333. # traditional ZIP code
  4334. 12345
  4335. ['12345']
  4336. # ZIP+4 form
  4337. 12101-0001
  4338. ['12101-0001']
  4339. # invalid ZIP
  4340. 98765-
  4341. ^
  4342. FAIL: Expected end of text (at char 5), (line:1, col:6)
  4343. """
  4344. __optionalNotMatched = _NullToken()
  4345. def __init__(
  4346. self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched
  4347. ):
  4348. super().__init__(expr, savelist=False)
  4349. self.saveAsList = self.expr.saveAsList
  4350. self.defaultValue = default
  4351. self.mayReturnEmpty = True
  4352. def parseImpl(self, instring, loc, doActions=True):
  4353. self_expr = self.expr
  4354. try:
  4355. loc, tokens = self_expr._parse(instring, loc, doActions, callPreParse=False)
  4356. except (ParseException, IndexError):
  4357. default_value = self.defaultValue
  4358. if default_value is not self.__optionalNotMatched:
  4359. if self_expr.resultsName:
  4360. tokens = ParseResults([default_value])
  4361. tokens[self_expr.resultsName] = default_value
  4362. else:
  4363. tokens = [default_value]
  4364. else:
  4365. tokens = []
  4366. return loc, tokens
  4367. def _generateDefaultName(self) -> str:
  4368. inner = str(self.expr)
  4369. # strip off redundant inner {}'s
  4370. while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
  4371. inner = inner[1:-1]
  4372. return "[" + inner + "]"
  4373. Optional = Opt
  4374. class SkipTo(ParseElementEnhance):
  4375. """
  4376. Token for skipping over all undefined text until the matched
  4377. expression is found.
  4378. Parameters:
  4379. - ``expr`` - target expression marking the end of the data to be skipped
  4380. - ``include`` - if ``True``, the target expression is also parsed
  4381. (the skipped text and target expression are returned as a 2-element
  4382. list) (default= ``False``).
  4383. - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and
  4384. comments) that might contain false matches to the target expression
  4385. - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be
  4386. included in the skipped test; if found before the target expression is found,
  4387. the :class:`SkipTo` is not a match
  4388. Example::
  4389. report = '''
  4390. Outstanding Issues Report - 1 Jan 2000
  4391. # | Severity | Description | Days Open
  4392. -----+----------+-------------------------------------------+-----------
  4393. 101 | Critical | Intermittent system crash | 6
  4394. 94 | Cosmetic | Spelling error on Login ('log|n') | 14
  4395. 79 | Minor | System slow when running too many reports | 47
  4396. '''
  4397. integer = Word(nums)
  4398. SEP = Suppress('|')
  4399. # use SkipTo to simply match everything up until the next SEP
  4400. # - ignore quoted strings, so that a '|' character inside a quoted string does not match
  4401. # - parse action will call token.strip() for each matched token, i.e., the description body
  4402. string_data = SkipTo(SEP, ignore=quoted_string)
  4403. string_data.set_parse_action(token_map(str.strip))
  4404. ticket_expr = (integer("issue_num") + SEP
  4405. + string_data("sev") + SEP
  4406. + string_data("desc") + SEP
  4407. + integer("days_open"))
  4408. for tkt in ticket_expr.search_string(report):
  4409. print tkt.dump()
  4410. prints::
  4411. ['101', 'Critical', 'Intermittent system crash', '6']
  4412. - days_open: '6'
  4413. - desc: 'Intermittent system crash'
  4414. - issue_num: '101'
  4415. - sev: 'Critical'
  4416. ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
  4417. - days_open: '14'
  4418. - desc: "Spelling error on Login ('log|n')"
  4419. - issue_num: '94'
  4420. - sev: 'Cosmetic'
  4421. ['79', 'Minor', 'System slow when running too many reports', '47']
  4422. - days_open: '47'
  4423. - desc: 'System slow when running too many reports'
  4424. - issue_num: '79'
  4425. - sev: 'Minor'
  4426. """
  4427. def __init__(
  4428. self,
  4429. other: Union[ParserElement, str],
  4430. include: bool = False,
  4431. ignore: typing.Optional[Union[ParserElement, str]] = None,
  4432. fail_on: typing.Optional[Union[ParserElement, str]] = None,
  4433. *,
  4434. failOn: typing.Optional[Union[ParserElement, str]] = None,
  4435. ):
  4436. super().__init__(other)
  4437. failOn = failOn or fail_on
  4438. self.ignoreExpr = ignore
  4439. self.mayReturnEmpty = True
  4440. self.mayIndexError = False
  4441. self.includeMatch = include
  4442. self.saveAsList = False
  4443. if isinstance(failOn, str_type):
  4444. self.failOn = self._literalStringClass(failOn)
  4445. else:
  4446. self.failOn = failOn
  4447. self.errmsg = "No match found for " + str(self.expr)
  4448. self.ignorer = Empty().leave_whitespace()
  4449. self._update_ignorer()
  4450. def _update_ignorer(self):
  4451. # rebuild internal ignore expr from current ignore exprs and assigned ignoreExpr
  4452. self.ignorer.ignoreExprs.clear()
  4453. for e in self.expr.ignoreExprs:
  4454. self.ignorer.ignore(e)
  4455. if self.ignoreExpr:
  4456. self.ignorer.ignore(self.ignoreExpr)
  4457. def ignore(self, expr):
  4458. super().ignore(expr)
  4459. self._update_ignorer()
  4460. def parseImpl(self, instring, loc, doActions=True):
  4461. startloc = loc
  4462. instrlen = len(instring)
  4463. self_expr_parse = self.expr._parse
  4464. self_failOn_canParseNext = (
  4465. self.failOn.canParseNext if self.failOn is not None else None
  4466. )
  4467. ignorer_try_parse = self.ignorer.try_parse if self.ignorer.ignoreExprs else None
  4468. tmploc = loc
  4469. while tmploc <= instrlen:
  4470. if self_failOn_canParseNext is not None:
  4471. # break if failOn expression matches
  4472. if self_failOn_canParseNext(instring, tmploc):
  4473. break
  4474. if ignorer_try_parse is not None:
  4475. # advance past ignore expressions
  4476. prev_tmploc = tmploc
  4477. while 1:
  4478. try:
  4479. tmploc = ignorer_try_parse(instring, tmploc)
  4480. except ParseBaseException:
  4481. break
  4482. # see if all ignorers matched, but didn't actually ignore anything
  4483. if tmploc == prev_tmploc:
  4484. break
  4485. prev_tmploc = tmploc
  4486. try:
  4487. self_expr_parse(instring, tmploc, doActions=False, callPreParse=False)
  4488. except (ParseException, IndexError):
  4489. # no match, advance loc in string
  4490. tmploc += 1
  4491. else:
  4492. # matched skipto expr, done
  4493. break
  4494. else:
  4495. # ran off the end of the input string without matching skipto expr, fail
  4496. raise ParseException(instring, loc, self.errmsg, self)
  4497. # build up return values
  4498. loc = tmploc
  4499. skiptext = instring[startloc:loc]
  4500. skipresult = ParseResults(skiptext)
  4501. if self.includeMatch:
  4502. loc, mat = self_expr_parse(instring, loc, doActions, callPreParse=False)
  4503. skipresult += mat
  4504. return loc, skipresult
  4505. class Forward(ParseElementEnhance):
  4506. """
  4507. Forward declaration of an expression to be defined later -
  4508. used for recursive grammars, such as algebraic infix notation.
  4509. When the expression is known, it is assigned to the ``Forward``
  4510. variable using the ``'<<'`` operator.
  4511. Note: take care when assigning to ``Forward`` not to overlook
  4512. precedence of operators.
  4513. Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that::
  4514. fwd_expr << a | b | c
  4515. will actually be evaluated as::
  4516. (fwd_expr << a) | b | c
  4517. thereby leaving b and c out as parseable alternatives. It is recommended that you
  4518. explicitly group the values inserted into the ``Forward``::
  4519. fwd_expr << (a | b | c)
  4520. Converting to use the ``'<<='`` operator instead will avoid this problem.
  4521. See :class:`ParseResults.pprint` for an example of a recursive
  4522. parser created using ``Forward``.
  4523. """
  4524. def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None):
  4525. self.caller_frame = traceback.extract_stack(limit=2)[0]
  4526. super().__init__(other, savelist=False) # type: ignore[arg-type]
  4527. self.lshift_line = None
  4528. def __lshift__(self, other) -> "Forward":
  4529. if hasattr(self, "caller_frame"):
  4530. del self.caller_frame
  4531. if isinstance(other, str_type):
  4532. other = self._literalStringClass(other)
  4533. if not isinstance(other, ParserElement):
  4534. return NotImplemented
  4535. self.expr = other
  4536. self.streamlined = other.streamlined
  4537. self.mayIndexError = self.expr.mayIndexError
  4538. self.mayReturnEmpty = self.expr.mayReturnEmpty
  4539. self.set_whitespace_chars(
  4540. self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars
  4541. )
  4542. self.skipWhitespace = self.expr.skipWhitespace
  4543. self.saveAsList = self.expr.saveAsList
  4544. self.ignoreExprs.extend(self.expr.ignoreExprs)
  4545. self.lshift_line = traceback.extract_stack(limit=2)[-2] # type: ignore[assignment]
  4546. return self
  4547. def __ilshift__(self, other) -> "Forward":
  4548. if not isinstance(other, ParserElement):
  4549. return NotImplemented
  4550. return self << other
  4551. def __or__(self, other) -> "ParserElement":
  4552. caller_line = traceback.extract_stack(limit=2)[-2]
  4553. if (
  4554. __diag__.warn_on_match_first_with_lshift_operator
  4555. and caller_line == self.lshift_line
  4556. and Diagnostics.warn_on_match_first_with_lshift_operator
  4557. not in self.suppress_warnings_
  4558. ):
  4559. warnings.warn(
  4560. "using '<<' operator with '|' is probably an error, use '<<='",
  4561. stacklevel=2,
  4562. )
  4563. ret = super().__or__(other)
  4564. return ret
  4565. def __del__(self):
  4566. # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<'
  4567. if (
  4568. self.expr is None
  4569. and __diag__.warn_on_assignment_to_Forward
  4570. and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_
  4571. ):
  4572. warnings.warn_explicit(
  4573. "Forward defined here but no expression attached later using '<<=' or '<<'",
  4574. UserWarning,
  4575. filename=self.caller_frame.filename,
  4576. lineno=self.caller_frame.lineno,
  4577. )
  4578. def parseImpl(self, instring, loc, doActions=True):
  4579. if (
  4580. self.expr is None
  4581. and __diag__.warn_on_parse_using_empty_Forward
  4582. and Diagnostics.warn_on_parse_using_empty_Forward
  4583. not in self.suppress_warnings_
  4584. ):
  4585. # walk stack until parse_string, scan_string, search_string, or transform_string is found
  4586. parse_fns = (
  4587. "parse_string",
  4588. "scan_string",
  4589. "search_string",
  4590. "transform_string",
  4591. )
  4592. tb = traceback.extract_stack(limit=200)
  4593. for i, frm in enumerate(reversed(tb), start=1):
  4594. if frm.name in parse_fns:
  4595. stacklevel = i + 1
  4596. break
  4597. else:
  4598. stacklevel = 2
  4599. warnings.warn(
  4600. "Forward expression was never assigned a value, will not parse any input",
  4601. stacklevel=stacklevel,
  4602. )
  4603. if not ParserElement._left_recursion_enabled:
  4604. return super().parseImpl(instring, loc, doActions)
  4605. # ## Bounded Recursion algorithm ##
  4606. # Recursion only needs to be processed at ``Forward`` elements, since they are
  4607. # the only ones that can actually refer to themselves. The general idea is
  4608. # to handle recursion stepwise: We start at no recursion, then recurse once,
  4609. # recurse twice, ..., until more recursion offers no benefit (we hit the bound).
  4610. #
  4611. # The "trick" here is that each ``Forward`` gets evaluated in two contexts
  4612. # - to *match* a specific recursion level, and
  4613. # - to *search* the bounded recursion level
  4614. # and the two run concurrently. The *search* must *match* each recursion level
  4615. # to find the best possible match. This is handled by a memo table, which
  4616. # provides the previous match to the next level match attempt.
  4617. #
  4618. # See also "Left Recursion in Parsing Expression Grammars", Medeiros et al.
  4619. #
  4620. # There is a complication since we not only *parse* but also *transform* via
  4621. # actions: We do not want to run the actions too often while expanding. Thus,
  4622. # we expand using `doActions=False` and only run `doActions=True` if the next
  4623. # recursion level is acceptable.
  4624. with ParserElement.recursion_lock:
  4625. memo = ParserElement.recursion_memos
  4626. try:
  4627. # we are parsing at a specific recursion expansion - use it as-is
  4628. prev_loc, prev_result = memo[loc, self, doActions]
  4629. if isinstance(prev_result, Exception):
  4630. raise prev_result
  4631. return prev_loc, prev_result.copy()
  4632. except KeyError:
  4633. act_key = (loc, self, True)
  4634. peek_key = (loc, self, False)
  4635. # we are searching for the best recursion expansion - keep on improving
  4636. # both `doActions` cases must be tracked separately here!
  4637. prev_loc, prev_peek = memo[peek_key] = (
  4638. loc - 1,
  4639. ParseException(
  4640. instring, loc, "Forward recursion without base case", self
  4641. ),
  4642. )
  4643. if doActions:
  4644. memo[act_key] = memo[peek_key]
  4645. while True:
  4646. try:
  4647. new_loc, new_peek = super().parseImpl(instring, loc, False)
  4648. except ParseException:
  4649. # we failed before getting any match – do not hide the error
  4650. if isinstance(prev_peek, Exception):
  4651. raise
  4652. new_loc, new_peek = prev_loc, prev_peek
  4653. # the match did not get better: we are done
  4654. if new_loc <= prev_loc:
  4655. if doActions:
  4656. # replace the match for doActions=False as well,
  4657. # in case the action did backtrack
  4658. prev_loc, prev_result = memo[peek_key] = memo[act_key]
  4659. del memo[peek_key], memo[act_key]
  4660. return prev_loc, prev_result.copy()
  4661. del memo[peek_key]
  4662. return prev_loc, prev_peek.copy()
  4663. # the match did get better: see if we can improve further
  4664. else:
  4665. if doActions:
  4666. try:
  4667. memo[act_key] = super().parseImpl(instring, loc, True)
  4668. except ParseException as e:
  4669. memo[peek_key] = memo[act_key] = (new_loc, e)
  4670. raise
  4671. prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek
  4672. def leave_whitespace(self, recursive: bool = True) -> ParserElement:
  4673. self.skipWhitespace = False
  4674. return self
  4675. def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
  4676. self.skipWhitespace = True
  4677. return self
  4678. def streamline(self) -> ParserElement:
  4679. if not self.streamlined:
  4680. self.streamlined = True
  4681. if self.expr is not None:
  4682. self.expr.streamline()
  4683. return self
  4684. def validate(self, validateTrace=None) -> None:
  4685. warnings.warn(
  4686. "ParserElement.validate() is deprecated, and should not be used to check for left recursion",
  4687. DeprecationWarning,
  4688. stacklevel=2,
  4689. )
  4690. if validateTrace is None:
  4691. validateTrace = []
  4692. if self not in validateTrace:
  4693. tmp = validateTrace[:] + [self]
  4694. if self.expr is not None:
  4695. self.expr.validate(tmp)
  4696. self._checkRecursion([])
  4697. def _generateDefaultName(self) -> str:
  4698. # Avoid infinite recursion by setting a temporary _defaultName
  4699. self._defaultName = ": ..."
  4700. # Use the string representation of main expression.
  4701. retString = "..."
  4702. try:
  4703. if self.expr is not None:
  4704. retString = str(self.expr)[:1000]
  4705. else:
  4706. retString = "None"
  4707. finally:
  4708. return self.__class__.__name__ + ": " + retString
  4709. def copy(self) -> ParserElement:
  4710. if self.expr is not None:
  4711. return super().copy()
  4712. else:
  4713. ret = Forward()
  4714. ret <<= self
  4715. return ret
  4716. def _setResultsName(self, name, list_all_matches=False):
  4717. if (
  4718. __diag__.warn_name_set_on_empty_Forward
  4719. and Diagnostics.warn_name_set_on_empty_Forward
  4720. not in self.suppress_warnings_
  4721. ):
  4722. if self.expr is None:
  4723. warnings.warn(
  4724. "{}: setting results name {!r} on {} expression "
  4725. "that has no contained expression".format(
  4726. "warn_name_set_on_empty_Forward", name, type(self).__name__
  4727. ),
  4728. stacklevel=3,
  4729. )
  4730. return super()._setResultsName(name, list_all_matches)
  4731. # Compatibility synonyms
  4732. # fmt: off
  4733. @replaced_by_pep8(leave_whitespace)
  4734. def leaveWhitespace(self): ...
  4735. @replaced_by_pep8(ignore_whitespace)
  4736. def ignoreWhitespace(self): ...
  4737. # fmt: on
  4738. class TokenConverter(ParseElementEnhance):
  4739. """
  4740. Abstract subclass of :class:`ParseExpression`, for converting parsed results.
  4741. """
  4742. def __init__(self, expr: Union[ParserElement, str], savelist=False):
  4743. super().__init__(expr) # , savelist)
  4744. self.saveAsList = False
  4745. class Combine(TokenConverter):
  4746. """Converter to concatenate all matching tokens to a single string.
  4747. By default, the matching patterns must also be contiguous in the
  4748. input string; this can be disabled by specifying
  4749. ``'adjacent=False'`` in the constructor.
  4750. Example::
  4751. real = Word(nums) + '.' + Word(nums)
  4752. print(real.parse_string('3.1416')) # -> ['3', '.', '1416']
  4753. # will also erroneously match the following
  4754. print(real.parse_string('3. 1416')) # -> ['3', '.', '1416']
  4755. real = Combine(Word(nums) + '.' + Word(nums))
  4756. print(real.parse_string('3.1416')) # -> ['3.1416']
  4757. # no match when there are internal spaces
  4758. print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...)
  4759. """
  4760. def __init__(
  4761. self,
  4762. expr: ParserElement,
  4763. join_string: str = "",
  4764. adjacent: bool = True,
  4765. *,
  4766. joinString: typing.Optional[str] = None,
  4767. ):
  4768. super().__init__(expr)
  4769. joinString = joinString if joinString is not None else join_string
  4770. # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
  4771. if adjacent:
  4772. self.leave_whitespace()
  4773. self.adjacent = adjacent
  4774. self.skipWhitespace = True
  4775. self.joinString = joinString
  4776. self.callPreparse = True
  4777. def ignore(self, other) -> ParserElement:
  4778. if self.adjacent:
  4779. ParserElement.ignore(self, other)
  4780. else:
  4781. super().ignore(other)
  4782. return self
  4783. def postParse(self, instring, loc, tokenlist):
  4784. retToks = tokenlist.copy()
  4785. del retToks[:]
  4786. retToks += ParseResults(
  4787. ["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults
  4788. )
  4789. if self.resultsName and retToks.haskeys():
  4790. return [retToks]
  4791. else:
  4792. return retToks
  4793. class Group(TokenConverter):
  4794. """Converter to return the matched tokens as a list - useful for
  4795. returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.
  4796. The optional ``aslist`` argument when set to True will return the
  4797. parsed tokens as a Python list instead of a pyparsing ParseResults.
  4798. Example::
  4799. ident = Word(alphas)
  4800. num = Word(nums)
  4801. term = ident | num
  4802. func = ident + Opt(DelimitedList(term))
  4803. print(func.parse_string("fn a, b, 100"))
  4804. # -> ['fn', 'a', 'b', '100']
  4805. func = ident + Group(Opt(DelimitedList(term)))
  4806. print(func.parse_string("fn a, b, 100"))
  4807. # -> ['fn', ['a', 'b', '100']]
  4808. """
  4809. def __init__(self, expr: ParserElement, aslist: bool = False):
  4810. super().__init__(expr)
  4811. self.saveAsList = True
  4812. self._asPythonList = aslist
  4813. def postParse(self, instring, loc, tokenlist):
  4814. if self._asPythonList:
  4815. return ParseResults.List(
  4816. tokenlist.asList()
  4817. if isinstance(tokenlist, ParseResults)
  4818. else list(tokenlist)
  4819. )
  4820. else:
  4821. return [tokenlist]
  4822. class Dict(TokenConverter):
  4823. """Converter to return a repetitive expression as a list, but also
  4824. as a dictionary. Each element can also be referenced using the first
  4825. token in the expression as its key. Useful for tabular report
  4826. scraping when the first column can be used as a item key.
  4827. The optional ``asdict`` argument when set to True will return the
  4828. parsed tokens as a Python dict instead of a pyparsing ParseResults.
  4829. Example::
  4830. data_word = Word(alphas)
  4831. label = data_word + FollowedBy(':')
  4832. text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
  4833. attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
  4834. # print attributes as plain groups
  4835. print(attr_expr[1, ...].parse_string(text).dump())
  4836. # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names
  4837. result = Dict(Group(attr_expr)[1, ...]).parse_string(text)
  4838. print(result.dump())
  4839. # access named fields as dict entries, or output as dict
  4840. print(result['shape'])
  4841. print(result.as_dict())
  4842. prints::
  4843. ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
  4844. [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
  4845. - color: 'light blue'
  4846. - posn: 'upper left'
  4847. - shape: 'SQUARE'
  4848. - texture: 'burlap'
  4849. SQUARE
  4850. {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
  4851. See more examples at :class:`ParseResults` of accessing fields by results name.
  4852. """
  4853. def __init__(self, expr: ParserElement, asdict: bool = False):
  4854. super().__init__(expr)
  4855. self.saveAsList = True
  4856. self._asPythonDict = asdict
  4857. def postParse(self, instring, loc, tokenlist):
  4858. for i, tok in enumerate(tokenlist):
  4859. if len(tok) == 0:
  4860. continue
  4861. ikey = tok[0]
  4862. if isinstance(ikey, int):
  4863. ikey = str(ikey).strip()
  4864. if len(tok) == 1:
  4865. tokenlist[ikey] = _ParseResultsWithOffset("", i)
  4866. elif len(tok) == 2 and not isinstance(tok[1], ParseResults):
  4867. tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)
  4868. else:
  4869. try:
  4870. dictvalue = tok.copy() # ParseResults(i)
  4871. except Exception:
  4872. exc = TypeError(
  4873. "could not extract dict values from parsed results"
  4874. " - Dict expression must contain Grouped expressions"
  4875. )
  4876. raise exc from None
  4877. del dictvalue[0]
  4878. if len(dictvalue) != 1 or (
  4879. isinstance(dictvalue, ParseResults) and dictvalue.haskeys()
  4880. ):
  4881. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)
  4882. else:
  4883. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)
  4884. if self._asPythonDict:
  4885. return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()
  4886. else:
  4887. return [tokenlist] if self.resultsName else tokenlist
  4888. class Suppress(TokenConverter):
  4889. """Converter for ignoring the results of a parsed expression.
  4890. Example::
  4891. source = "a, b, c,d"
  4892. wd = Word(alphas)
  4893. wd_list1 = wd + (',' + wd)[...]
  4894. print(wd_list1.parse_string(source))
  4895. # often, delimiters that are useful during parsing are just in the
  4896. # way afterward - use Suppress to keep them out of the parsed output
  4897. wd_list2 = wd + (Suppress(',') + wd)[...]
  4898. print(wd_list2.parse_string(source))
  4899. # Skipped text (using '...') can be suppressed as well
  4900. source = "lead in START relevant text END trailing text"
  4901. start_marker = Keyword("START")
  4902. end_marker = Keyword("END")
  4903. find_body = Suppress(...) + start_marker + ... + end_marker
  4904. print(find_body.parse_string(source)
  4905. prints::
  4906. ['a', ',', 'b', ',', 'c', ',', 'd']
  4907. ['a', 'b', 'c', 'd']
  4908. ['START', 'relevant text ', 'END']
  4909. (See also :class:`DelimitedList`.)
  4910. """
  4911. def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):
  4912. if expr is ...:
  4913. expr = _PendingSkip(NoMatch())
  4914. super().__init__(expr)
  4915. def __add__(self, other) -> "ParserElement":
  4916. if isinstance(self.expr, _PendingSkip):
  4917. return Suppress(SkipTo(other)) + other
  4918. else:
  4919. return super().__add__(other)
  4920. def __sub__(self, other) -> "ParserElement":
  4921. if isinstance(self.expr, _PendingSkip):
  4922. return Suppress(SkipTo(other)) - other
  4923. else:
  4924. return super().__sub__(other)
  4925. def postParse(self, instring, loc, tokenlist):
  4926. return []
  4927. def suppress(self) -> ParserElement:
  4928. return self
  4929. def trace_parse_action(f: ParseAction) -> ParseAction:
  4930. """Decorator for debugging parse actions.
  4931. When the parse action is called, this decorator will print
  4932. ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
  4933. When the parse action completes, the decorator will print
  4934. ``"<<"`` followed by the returned value, or any exception that the parse action raised.
  4935. Example::
  4936. wd = Word(alphas)
  4937. @trace_parse_action
  4938. def remove_duplicate_chars(tokens):
  4939. return ''.join(sorted(set(''.join(tokens))))
  4940. wds = wd[1, ...].set_parse_action(remove_duplicate_chars)
  4941. print(wds.parse_string("slkdjs sld sldd sdlf sdljf"))
  4942. prints::
  4943. >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
  4944. <<leaving remove_duplicate_chars (ret: 'dfjkls')
  4945. ['dfjkls']
  4946. """
  4947. f = _trim_arity(f)
  4948. def z(*paArgs):
  4949. thisFunc = f.__name__
  4950. s, l, t = paArgs[-3:]
  4951. if len(paArgs) > 3:
  4952. thisFunc = paArgs[0].__class__.__name__ + "." + thisFunc
  4953. sys.stderr.write(f">>entering {thisFunc}(line: {line(l, s)!r}, {l}, {t!r})\n")
  4954. try:
  4955. ret = f(*paArgs)
  4956. except Exception as exc:
  4957. sys.stderr.write(f"<<leaving {thisFunc} (exception: {exc})\n")
  4958. raise
  4959. sys.stderr.write(f"<<leaving {thisFunc} (ret: {ret!r})\n")
  4960. return ret
  4961. z.__name__ = f.__name__
  4962. return z
  4963. # convenience constants for positional expressions
  4964. empty = Empty().set_name("empty")
  4965. line_start = LineStart().set_name("line_start")
  4966. line_end = LineEnd().set_name("line_end")
  4967. string_start = StringStart().set_name("string_start")
  4968. string_end = StringEnd().set_name("string_end")
  4969. _escapedPunc = Regex(r"\\[\\[\]\/\-\*\.\$\+\^\?()~ ]").set_parse_action(
  4970. lambda s, l, t: t[0][1]
  4971. )
  4972. _escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").set_parse_action(
  4973. lambda s, l, t: chr(int(t[0].lstrip(r"\0x"), 16))
  4974. )
  4975. _escapedOctChar = Regex(r"\\0[0-7]+").set_parse_action(
  4976. lambda s, l, t: chr(int(t[0][1:], 8))
  4977. )
  4978. _singleChar = (
  4979. _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r"\]", exact=1)
  4980. )
  4981. _charRange = Group(_singleChar + Suppress("-") + _singleChar)
  4982. _reBracketExpr = (
  4983. Literal("[")
  4984. + Opt("^").set_results_name("negate")
  4985. + Group(OneOrMore(_charRange | _singleChar)).set_results_name("body")
  4986. + Literal("]")
  4987. )
  4988. def srange(s: str) -> str:
  4989. r"""Helper to easily define string ranges for use in :class:`Word`
  4990. construction. Borrows syntax from regexp ``'[]'`` string range
  4991. definitions::
  4992. srange("[0-9]") -> "0123456789"
  4993. srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
  4994. srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
  4995. The input string must be enclosed in []'s, and the returned string
  4996. is the expanded character set joined into a single string. The
  4997. values enclosed in the []'s may be:
  4998. - a single character
  4999. - an escaped character with a leading backslash (such as ``\-``
  5000. or ``\]``)
  5001. - an escaped hex character with a leading ``'\x'``
  5002. (``\x21``, which is a ``'!'`` character) (``\0x##``
  5003. is also supported for backwards compatibility)
  5004. - an escaped octal character with a leading ``'\0'``
  5005. (``\041``, which is a ``'!'`` character)
  5006. - a range of any of the above, separated by a dash (``'a-z'``,
  5007. etc.)
  5008. - any combination of the above (``'aeiouy'``,
  5009. ``'a-zA-Z0-9_$'``, etc.)
  5010. """
  5011. _expanded = (
  5012. lambda p: p
  5013. if not isinstance(p, ParseResults)
  5014. else "".join(chr(c) for c in range(ord(p[0]), ord(p[1]) + 1))
  5015. )
  5016. try:
  5017. return "".join(_expanded(part) for part in _reBracketExpr.parse_string(s).body)
  5018. except Exception as e:
  5019. return ""
  5020. def token_map(func, *args) -> ParseAction:
  5021. """Helper to define a parse action by mapping a function to all
  5022. elements of a :class:`ParseResults` list. If any additional args are passed,
  5023. they are forwarded to the given function as additional arguments
  5024. after the token, as in
  5025. ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``,
  5026. which will convert the parsed data to an integer using base 16.
  5027. Example (compare the last to example in :class:`ParserElement.transform_string`::
  5028. hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16))
  5029. hex_ints.run_tests('''
  5030. 00 11 22 aa FF 0a 0d 1a
  5031. ''')
  5032. upperword = Word(alphas).set_parse_action(token_map(str.upper))
  5033. upperword[1, ...].run_tests('''
  5034. my kingdom for a horse
  5035. ''')
  5036. wd = Word(alphas).set_parse_action(token_map(str.title))
  5037. wd[1, ...].set_parse_action(' '.join).run_tests('''
  5038. now is the winter of our discontent made glorious summer by this sun of york
  5039. ''')
  5040. prints::
  5041. 00 11 22 aa FF 0a 0d 1a
  5042. [0, 17, 34, 170, 255, 10, 13, 26]
  5043. my kingdom for a horse
  5044. ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
  5045. now is the winter of our discontent made glorious summer by this sun of york
  5046. ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
  5047. """
  5048. def pa(s, l, t):
  5049. return [func(tokn, *args) for tokn in t]
  5050. func_name = getattr(func, "__name__", getattr(func, "__class__").__name__)
  5051. pa.__name__ = func_name
  5052. return pa
  5053. def autoname_elements() -> None:
  5054. """
  5055. Utility to simplify mass-naming of parser elements, for
  5056. generating railroad diagram with named subdiagrams.
  5057. """
  5058. calling_frame = sys._getframe().f_back
  5059. if calling_frame is None:
  5060. return
  5061. calling_frame = typing.cast(types.FrameType, calling_frame)
  5062. for name, var in calling_frame.f_locals.items():
  5063. if isinstance(var, ParserElement) and not var.customName:
  5064. var.set_name(name)
  5065. dbl_quoted_string = Combine(
  5066. Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"'
  5067. ).set_name("string enclosed in double quotes")
  5068. sgl_quoted_string = Combine(
  5069. Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'"
  5070. ).set_name("string enclosed in single quotes")
  5071. quoted_string = Combine(
  5072. (Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name(
  5073. "double quoted string"
  5074. )
  5075. | (Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name(
  5076. "single quoted string"
  5077. )
  5078. ).set_name("quoted string using single or double quotes")
  5079. python_quoted_string = Combine(
  5080. (Regex(r'"""(?:[^"\\]|""(?!")|"(?!"")|\\.)*', flags=re.MULTILINE) + '"""').set_name(
  5081. "multiline double quoted string"
  5082. )
  5083. ^ (
  5084. Regex(r"'''(?:[^'\\]|''(?!')|'(?!'')|\\.)*", flags=re.MULTILINE) + "'''"
  5085. ).set_name("multiline single quoted string")
  5086. ^ (Regex(r'"(?:[^"\n\r\\]|(?:\\")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name(
  5087. "double quoted string"
  5088. )
  5089. ^ (Regex(r"'(?:[^'\n\r\\]|(?:\\')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name(
  5090. "single quoted string"
  5091. )
  5092. ).set_name("Python quoted string")
  5093. unicode_string = Combine("u" + quoted_string.copy()).set_name("unicode string literal")
  5094. alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
  5095. punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
  5096. # build list of built-in expressions, for future reference if a global default value
  5097. # gets updated
  5098. _builtin_exprs: List[ParserElement] = [
  5099. v for v in vars().values() if isinstance(v, ParserElement)
  5100. ]
  5101. # backward compatibility names
  5102. # fmt: off
  5103. sglQuotedString = sgl_quoted_string
  5104. dblQuotedString = dbl_quoted_string
  5105. quotedString = quoted_string
  5106. unicodeString = unicode_string
  5107. lineStart = line_start
  5108. lineEnd = line_end
  5109. stringStart = string_start
  5110. stringEnd = string_end
  5111. @replaced_by_pep8(null_debug_action)
  5112. def nullDebugAction(): ...
  5113. @replaced_by_pep8(trace_parse_action)
  5114. def traceParseAction(): ...
  5115. @replaced_by_pep8(condition_as_parse_action)
  5116. def conditionAsParseAction(): ...
  5117. @replaced_by_pep8(token_map)
  5118. def tokenMap(): ...
  5119. # fmt: on