core.py 246 KB

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