core.py 208 KB

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