core.py 246 KB

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