core.py 207 KB

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