You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pyparsing.py 257KB

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