urn.lua 412 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078
  1. #!/usr/bin/env lua
  2. if not table.pack then table.pack = function(...) return { n = select("#", ...), ... } end end
  3. if not table.unpack then table.unpack = unpack end
  4. local load = load if _VERSION:find("5.1") then load = function(x, n, _, env) local f, e = loadstring(x, n) if not f then return f, e end if env then setfenv(f, env) end return f end end
  5. local _select, _unpack, _pack, _error = select, table.unpack, table.pack, error
  6. local _libs = {}
  7. local _2a_arguments_2a_1, _2b_1, _2d_1, _2e2e_1, _2f3d_1, _3c3d_1, _3c_1, _3d_1, _3e3d_1, _3e_1, addArgument_21_1, addParen1, any1, append_21_1, apply1, beginBlock_21_1, between_3f_1, builtin_3f_1, builtins1, caar1, cadr1, car1, child1, coloured1, compileBlock1, compileExpression1, concat2, constVal1, demandFailure1, display1, doNodeError_21_1, empty_3f_1, endBlock_21_1, error1, errorPositions_21_1, escapeVar1, exit_21_1, expectType_21_1, expect_21_1, find1, format1, formatOutput_21_1, getIdx1, getVar1, getenv1, getinfo1, gsub1, huge1, last1, len_23_1, lex1, line_21_1, list1, lookup1, lower1, makeNil1, map2, match1, min1, n1, next1, nth1, number_3f_1, open1, pcall1, pretty1, print1, pushEscapeVar_21_1, push_21_1, putNodeWarning_21_1, quoted1, removeNth_21_1, require1, resolveNode1, runPass1, scoreNodes1, self1, setIdx_21_1, sethook1, slice1, sort1, sourceRange1, splice1, split1, string_3f_1, sub1, symbol_2d3e_string1, tonumber1, tostring1, type1, type_23_1, unmangleIdent1, usage_21_1, varNative1, visitBlock1, visitNode1, visitNode2, visitNode3, visitNodes2, zipArgs1
  8. local _ENV = setmetatable({}, {__index=_ENV or (getfenv and getfenv()) or _G}) if setfenv then setfenv(0, _ENV) end
  9. _3d_1 = function(v1, v2) return v1 == v2 end
  10. _2f3d_1 = function(v1, v2) return v1 ~= v2 end
  11. _3c_1 = function(v1, v2) return v1 < v2 end
  12. _3c3d_1 = function(v1, v2) return v1 <= v2 end
  13. _3e_1 = function(v1, v2) return v1 > v2 end
  14. _3e3d_1 = function(v1, v2) return v1 >= v2 end
  15. _2b_1 = function(x, ...) local t = x + ... for i = 2, _select('#', ...) do t = t + _select(i, ...) end return t end
  16. _2d_1 = function(x, ...) local t = x - ... for i = 2, _select('#', ...) do t = t - _select(i, ...) end return t end
  17. _2a_1 = function(x, ...) local t = x * ... for i = 2, _select('#', ...) do t = t * _select(i, ...) end return t end
  18. _2f_1 = function(x, ...) local t = x / ... for i = 2, _select('#', ...) do t = t / _select(i, ...) end return t end
  19. mod1 = function(x, ...) local t = x % ... for i = 2, _select('#', ...) do t = t % _select(i, ...) end return t end
  20. expt1 = function(x, ...) local n = _select('#', ...) local t = _select(n, ...) for i = n - 1, 1, -1 do t = _select(i, ...) ^ t end return x ^ t end
  21. _2e2e_1 = function(x, ...) local n = _select('#', ...) local t = _select(n, ...) for i = n - 1, 1, -1 do t = _select(i, ...) .. t end return x .. t end
  22. len_23_1 = function(v1) return #v1 end
  23. getIdx1 = function(v1, v2) return v1[v2] end
  24. setIdx_21_1 = function(v1, v2, v3) v1[v2] = v3 end
  25. _5f_G1 = _G
  26. arg_23_1 = arg or {...}
  27. error1 = error
  28. getmetatable1 = getmetatable
  29. load1 = load
  30. next1 = next
  31. pcall1 = pcall
  32. print1 = print
  33. require1 = require
  34. setmetatable1 = setmetatable
  35. tonumber1 = tonumber
  36. tostring1 = tostring
  37. type_23_1 = type
  38. xpcall1 = xpcall
  39. byte1 = string.byte
  40. char1 = string.char
  41. find1 = string.find
  42. format1 = string.format
  43. gsub1 = string.gsub
  44. lower1 = string.lower
  45. match1 = string.match
  46. rep1 = string.rep
  47. reverse1 = string.reverse
  48. sub1 = string.sub
  49. upper1 = string.upper
  50. concat1 = table.concat
  51. insert1 = table.insert
  52. remove1 = table.remove
  53. sort1 = table.sort
  54. unpack1 = table.unpack
  55. n1 = function(x)
  56. if type_23_1(x) == "table" then
  57. return x["n"]
  58. else
  59. return #x
  60. end
  61. end
  62. slice1 = function(xs, start, finish)
  63. if not finish then
  64. finish = xs["n"]
  65. if not finish then
  66. finish = #xs
  67. end
  68. end
  69. local len, _ = (finish - start) + 1
  70. if len < 0 then
  71. len = 0
  72. end
  73. local out, i, j = {tag="list", n=len}, 1, start
  74. while j <= finish do
  75. out[i] = xs[j]
  76. i, j = i + 1, j + 1
  77. end
  78. return out
  79. end
  80. list1 = function(...)
  81. local xs = _pack(...) xs.tag = "list"
  82. return xs
  83. end
  84. if nil == arg_23_1 then
  85. _2a_arguments_2a_1 = {tag="list", n=0}
  86. else
  87. arg_23_1["tag"] = "list"
  88. if not arg_23_1["n"] then
  89. arg_23_1["n"] = #arg_23_1
  90. end
  91. _2a_arguments_2a_1 = arg_23_1
  92. end
  93. constVal1 = function(val)
  94. if type_23_1(val) == "table" then
  95. local tag = val["tag"]
  96. if tag == "number" then
  97. return val["value"]
  98. elseif tag == "string" then
  99. return val["value"]
  100. else
  101. return val
  102. end
  103. else
  104. return val
  105. end
  106. end
  107. splice1 = function(xs)
  108. local parent = xs["parent"]
  109. if parent then
  110. return unpack1(parent, xs["offset"] + 1, xs["n"] + xs["offset"])
  111. else
  112. return unpack1(xs, 1, xs["n"])
  113. end
  114. end
  115. apply1 = function(f, ...)
  116. local _n = _select("#", ...) - 1
  117. local xss, xs
  118. if _n > 0 then
  119. xss = {tag="list", n=_n, _unpack(_pack(...), 1, _n)}
  120. xs = select(_n + 1, ...)
  121. else
  122. xss = {tag="list", n=0}
  123. xs = ...
  124. end
  125. return f(splice1((function()
  126. local _offset, _result, _temp = 0, {tag="list"}
  127. _temp = xss
  128. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  129. _offset = _offset + _temp.n
  130. _temp = xs
  131. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  132. _offset = _offset + _temp.n
  133. _result.n = _offset + 0
  134. return _result
  135. end)()
  136. ))
  137. end
  138. first1 = function(...)
  139. local rest = _pack(...) rest.tag = "list"
  140. return rest[1]
  141. end
  142. empty_3f_1 = function(x)
  143. local xt = type1(x)
  144. if xt == "list" then
  145. return x["n"] == 0
  146. elseif xt == "string" then
  147. return #x == 0
  148. else
  149. return false
  150. end
  151. end
  152. string_3f_1 = function(x)
  153. return type_23_1(x) == "string" or type_23_1(x) == "table" and x["tag"] == "string"
  154. end
  155. number_3f_1 = function(x)
  156. return type_23_1(x) == "number" or type_23_1(x) == "table" and x["tag"] == "number"
  157. end
  158. function_3f_1 = function(x)
  159. return type1(x) == "function" or type1(x) == "multimethod"
  160. end
  161. atom_3f_1 = function(x)
  162. local temp = type_23_1(x) ~= "table"
  163. if temp then
  164. return temp
  165. else
  166. local temp1 = type_23_1(x) == "table"
  167. if temp1 then
  168. local tag = x["tag"]
  169. return tag == "symbol" or (tag == "key" or (tag == "number" or tag == "string"))
  170. else
  171. return temp1
  172. end
  173. end
  174. end
  175. nil_3f_1 = function(x)
  176. return type_23_1(x) == "nil"
  177. end
  178. between_3f_1 = function(val, min, max)
  179. return val >= min and val <= max
  180. end
  181. type1 = function(val)
  182. local ty = type_23_1(val)
  183. if ty == "table" then
  184. return val["tag"] or "table"
  185. else
  186. return ty
  187. end
  188. end
  189. map1 = function(f, x)
  190. local out = {tag="list", n=0}
  191. local forLimit = n1(x)
  192. local i = 1
  193. while i <= forLimit do
  194. out[i] = f(x[i])
  195. i = i + 1
  196. end
  197. out["n"] = n1(x)
  198. return out
  199. end
  200. put_21_1 = function(t, typs, l)
  201. local len = n1(typs)
  202. local forLimit = len - 1
  203. local i = 1
  204. while i <= forLimit do
  205. local x = typs[i]
  206. local y = t[x]
  207. if not y then
  208. y = {}
  209. t[x] = y
  210. end
  211. t = y
  212. i = i + 1
  213. end
  214. t[typs[len]] = l
  215. return nil
  216. end
  217. neq_3f_1 = function(x, y)
  218. return not eq_3f_1(x, y)
  219. end
  220. local eq_3f_
  221. local this = {lookup={list={list=function(x, y)
  222. if n1(x) ~= n1(y) then
  223. return false
  224. else
  225. local equal = true
  226. local forLimit = n1(x)
  227. local i = 1
  228. while i <= forLimit do
  229. if neq_3f_1(x[i], y[i]) then
  230. equal = false
  231. end
  232. i = i + 1
  233. end
  234. return equal
  235. end
  236. end}, table={table=function(x, y)
  237. local equal = true
  238. local temp, v = next1(x)
  239. while temp ~= nil do
  240. if neq_3f_1(v, y[temp]) then
  241. equal = false
  242. end
  243. temp, v = next1(x, temp)
  244. end
  245. return equal
  246. end}, symbol={symbol=function(x, y)
  247. return x["contents"] == y["contents"]
  248. end, string=function(x, y)
  249. return x["contents"] == y
  250. end}, string={symbol=function(x, y)
  251. return x == y["contents"]
  252. end, key=function(x, y)
  253. return x == y["value"]
  254. end, string=function(x, y)
  255. return constVal1(x) == constVal1(y)
  256. end}, key={string=function(x, y)
  257. return x["value"] == y
  258. end, key=function(x, y)
  259. return x["value"] == y["value"]
  260. end}, number={number=function(x, y)
  261. return constVal1(x) == constVal1(y)
  262. end}, rational={rational=function(x, y)
  263. local xn, xd = normalisedRationalComponents1(x)
  264. local yn, yd = normalisedRationalComponents1(y)
  265. return xn == yn and xd == yd
  266. end}}, tag="multimethod", default=function(x, y)
  267. return false
  268. end}
  269. eq_3f_ = setmetatable1(this, {__call=function(this1, x, y)
  270. if x == y then
  271. return true
  272. else
  273. local method = (this["lookup"][type1(x)] or {})[type1(y)] or this["default"]
  274. if not method then
  275. error1("No matching method to call for (" .. concat1(list1("eq?", type1(x), type1(y)), " ") .. ")")
  276. end
  277. return method(x, y)
  278. end
  279. end, name="eq?", args=list1("x", "y")})
  280. put_21_1(eq_3f_, list1("lookup", "number", "rational"), (eq_3f_["lookup"]["rational"] or {})["rational"])
  281. put_21_1(eq_3f_, list1("lookup", "rational", "number"), (eq_3f_["lookup"]["rational"] or {})["rational"])
  282. eq_3f_1 = eq_3f_
  283. local this = {lookup={list=function(xs)
  284. return "(" .. concat1(map1(pretty1, xs), " ") .. ")"
  285. end, symbol=function(x)
  286. return x["contents"]
  287. end, key=function(x)
  288. return ":" .. x["value"]
  289. end, number=function(x)
  290. return format1("%g", constVal1(x))
  291. end, string=function(x)
  292. return format1("%q", constVal1(x))
  293. end, table=function(x)
  294. local out = {tag="list", n=0}
  295. local temp, v = next1(x)
  296. while temp ~= nil do
  297. local _offset, _result, _temp = 0, {tag="list"}
  298. _result[1 + _offset] = pretty1(temp) .. " " .. pretty1(v)
  299. _temp = out
  300. for _c = 1, _temp.n do _result[1 + _c + _offset] = _temp[_c] end
  301. _offset = _offset + _temp.n
  302. _result.n = _offset + 1
  303. out = _result
  304. temp, v = next1(x, temp)
  305. end
  306. return "{" .. (concat1(out, " ") .. "}")
  307. end, multimethod=function(x)
  308. return "«method: (" .. getmetatable1(x)["name"] .. " " .. concat1(getmetatable1(x)["args"], " ") .. ")»"
  309. end, ["demand-failure"]=function(failure)
  310. return demandFailure_2d3e_string1(failure)
  311. end, rational=function(x)
  312. local xn, xd = normalisedRationalComponents1(x)
  313. return formatOutput_21_1(nil, "" .. format1("%d", xn) .. "/" .. format1("%d", xd))
  314. end, var=function(var)
  315. return "«var : " .. var["name"] .. "»"
  316. end, position=function(pos)
  317. return pos["line"] .. ":" .. pos["column"]
  318. end, range=function(range)
  319. return formatRange1(range)
  320. end, ["node-source"]=function(source)
  321. return formatNodeSource1(source)
  322. end}, tag="multimethod", default=function(x)
  323. if type_23_1(x) == "table" then
  324. return pretty1["lookup"]["table"](x)
  325. else
  326. return tostring1(x)
  327. end
  328. end}
  329. pretty1 = setmetatable1(this, {__call=function(this1, x)
  330. local method = this["lookup"][type1(x)] or this["default"]
  331. if not method then
  332. error1("No matching method to call for (" .. concat1(list1("pretty", type1(x)), " ") .. ")")
  333. end
  334. return method(x)
  335. end, name="pretty", args=list1("x")})
  336. gethook1 = debug and debug.gethook
  337. getinfo1 = debug and debug.getinfo
  338. sethook1 = debug and debug.sethook
  339. traceback1 = debug and debug.traceback
  340. demandFailure_2d3e_string1 = function(failure)
  341. if failure["message"] then
  342. return format1("demand not met: %s (%s).\n%s", failure["condition"], failure["message"], failure["traceback"])
  343. else
  344. return format1("demand not met: %s.\n%s", failure["condition"], failure["traceback"])
  345. end
  346. end
  347. _2a_demandFailureMt_2a_1 = {__tostring=demandFailure_2d3e_string1}
  348. demandFailure1 = function(message, condition)
  349. return setmetatable1({tag="demand-failure", message=message, traceback=(function()
  350. if traceback1 then
  351. return traceback1("", 2)
  352. else
  353. return ""
  354. end
  355. end)(), condition=condition}, _2a_demandFailureMt_2a_1)
  356. end
  357. abs1 = math.abs
  358. huge1 = math.huge
  359. max1 = math.max
  360. min1 = math.min
  361. modf1 = math.modf
  362. car1 = function(x)
  363. if type1(x) ~= "list" then
  364. error1(demandFailure1(nil, "(= (type x) \"list\")"))
  365. end
  366. return x[1]
  367. end
  368. local refMt = {__index=function(t, k)
  369. return t["parent"][k + t["offset"]]
  370. end, __newindex=function(t, k, v)
  371. t["parent"][k + t["offset"]] = v
  372. return nil
  373. end}
  374. slicingView1 = function(list, offset)
  375. if n1(list) <= offset then
  376. return {tag="list", n=0}
  377. elseif list["parent"] and list["offset"] then
  378. return setmetatable1({parent=list["parent"], offset=list["offset"] + offset, n=n1(list) - offset, tag=type1(list)}, refMt)
  379. else
  380. return setmetatable1({parent=list, offset=offset, n=n1(list) - offset, tag=type1(list)}, refMt)
  381. end
  382. end
  383. cons1 = function(...)
  384. local _n = _select("#", ...) - 1
  385. local xs, xss
  386. if _n > 0 then
  387. xs = {tag="list", n=_n, _unpack(_pack(...), 1, _n)}
  388. xss = select(_n + 1, ...)
  389. else
  390. xs = {tag="list", n=0}
  391. xss = ...
  392. end
  393. local _offset, _result, _temp = 0, {tag="list"}
  394. _temp = xs
  395. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  396. _offset = _offset + _temp.n
  397. _temp = xss
  398. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  399. _offset = _offset + _temp.n
  400. _result.n = _offset + 0
  401. return _result
  402. end
  403. reduce1 = function(f, z, xs)
  404. if type1(f) ~= "function" then
  405. error1(demandFailure1(nil, "(= (type f) \"function\")"))
  406. end
  407. local start = 1
  408. if type_23_1(xs) == "nil" and type1(z) == "list" then
  409. start = 2
  410. xs = z
  411. z = car1(z)
  412. end
  413. if type1(xs) ~= "list" then
  414. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  415. end
  416. local accum = z
  417. local forStart, forLimit = start, n1(xs)
  418. local i = forStart
  419. while i <= forLimit do
  420. accum = f(accum, nth1(xs, i))
  421. i = i + 1
  422. end
  423. return accum
  424. end
  425. map2 = function(fn, ...)
  426. local xss = _pack(...) xss.tag = "list"
  427. local ns
  428. local out = {tag="list", n=0}
  429. local forLimit = n1(xss)
  430. local i = 1
  431. while i <= forLimit do
  432. if type1((nth1(xss, i))) ~= "list" then
  433. error1("that's no list! " .. pretty1(nth1(xss, i)) .. " (it's a " .. type1(nth1(xss, i)) .. "!)")
  434. end
  435. push_21_1(out, n1(nth1(xss, i)))
  436. i = i + 1
  437. end
  438. ns = out
  439. local out = {tag="list", n=0}
  440. local forLimit = apply1(min1, ns)
  441. local i = 1
  442. while i <= forLimit do
  443. push_21_1(out, apply1(fn, nths1(xss, i)))
  444. i = i + 1
  445. end
  446. return out
  447. end
  448. partition1 = function(p, xs)
  449. if type1(p) ~= "function" then
  450. error1(demandFailure1(nil, "(= (type p) \"function\")"))
  451. end
  452. if type1(xs) ~= "list" then
  453. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  454. end
  455. local passed, failed = {tag="list", n=0}, {tag="list", n=0}
  456. local forLimit = n1(xs)
  457. local i = 1
  458. while i <= forLimit do
  459. local x = nth1(xs, i)
  460. push_21_1((function()
  461. if p(x) then
  462. return passed
  463. else
  464. return failed
  465. end
  466. end)(), x)
  467. i = i + 1
  468. end
  469. return splice1(list1(passed, failed))
  470. end
  471. any1 = function(p, xs)
  472. if type1(p) ~= "function" then
  473. error1(demandFailure1(nil, "(= (type p) \"function\")"))
  474. end
  475. if type1(xs) ~= "list" then
  476. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  477. end
  478. local len = n1(xs)
  479. local i = 1
  480. while true do
  481. if i > len then
  482. return false
  483. elseif p(nth1(xs, i)) then
  484. return true
  485. else
  486. i = i + 1
  487. end
  488. end
  489. end
  490. nub1 = function(xs)
  491. local hm, out = {}, {tag="list", n=0}
  492. local forLimit = n1(xs)
  493. local i = 1
  494. while i <= forLimit do
  495. local elm = xs[i]
  496. local szd = pretty1(elm)
  497. if type_23_1((hm[szd])) == "nil" then
  498. push_21_1(out, elm)
  499. hm[szd] = elm
  500. end
  501. i = i + 1
  502. end
  503. return out
  504. end
  505. all1 = function(p, xs)
  506. if type1(p) ~= "function" then
  507. error1(demandFailure1(nil, "(= (type p) \"function\")"))
  508. end
  509. if type1(xs) ~= "list" then
  510. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  511. end
  512. local len = n1(xs)
  513. local i = 1
  514. while true do
  515. if i > len then
  516. return true
  517. elseif p(nth1(xs, i)) then
  518. i = i + 1
  519. else
  520. return false
  521. end
  522. end
  523. end
  524. elem_3f_1 = function(x, xs)
  525. if type1(xs) ~= "list" then
  526. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  527. end
  528. return any1(function(y)
  529. return eq_3f_1(x, y)
  530. end, xs)
  531. end
  532. findIndex1 = function(p, xs)
  533. if type1(p) ~= "function" then
  534. error1(demandFailure1(nil, "(= (type p) \"function\")"))
  535. end
  536. if type1(xs) ~= "list" then
  537. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  538. end
  539. local len = n1(xs)
  540. local i = 1
  541. while true do
  542. if i > len then
  543. return nil
  544. elseif p(nth1(xs, i)) then
  545. return i
  546. else
  547. i = i + 1
  548. end
  549. end
  550. end
  551. last1 = function(xs)
  552. if type1(xs) ~= "list" then
  553. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  554. end
  555. return xs[n1(xs)]
  556. end
  557. nth1 = function(xs, idx)
  558. if idx >= 0 then
  559. return xs[idx]
  560. else
  561. return xs[xs["n"] + 1 + idx]
  562. end
  563. end
  564. nths1 = function(xss, idx)
  565. local out = {tag="list", n=0}
  566. local forLimit = n1(xss)
  567. local i = 1
  568. while i <= forLimit do
  569. push_21_1(out, nth1(nth1(xss, i), idx))
  570. i = i + 1
  571. end
  572. return out
  573. end
  574. push_21_1 = function(xs, ...)
  575. local vals = _pack(...) vals.tag = "list"
  576. if type1(xs) ~= "list" then
  577. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  578. end
  579. local nxs = n1(xs)
  580. xs["n"] = (nxs + n1(vals))
  581. local forLimit = n1(vals)
  582. local i = 1
  583. while i <= forLimit do
  584. xs[nxs + i] = vals[i]
  585. i = i + 1
  586. end
  587. return xs
  588. end
  589. popLast_21_1 = function(xs)
  590. if type1(xs) ~= "list" then
  591. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  592. end
  593. local x = xs[n1(xs)]
  594. xs[n1(xs)] = nil
  595. xs["n"] = n1(xs) - 1
  596. return x
  597. end
  598. removeNth_21_1 = function(li, idx)
  599. if type1(li) ~= "list" then
  600. error1(demandFailure1(nil, "(= (type li) \"list\")"))
  601. end
  602. li["n"] = li["n"] - 1
  603. return remove1(li, idx)
  604. end
  605. insertNth_21_1 = function(li, idx, val)
  606. if type1(li) ~= "list" then
  607. error1(demandFailure1(nil, "(= (type li) \"list\")"))
  608. end
  609. li["n"] = li["n"] + 1
  610. return insert1(li, idx, val)
  611. end
  612. append1 = function(xs, ys)
  613. local _offset, _result, _temp = 0, {tag="list"}
  614. _temp = xs
  615. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  616. _offset = _offset + _temp.n
  617. _temp = ys
  618. for _c = 1, _temp.n do _result[0 + _c + _offset] = _temp[_c] end
  619. _offset = _offset + _temp.n
  620. _result.n = _offset + 0
  621. return _result
  622. end
  623. range1 = function(...)
  624. local args = _pack(...) args.tag = "list"
  625. local x
  626. local out = {}
  627. if n1(args) % 2 == 1 then
  628. error1("Expected an even number of arguments to range", 2)
  629. end
  630. local forLimit = n1(args)
  631. local i = 1
  632. while i <= forLimit do
  633. out[args[i]] = args[i + 1]
  634. i = i + 2
  635. end
  636. x = out
  637. local st, ed = x["from"] or 1, 1 + x["to"] or error1("Expected end index, got nothing")
  638. local inc = (x["by"] or 1 + st) - st
  639. local tst
  640. if st >= ed then
  641. tst = _3e_1
  642. else
  643. tst = _3c_1
  644. end
  645. local c, out = st, {tag="list", n=0}
  646. while tst(c, ed) do
  647. push_21_1(out, c)
  648. c = c + inc
  649. end
  650. return out
  651. end
  652. sort2 = function(xs, f)
  653. local copy = map2(function(x)
  654. return x
  655. end, xs)
  656. sort1(copy, f)
  657. return copy
  658. end
  659. caar1 = function(xs)
  660. if type1(xs) ~= "list" then
  661. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  662. end
  663. return car1(xs[1])
  664. end
  665. caadr1 = function(xs)
  666. if type1(xs) ~= "list" then
  667. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  668. end
  669. return car1(xs[2])
  670. end
  671. cadr1 = function(xs)
  672. if type1(xs) ~= "list" then
  673. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  674. end
  675. return xs[2]
  676. end
  677. cadar1 = function(xs)
  678. if type1(xs) ~= "list" then
  679. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  680. end
  681. return cadr1(xs[1])
  682. end
  683. concat2 = function(xs, separator)
  684. if type1(xs) ~= "list" then
  685. error1(demandFailure1(nil, "(= (type xs) \"list\")"))
  686. end
  687. if xs["parent"] then
  688. return concat1(xs["parent"], separator, xs["offset"] + 1, xs["n"] + xs["offset"])
  689. else
  690. return concat1(xs, separator, 1, xs["n"])
  691. end
  692. end
  693. split1 = function(text, pattern, limit)
  694. local out, loop, start = {tag="list", n=0}, true, 1
  695. while loop do
  696. local pos = list1(find1(text, pattern, start))
  697. local nstart, nend = car1(pos), cadr1(pos)
  698. if nstart == nil or limit and n1(out) >= limit then
  699. loop = false
  700. push_21_1(out, sub1(text, start, n1(text)))
  701. start = n1(text) + 1
  702. elseif nstart > #text then
  703. if start <= #text then
  704. push_21_1(out, sub1(text, start, #text))
  705. end
  706. loop = false
  707. elseif nend < nstart then
  708. push_21_1(out, sub1(text, start, nstart))
  709. start = nstart + 1
  710. else
  711. push_21_1(out, sub1(text, start, nstart - 1))
  712. start = nend + 1
  713. end
  714. end
  715. return out
  716. end
  717. trim1 = function(str)
  718. return (gsub1(gsub1(str, "^%s+", ""), "%s+$", ""))
  719. end
  720. local escapes = {}
  721. local i = 0
  722. while i <= 31 do
  723. escapes[char1(i)] = "\\" .. tostring1(i)
  724. i = i + 1
  725. end
  726. escapes["\n"] = "n"
  727. quoted1 = function(str)
  728. return (gsub1(format1("%q", str), ".", escapes))
  729. end
  730. endsWith_3f_1 = function(str, suffix)
  731. return sub1(str, 0 - #suffix) == suffix
  732. end
  733. symbol_2d3e_string1 = function(x)
  734. if type1(x) == "symbol" then
  735. return x["contents"]
  736. else
  737. return nil
  738. end
  739. end
  740. struct1 = function(...)
  741. local entries = _pack(...) entries.tag = "list"
  742. if n1(entries) % 2 == 1 then
  743. error1("Expected an even number of arguments to struct", 2)
  744. end
  745. local out = {}
  746. local forLimit = n1(entries)
  747. local i = 1
  748. while i <= forLimit do
  749. local key, val = entries[i], entries[1 + i]
  750. out[(function()
  751. if type1(key) == "key" then
  752. return key["value"]
  753. else
  754. return key
  755. end
  756. end)()] = val
  757. i = i + 2
  758. end
  759. return out
  760. end
  761. iterPairs1 = function(table, func)
  762. local temp, v = next1(table)
  763. while temp ~= nil do
  764. func(temp, v)
  765. temp, v = next1(table, temp)
  766. end
  767. return nil
  768. end
  769. copyOf1 = function(struct)
  770. local out = {}
  771. local temp, v = next1(struct)
  772. while temp ~= nil do
  773. out[temp] = v
  774. temp, v = next1(struct, temp)
  775. end
  776. return out
  777. end
  778. merge1 = function(...)
  779. local structs = _pack(...) structs.tag = "list"
  780. local out = {}
  781. local forLimit = n1(structs)
  782. local i = 1
  783. while i <= forLimit do
  784. local st = structs[i]
  785. local temp, v = next1(st)
  786. while temp ~= nil do
  787. out[temp] = v
  788. temp, v = next1(st, temp)
  789. end
  790. i = i + 1
  791. end
  792. return out
  793. end
  794. keys1 = function(st)
  795. local out = {tag="list", n=0}
  796. local temp, _5f_ = next1(st)
  797. while temp ~= nil do
  798. push_21_1(out, temp)
  799. temp, _5f_ = next1(st, temp)
  800. end
  801. return out
  802. end
  803. values1 = function(st)
  804. local out = {tag="list", n=0}
  805. local temp, v = next1(st)
  806. while temp ~= nil do
  807. push_21_1(out, v)
  808. temp, v = next1(st, temp)
  809. end
  810. return out
  811. end
  812. updateStruct1 = function(st, ...)
  813. local keys = _pack(...) keys.tag = "list"
  814. return merge1(st, apply1(struct1, keys))
  815. end
  816. createLookup1 = function(values)
  817. local res = {}
  818. local forLimit = n1(values)
  819. local i = 1
  820. while i <= forLimit do
  821. res[nth1(values, i)] = i
  822. i = i + 1
  823. end
  824. return res
  825. end
  826. clock1 = os.clock
  827. execute1 = os.execute
  828. exit1 = os.exit
  829. getenv1 = os.getenv
  830. flush1 = io.flush
  831. open1 = io.open
  832. read1 = io.read
  833. write1 = io.write
  834. exit_21_1 = function(reason, code)
  835. local code1
  836. if string_3f_1(reason) then
  837. code1 = code
  838. else
  839. code1 = reason
  840. end
  841. if exit1 then
  842. if string_3f_1(reason) then
  843. print1(reason)
  844. end
  845. return exit1(code1)
  846. elseif string_3f_1(reason) then
  847. return error1(reason, 0)
  848. else
  849. return error1(nil, 0)
  850. end
  851. end
  852. sprintf1 = function(fmt, ...)
  853. local args = _pack(...) args.tag = "list"
  854. return apply1(format1, fmt, args)
  855. end
  856. assoc1 = function(list, key, orVal)
  857. while true do
  858. if type1(list) ~= "list" or empty_3f_1(list) then
  859. return orVal
  860. elseif eq_3f_1(caar1(list), key) then
  861. return cadar1(list)
  862. else
  863. list = slicingView1(list, 1)
  864. end
  865. end
  866. end
  867. assoc_3f_1 = function(list, key)
  868. while true do
  869. if type1(list) ~= "list" or empty_3f_1(list) then
  870. return false
  871. elseif eq_3f_1(caar1(list), key) then
  872. return true
  873. else
  874. list = slicingView1(list, 1)
  875. end
  876. end
  877. end
  878. struct_2d3e_assoc1 = function(tbl)
  879. local out = {tag="list", n=0}
  880. local temp, v = next1(tbl)
  881. while temp ~= nil do
  882. push_21_1(out, list1(temp, v))
  883. temp, v = next1(tbl, temp)
  884. end
  885. return out
  886. end
  887. display1 = function(x)
  888. if type_23_1(x) == "string" then
  889. return x
  890. elseif type_23_1(x) == "table" and x["tag"] == "string" then
  891. return x["value"]
  892. else
  893. return pretty1(x)
  894. end
  895. end
  896. formatOutput_21_1 = function(out, buf)
  897. if out == nil then
  898. return buf
  899. elseif out == true then
  900. return print1(buf)
  901. elseif number_3f_1(out) then
  902. return error1(buf, out)
  903. elseif function_3f_1(out) then
  904. return out(buf)
  905. else
  906. return out["write"](out, buf)
  907. end
  908. end
  909. invokable_3f_1 = function(x)
  910. while true do
  911. local temp = function_3f_1(x)
  912. if temp then
  913. return temp
  914. else
  915. local temp1 = type_23_1(x) == "table"
  916. if temp1 then
  917. local temp2 = type_23_1((getmetatable1(x))) == "table"
  918. if temp2 then
  919. x = getmetatable1(x)["__call"]
  920. else
  921. return temp2
  922. end
  923. else
  924. return temp1
  925. end
  926. end
  927. end
  928. end
  929. compose1 = function(f, g)
  930. if invokable_3f_1(f) and invokable_3f_1(g) then
  931. return function(x)
  932. return f(g(x))
  933. end
  934. else
  935. return nil
  936. end
  937. end
  938. comp1 = function(...)
  939. local fs = _pack(...) fs.tag = "list"
  940. return reduce1(compose1, function(x)
  941. return x
  942. end, fs)
  943. end
  944. id1 = function(x)
  945. return x
  946. end
  947. call1 = function(x, key, ...)
  948. local args = _pack(...) args.tag = "list"
  949. return apply1(x[key], args)
  950. end
  951. self1 = function(x, key, ...)
  952. local args = _pack(...) args.tag = "list"
  953. return apply1(x[key], x, args)
  954. end
  955. gcd1 = function(x, y)
  956. local x1, y1 = abs1(x), abs1(y)
  957. while not (y1 == 0) do
  958. x1, y1 = y1, x1 % y1
  959. end
  960. return x1
  961. end
  962. _2d3e_ratComponents1 = function(y)
  963. local i, f = modf1(y)
  964. local f_27_ = 10 ^ (n1(tostring1(f)) - 2)
  965. if 0 == f then
  966. return splice1(list1(y, 1))
  967. else
  968. local n = y * f_27_
  969. local g = gcd1(n, f_27_)
  970. return splice1(list1(n / g, (f_27_ / g)))
  971. end
  972. end
  973. normalisedRationalComponents1 = function(x)
  974. if number_3f_1(x) then
  975. return _2d3e_ratComponents1(x)
  976. else
  977. return splice1(list1(x["numerator"], (x["denominator"])))
  978. end
  979. end
  980. config1 = package.config
  981. colouredAnsi1 = function(col, msg)
  982. return "\27[" .. col .. "m" .. msg .. "\27[0m"
  983. end
  984. local termTy = lower1(getenv1 and getenv1("TERM") or "")
  985. if termTy == "dumb" then
  986. coloured_3f_1 = false
  987. elseif find1(termTy, "xterm") then
  988. coloured_3f_1 = true
  989. elseif config1 and sub1(config1, 1, 1) == "/" then
  990. coloured_3f_1 = true
  991. elseif getenv1 and getenv1("ANSICON") ~= nil then
  992. coloured_3f_1 = true
  993. else
  994. coloured_3f_1 = false
  995. end
  996. if coloured_3f_1 then
  997. coloured1 = colouredAnsi1
  998. else
  999. coloured1 = function(_5f_, msg)
  1000. return msg
  1001. end
  1002. end
  1003. create1 = function(description)
  1004. return {desc=description, ["flag-map"]={}, ["opt-map"]={}, cats={tag="list", n=0}, opt={tag="list", n=0}, pos={tag="list", n=0}}
  1005. end
  1006. setAction1 = function(arg, data, value)
  1007. data[arg["name"]] = value
  1008. return nil
  1009. end
  1010. addAction1 = function(arg, data, value)
  1011. local lst = data[arg["name"]]
  1012. if not lst then
  1013. lst = {tag="list", n=0}
  1014. data[arg["name"]] = lst
  1015. end
  1016. return push_21_1(lst, value)
  1017. end
  1018. setNumAction1 = function(aspec, data, value, usage_21_)
  1019. local val = tonumber1(value)
  1020. if val then
  1021. data[aspec["name"]] = val
  1022. return nil
  1023. else
  1024. return usage_21_("Expected number for " .. car1(_2a_arguments_2a_1["names"]) .. ", got " .. value)
  1025. end
  1026. end
  1027. addArgument_21_1 = function(spec, names, ...)
  1028. local options = _pack(...) options.tag = "list"
  1029. if type1(names) ~= "list" then
  1030. error1(demandFailure1(nil, "(= (type names) \"list\")"))
  1031. end
  1032. if empty_3f_1(names) then
  1033. error1("Names list is empty")
  1034. end
  1035. if n1(options) % 2 ~= 0 then
  1036. error1("Options list should be a multiple of two")
  1037. end
  1038. local result = {names=names, action=nil, narg=0, default=false, help="", value=true}
  1039. local first = car1(names)
  1040. if sub1(first, 1, 2) == "--" then
  1041. push_21_1(spec["opt"], result)
  1042. result["name"] = sub1(first, 3)
  1043. elseif sub1(first, 1, 1) == "-" then
  1044. push_21_1(spec["opt"], result)
  1045. result["name"] = sub1(first, 2)
  1046. else
  1047. result["name"] = first
  1048. result["narg"] = "*"
  1049. result["default"] = {tag="list", n=0}
  1050. push_21_1(spec["pos"], result)
  1051. end
  1052. local forLimit = n1(names)
  1053. local i = 1
  1054. while i <= forLimit do
  1055. local name = names[i]
  1056. if sub1(name, 1, 2) == "--" then
  1057. spec["opt-map"][sub1(name, 3)] = result
  1058. elseif sub1(name, 1, 1) == "-" then
  1059. spec["flag-map"][sub1(name, 2)] = result
  1060. end
  1061. i = i + 1
  1062. end
  1063. local forLimit = n1(options)
  1064. local i = 1
  1065. while i <= forLimit do
  1066. result[nth1(options, i)] = (nth1(options, i + 1))
  1067. i = i + 2
  1068. end
  1069. if not result["var"] then
  1070. result["var"] = upper1(result["name"])
  1071. end
  1072. if not result["action"] then
  1073. result["action"] = (function()
  1074. local temp
  1075. if number_3f_1(result["narg"]) then
  1076. temp = result["narg"] <= 1
  1077. else
  1078. temp = result["narg"] == "?"
  1079. end
  1080. if temp then
  1081. return setAction1
  1082. else
  1083. return addAction1
  1084. end
  1085. end)()
  1086. end
  1087. return result
  1088. end
  1089. addHelp_21_1 = function(spec)
  1090. return addArgument_21_1(spec, {tag="list", n=2, "--help", "-h"}, "help", "Show this help message", "default", nil, "value", nil, "action", function()
  1091. help_21_1(spec)
  1092. return exit_21_1(0)
  1093. end)
  1094. end
  1095. addCategory_21_1 = function(spec, id, name, description)
  1096. if type1(id) ~= "string" then
  1097. error1(demandFailure1(nil, "(= (type id) \"string\")"))
  1098. end
  1099. if type1(name) ~= "string" then
  1100. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1101. end
  1102. push_21_1(spec["cats"], {id=id, name=name, desc=description})
  1103. return spec
  1104. end
  1105. usageNarg_21_1 = function(buffer, arg)
  1106. local temp = arg["narg"]
  1107. if temp == "?" then
  1108. return push_21_1(buffer, " [" .. arg["var"] .. "]")
  1109. elseif temp == "*" then
  1110. return push_21_1(buffer, " [" .. arg["var"] .. "...]")
  1111. elseif temp == "+" then
  1112. return push_21_1(buffer, " " .. arg["var"] .. " [" .. arg["var"] .. "...]")
  1113. else
  1114. local _5f_ = 1
  1115. while _5f_ <= temp do
  1116. push_21_1(buffer, " " .. arg["var"])
  1117. _5f_ = _5f_ + 1
  1118. end
  1119. return nil
  1120. end
  1121. end
  1122. usage_21_1 = function(spec, name)
  1123. if not name then
  1124. name = nth1(_2a_arguments_2a_1, 0) or (_2a_arguments_2a_1[-1] or "?")
  1125. end
  1126. local usage = list1("usage: ", name)
  1127. local temp = spec["opt"]
  1128. local forLimit = n1(temp)
  1129. local i = 1
  1130. while i <= forLimit do
  1131. local arg = temp[i]
  1132. push_21_1(usage, " [" .. car1(arg["names"]))
  1133. usageNarg_21_1(usage, arg)
  1134. push_21_1(usage, "]")
  1135. i = i + 1
  1136. end
  1137. local temp = spec["pos"]
  1138. local forLimit = n1(temp)
  1139. local i = 1
  1140. while i <= forLimit do
  1141. usageNarg_21_1(usage, (temp[i]))
  1142. i = i + 1
  1143. end
  1144. return print1(concat2(usage))
  1145. end
  1146. helpArgs_21_1 = function(pos, opt, format)
  1147. if (empty_3f_1(pos) and empty_3f_1(opt)) then
  1148. return nil
  1149. else
  1150. print1()
  1151. local forLimit = n1(pos)
  1152. local i = 1
  1153. while i <= forLimit do
  1154. local arg = pos[i]
  1155. print1(format1(format, arg["var"], arg["help"]))
  1156. i = i + 1
  1157. end
  1158. local forLimit = n1(opt)
  1159. local i = 1
  1160. while i <= forLimit do
  1161. local arg = opt[i]
  1162. print1(format1(format, concat2(arg["names"], ", "), arg["help"]))
  1163. i = i + 1
  1164. end
  1165. return nil
  1166. end
  1167. end
  1168. help_21_1 = function(spec, name)
  1169. if not name then
  1170. name = nth1(_2a_arguments_2a_1, 0) or (_2a_arguments_2a_1[-1] or "?")
  1171. end
  1172. usage_21_1(spec, name)
  1173. if spec["desc"] then
  1174. print1()
  1175. print1(spec["desc"])
  1176. end
  1177. local max = 0
  1178. local temp = spec["pos"]
  1179. local forLimit = n1(temp)
  1180. local i = 1
  1181. while i <= forLimit do
  1182. local len = n1(temp[i]["var"])
  1183. if len > max then
  1184. max = len
  1185. end
  1186. i = i + 1
  1187. end
  1188. local temp = spec["opt"]
  1189. local forLimit = n1(temp)
  1190. local i = 1
  1191. while i <= forLimit do
  1192. local len = n1(concat2(temp[i]["names"], ", "))
  1193. if len > max then
  1194. max = len
  1195. end
  1196. i = i + 1
  1197. end
  1198. local fmt = " %-" .. tostring1(max + 1) .. "s %s"
  1199. helpArgs_21_1(first1(partition1(function(x)
  1200. return x["cat"] == nil
  1201. end, (spec["pos"]))), first1(partition1(function(x)
  1202. return x["cat"] == nil
  1203. end, (spec["opt"]))), fmt)
  1204. local temp = spec["cats"]
  1205. local forLimit = n1(temp)
  1206. local i = 1
  1207. while i <= forLimit do
  1208. local cat = temp[i]
  1209. print1()
  1210. print1(coloured1("4", cat["name"]))
  1211. local desc = cat["desc"]
  1212. if desc then
  1213. print1(desc)
  1214. end
  1215. helpArgs_21_1(first1(partition1(function(x)
  1216. return x["cat"] == cat["id"]
  1217. end, (spec["pos"]))), first1(partition1(function(x)
  1218. return x["cat"] == cat["id"]
  1219. end, (spec["opt"]))), fmt)
  1220. i = i + 1
  1221. end
  1222. return nil
  1223. end
  1224. matcher1 = function(pattern)
  1225. return function(x)
  1226. local res = list1(match1(x, pattern))
  1227. if car1(res) == nil then
  1228. return nil
  1229. else
  1230. return res
  1231. end
  1232. end
  1233. end
  1234. parse_21_1 = function(spec, args)
  1235. if not args then
  1236. args = _2a_arguments_2a_1
  1237. end
  1238. local result, pos, posIdx, idx, len, usage_21_ = {}, spec["pos"], 1, 1, n1(args), function(msg)
  1239. usage_21_1(spec, (nth1(args, 0)))
  1240. print1(msg)
  1241. return exit_21_1(1)
  1242. end
  1243. local readArgs = function(key, arg)
  1244. local temp = arg["narg"]
  1245. if temp == "+" then
  1246. idx = idx + 1
  1247. local elem = nth1(args, idx)
  1248. if elem == nil then
  1249. local msg = "Expected " .. arg["var"] .. " after --" .. key .. ", got nothing"
  1250. usage_21_1(spec, (nth1(args, 0)))
  1251. print1(msg)
  1252. exit_21_1(1)
  1253. elseif not arg["all"] and find1(elem, "^%-") then
  1254. local msg = "Expected " .. arg["var"] .. " after --" .. key .. ", got " .. nth1(args, idx)
  1255. usage_21_1(spec, (nth1(args, 0)))
  1256. print1(msg)
  1257. exit_21_1(1)
  1258. else
  1259. arg["action"](arg, result, elem, usage_21_)
  1260. end
  1261. local running = true
  1262. while running do
  1263. idx = idx + 1
  1264. local elem = nth1(args, idx)
  1265. if elem == nil then
  1266. running = false
  1267. elseif not arg["all"] and find1(elem, "^%-") then
  1268. running = false
  1269. else
  1270. arg["action"](arg, result, elem, usage_21_)
  1271. end
  1272. end
  1273. return nil
  1274. elseif temp == "*" then
  1275. local running = true
  1276. while running do
  1277. idx = idx + 1
  1278. local elem = nth1(args, idx)
  1279. if elem == nil then
  1280. running = false
  1281. elseif not arg["all"] and find1(elem, "^%-") then
  1282. running = false
  1283. else
  1284. arg["action"](arg, result, elem, usage_21_)
  1285. end
  1286. end
  1287. return nil
  1288. elseif temp == "?" then
  1289. idx = idx + 1
  1290. local elem = nth1(args, idx)
  1291. if elem == nil or not arg["all"] and find1(elem, "^%-") then
  1292. return arg["action"](arg, result, arg["value"])
  1293. else
  1294. idx = idx + 1
  1295. return arg["action"](arg, result, elem, usage_21_)
  1296. end
  1297. elseif temp == 0 then
  1298. idx = idx + 1
  1299. local value = arg["value"]
  1300. return arg["action"](arg, result, value, usage_21_)
  1301. else
  1302. local i = 1
  1303. while i <= temp do
  1304. idx = idx + 1
  1305. local elem = nth1(args, idx)
  1306. if elem == nil then
  1307. local msg = "Expected " .. temp .. " args for " .. key .. ", got " .. i - 1
  1308. usage_21_1(spec, (nth1(args, 0)))
  1309. print1(msg)
  1310. exit_21_1(1)
  1311. elseif not arg["all"] and find1(elem, "^%-") then
  1312. local msg = "Expected " .. temp .. " for " .. key .. ", got " .. i - 1
  1313. usage_21_1(spec, (nth1(args, 0)))
  1314. print1(msg)
  1315. exit_21_1(1)
  1316. else
  1317. arg["action"](arg, result, elem, usage_21_)
  1318. end
  1319. i = i + 1
  1320. end
  1321. idx = idx + 1
  1322. return nil
  1323. end
  1324. end
  1325. while idx <= len do
  1326. local temp = nth1(args, idx)
  1327. local temp1
  1328. local temp2 = matcher1("^%-%-([^=]+)=(.+)$")(temp)
  1329. temp1 = type1(temp2) == "list" and (n1(temp2) >= 2 and (n1(temp2) <= 2 and true))
  1330. if temp1 then
  1331. local key, val = nth1(matcher1("^%-%-([^=]+)=(.+)$")(temp), 1), nth1(matcher1("^%-%-([^=]+)=(.+)$")(temp), 2)
  1332. local arg = spec["opt-map"][key]
  1333. if arg == nil then
  1334. local msg = "Unknown argument " .. key .. " in " .. nth1(args, idx)
  1335. usage_21_1(spec, (nth1(args, 0)))
  1336. print1(msg)
  1337. exit_21_1(1)
  1338. elseif not arg["many"] and nil ~= result[arg["name"]] then
  1339. local msg = "Too may values for " .. key .. " in " .. nth1(args, idx)
  1340. usage_21_1(spec, (nth1(args, 0)))
  1341. print1(msg)
  1342. exit_21_1(1)
  1343. else
  1344. local narg = arg["narg"]
  1345. if number_3f_1(narg) and narg ~= 1 then
  1346. local msg = "Expected " .. tostring1(narg) .. " values, got 1 in " .. nth1(args, idx)
  1347. usage_21_1(spec, (nth1(args, 0)))
  1348. print1(msg)
  1349. exit_21_1(1)
  1350. end
  1351. arg["action"](arg, result, val, usage_21_)
  1352. end
  1353. idx = idx + 1
  1354. else
  1355. local temp1
  1356. local temp2 = matcher1("^%-%-(.*)$")(temp)
  1357. temp1 = type1(temp2) == "list" and (n1(temp2) >= 1 and (n1(temp2) <= 1 and true))
  1358. if temp1 then
  1359. local key = nth1(matcher1("^%-%-(.*)$")(temp), 1)
  1360. local arg = spec["opt-map"][key]
  1361. if arg == nil then
  1362. local msg = "Unknown argument " .. key .. " in " .. nth1(args, idx)
  1363. usage_21_1(spec, (nth1(args, 0)))
  1364. print1(msg)
  1365. exit_21_1(1)
  1366. elseif not arg["many"] and nil ~= result[arg["name"]] then
  1367. local msg = "Too may values for " .. key .. " in " .. nth1(args, idx)
  1368. usage_21_1(spec, (nth1(args, 0)))
  1369. print1(msg)
  1370. exit_21_1(1)
  1371. else
  1372. readArgs(key, arg)
  1373. end
  1374. else
  1375. local temp1
  1376. local temp2 = matcher1("^%-(.+)$")(temp)
  1377. temp1 = type1(temp2) == "list" and (n1(temp2) >= 1 and (n1(temp2) <= 1 and true))
  1378. if temp1 then
  1379. local flags, i = nth1(matcher1("^%-(.+)$")(temp), 1), 1
  1380. local s = n1(flags)
  1381. while i <= s do
  1382. local key
  1383. local x = i
  1384. key = sub1(flags, x, x)
  1385. local arg = spec["flag-map"][key]
  1386. if arg == nil then
  1387. local msg = "Unknown flag " .. key .. " in " .. nth1(args, idx)
  1388. usage_21_1(spec, (nth1(args, 0)))
  1389. print1(msg)
  1390. exit_21_1(1)
  1391. elseif not arg["many"] and nil ~= result[arg["name"]] then
  1392. local msg = "Too many occurances of " .. key .. " in " .. nth1(args, idx)
  1393. usage_21_1(spec, (nth1(args, 0)))
  1394. print1(msg)
  1395. exit_21_1(1)
  1396. else
  1397. local narg = arg["narg"]
  1398. if i == s then
  1399. readArgs(key, arg)
  1400. elseif narg == 0 then
  1401. local value = arg["value"]
  1402. arg["action"](arg, result, value, usage_21_)
  1403. else
  1404. local value = sub1(flags, i + 1)
  1405. arg["action"](arg, result, value, usage_21_)
  1406. i = s + 1
  1407. idx = idx + 1
  1408. end
  1409. end
  1410. i = i + 1
  1411. end
  1412. else
  1413. local arg = nth1(pos, posIdx)
  1414. if arg then
  1415. idx = idx - 1
  1416. readArgs(arg["var"], arg)
  1417. if not arg["many"] then
  1418. posIdx = posIdx + 1
  1419. end
  1420. else
  1421. local msg = "Unknown argument " .. temp
  1422. usage_21_1(spec, (nth1(args, 0)))
  1423. print1(msg)
  1424. exit_21_1(1)
  1425. end
  1426. end
  1427. end
  1428. end
  1429. end
  1430. local temp = spec["opt"]
  1431. local forLimit = n1(temp)
  1432. local i = 1
  1433. while i <= forLimit do
  1434. local arg = temp[i]
  1435. if result[arg["name"]] == nil then
  1436. result[arg["name"]] = arg["default"]
  1437. end
  1438. i = i + 1
  1439. end
  1440. local temp = spec["pos"]
  1441. local forLimit = n1(temp)
  1442. local i = 1
  1443. while i <= forLimit do
  1444. local arg = temp[i]
  1445. if result[arg["name"]] == nil then
  1446. result[arg["name"]] = arg["default"]
  1447. end
  1448. i = i + 1
  1449. end
  1450. return result
  1451. end
  1452. range_3c_1 = function(a, b)
  1453. if a["name"] == b["name"] then
  1454. return a["start"]["offset"] < b["start"]["offset"]
  1455. else
  1456. return a["name"] < b["name"]
  1457. end
  1458. end
  1459. rangeOfStart1 = function(range)
  1460. if type1(range) ~= "range" then
  1461. error1(demandFailure1(nil, "(= (type range) \"range\")"))
  1462. end
  1463. return {tag="range", name=range["name"], start=range["start"], finish=range["start"], lines=range["lines"]}
  1464. end
  1465. rangeOfSpan1 = function(from, to)
  1466. if type1(from) ~= "range" then
  1467. error1(demandFailure1(nil, "(= (type from) \"range\")"))
  1468. end
  1469. if type1(to) ~= "range" then
  1470. error1(demandFailure1(nil, "(= (type to) \"range\")"))
  1471. end
  1472. return {tag="range", name=from["name"], start=from["start"], finish=to["finish"], lines=from["lines"]}
  1473. end
  1474. nodeSource_3f_1 = function(nodeSource)
  1475. return type_23_1(nodeSource) == "table" and nodeSource["tag"] == "node-source"
  1476. end
  1477. sourceFullRange1 = function(source)
  1478. local temp = type1(source)
  1479. if temp == "node-source" then
  1480. return source["range"]
  1481. elseif temp == "range" then
  1482. return source
  1483. elseif temp == "nil" then
  1484. return nil
  1485. else
  1486. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"node-source\"`\n Tried: `\"range\"`\n Tried: `\"nil\"`")
  1487. end
  1488. end
  1489. sourceRange1 = function(source)
  1490. while true do
  1491. local temp = type1(source)
  1492. if temp == "node-source" then
  1493. source = source["parent"]
  1494. elseif temp == "range" then
  1495. return source
  1496. elseif temp == "nil" then
  1497. return nil
  1498. else
  1499. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"node-source\"`\n Tried: `\"range\"`\n Tried: `\"nil\"`")
  1500. end
  1501. end
  1502. end
  1503. getSource1 = function(node)
  1504. return sourceRange1(node["source"])
  1505. end
  1506. append_21_1 = function(writer, text, position)
  1507. if type1(text) ~= "string" then
  1508. error1(demandFailure1(nil, "(= (type text) \"string\")"))
  1509. end
  1510. if position then
  1511. local line = writer["lines"][writer["line"]]
  1512. if not line then
  1513. line = {}
  1514. writer["lines"][writer["line"]] = line
  1515. end
  1516. line[position] = true
  1517. end
  1518. if writer["tabs-pending"] then
  1519. writer["tabs-pending"] = false
  1520. push_21_1(writer["out"], rep1(" ", writer["indent"]))
  1521. end
  1522. return push_21_1(writer["out"], text)
  1523. end
  1524. line_21_1 = function(writer, text, force)
  1525. if text then
  1526. append_21_1(writer, text)
  1527. end
  1528. if force or not writer["tabs-pending"] then
  1529. writer["tabs-pending"] = true
  1530. writer["line"] = writer["line"] + 1
  1531. return push_21_1(writer["out"], "\n")
  1532. else
  1533. return nil
  1534. end
  1535. end
  1536. beginBlock_21_1 = function(writer, text)
  1537. line_21_1(writer, text)
  1538. writer["indent"] = writer["indent"] + 1
  1539. return writer
  1540. end
  1541. nextBlock_21_1 = function(writer, text)
  1542. writer["indent"] = writer["indent"] - 1
  1543. line_21_1(writer, text)
  1544. writer["indent"] = writer["indent"] + 1
  1545. return writer
  1546. end
  1547. endBlock_21_1 = function(writer, text)
  1548. writer["indent"] = writer["indent"] - 1
  1549. return line_21_1(writer, text)
  1550. end
  1551. pushNode_21_1 = function(writer, node)
  1552. local range = sourceRange1(node["source"])
  1553. if range then
  1554. push_21_1(writer["node-stack"], range)
  1555. writer["active-pos"] = range
  1556. return nil
  1557. else
  1558. return nil
  1559. end
  1560. end
  1561. popNode_21_1 = function(writer, node)
  1562. local range = sourceRange1(node["source"])
  1563. if range then
  1564. local stack = writer["node-stack"]
  1565. if last1(stack) ~= range then
  1566. error1("Incorrect node popped")
  1567. end
  1568. popLast_21_1(stack)
  1569. writer["active-pos"] = last1(stack)
  1570. return nil
  1571. else
  1572. return nil
  1573. end
  1574. end
  1575. create2 = coroutine.create
  1576. resume1 = coroutine.resume
  1577. status1 = coroutine.status
  1578. yield1 = coroutine.yield
  1579. putNodeError_21_1 = function(logger, msg, source, explain, ...)
  1580. local lines = _pack(...) lines.tag = "list"
  1581. return self1(logger, "put-node-error!", msg, source, explain, lines)
  1582. end
  1583. putNodeWarning_21_1 = function(logger, msg, source, explain, ...)
  1584. local lines = _pack(...) lines.tag = "list"
  1585. return self1(logger, "put-node-warning!", msg, source, explain, lines)
  1586. end
  1587. tracebackPlain1 = function(...)
  1588. local args = _pack(...) args.tag = "list"
  1589. if traceback1 then
  1590. return apply1(traceback1, args)
  1591. elseif empty_3f_1(args) then
  1592. return ""
  1593. else
  1594. return car1(args)
  1595. end
  1596. end
  1597. traceback2 = function(msg)
  1598. if not string_3f_1(msg) then
  1599. msg = pretty1(msg)
  1600. end
  1601. return tracebackPlain1(msg, 2)
  1602. end
  1603. truncateTraceback1 = function(trace)
  1604. local there, here = split1(trace, "\n"), split1(tracebackPlain1(), "\n")
  1605. local i = min1(n1(here), n1(there))
  1606. while true do
  1607. if i <= 1 then
  1608. break
  1609. elseif nth1(here, i) == nth1(there, i) then
  1610. removeNth_21_1(here, i)
  1611. i = i - 1
  1612. else
  1613. break
  1614. end
  1615. end
  1616. local i = n1(there)
  1617. while true do
  1618. if i <= 1 then
  1619. break
  1620. elseif nth1(there, i) == "\9[C]: in function 'xpcall1'" or nth1(there, i) == "\9[C]: in function 'xpcall'" then
  1621. local forStart = n1(there)
  1622. local j = forStart
  1623. while j >= i do
  1624. removeNth_21_1(there, j)
  1625. j = j + -1
  1626. end
  1627. break
  1628. else
  1629. i = i - 1
  1630. end
  1631. end
  1632. return concat2(there, "\n")
  1633. end
  1634. unmangleIdent1 = function(ident)
  1635. local esc = match1(ident, "^(.-)%d+$")
  1636. if esc == nil then
  1637. return ident
  1638. elseif sub1(esc, 1, 2) == "_e" then
  1639. return sub1(ident, 3)
  1640. else
  1641. local buffer, pos, len = {tag="list", n=0}, 0, n1(esc)
  1642. while pos <= len do
  1643. local char
  1644. local x = pos
  1645. char = sub1(esc, x, x)
  1646. if char == "_" then
  1647. local temp = list1(find1(esc, "^_[%da-z]+_", pos))
  1648. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and true)) then
  1649. local start, _eend = nth1(temp, 1), nth1(temp, 2)
  1650. pos = pos + 1
  1651. while pos < _eend do
  1652. push_21_1(buffer, char1(tonumber1(sub1(esc, pos, pos + 1), 16)))
  1653. pos = pos + 2
  1654. end
  1655. else
  1656. push_21_1(buffer, "_")
  1657. end
  1658. elseif between_3f_1(char, "A", "Z") then
  1659. push_21_1(buffer, "-")
  1660. push_21_1(buffer, lower1(char))
  1661. else
  1662. push_21_1(buffer, char)
  1663. end
  1664. pos = pos + 1
  1665. end
  1666. return concat2(buffer)
  1667. end
  1668. end
  1669. remapError1 = function(msg)
  1670. return (gsub1(gsub1(gsub1(gsub1(msg, "local '([^']+)'", function(x)
  1671. return "local '" .. unmangleIdent1(x) .. "'"
  1672. end), "global '([^']+)'", function(x)
  1673. return "global '" .. unmangleIdent1(x) .. "'"
  1674. end), "upvalue '([^']+)'", function(x)
  1675. return "upvalue '" .. unmangleIdent1(x) .. "'"
  1676. end), "function '([^']+)'", function(x)
  1677. return "function '" .. unmangleIdent1(x) .. "'"
  1678. end))
  1679. end
  1680. remapMessage1 = function(mappings, msg)
  1681. local temp = list1(match1(msg, "^(.-):(%d+)(.*)$"))
  1682. if type1(temp) == "list" and (n1(temp) >= 3 and (n1(temp) <= 3 and true)) then
  1683. local file, line, extra = nth1(temp, 1), nth1(temp, 2), nth1(temp, 3)
  1684. local mapping = mappings[file]
  1685. if mapping then
  1686. local range = mapping[tonumber1(line)]
  1687. if range then
  1688. return range .. " (" .. file .. ":" .. line .. ")" .. remapError1(extra)
  1689. else
  1690. return msg
  1691. end
  1692. else
  1693. return msg
  1694. end
  1695. else
  1696. return msg
  1697. end
  1698. end
  1699. remapTraceback1 = function(mappings, msg)
  1700. return gsub1(gsub1(gsub1(gsub1(gsub1(gsub1(gsub1(truncateTraceback1(msg), "^([^\n:]-:%d+:[^\n]*)", function(temp)
  1701. return remapMessage1(mappings, temp)
  1702. end), "\9([^\n:]-:%d+:)", function(msg1)
  1703. return "\9" .. remapMessage1(mappings, msg1)
  1704. end), "<([^\n:]-:%d+)>\n", function(msg1)
  1705. return "<" .. remapMessage1(mappings, msg1) .. ">\n"
  1706. end), "in local '([^']+)'\n", function(x)
  1707. return "in local '" .. unmangleIdent1(x) .. "'\n"
  1708. end), "in global '([^']+)'\n", function(x)
  1709. return "in global '" .. unmangleIdent1(x) .. "'\n"
  1710. end), "in upvalue '([^']+)'\n", function(x)
  1711. return "in upvalue '" .. unmangleIdent1(x) .. "'\n"
  1712. end), "in function '([^']+)'\n", function(x)
  1713. return "in function '" .. unmangleIdent1(x) .. "'\n"
  1714. end)
  1715. end
  1716. generateMappings1 = function(lines)
  1717. local outLines = {}
  1718. local temp, ranges = next1(lines)
  1719. while temp ~= nil do
  1720. local rangeLists = {}
  1721. local temp1 = next1(ranges)
  1722. while temp1 ~= nil do
  1723. local file = temp1["name"]
  1724. local rangeList = rangeLists[file]
  1725. if not rangeList then
  1726. rangeList = {n=0, min=huge1, max=0 - huge1}
  1727. rangeLists[file] = rangeList
  1728. end
  1729. local forStart, forLimit = temp1["start"]["line"], temp1["finish"]["line"]
  1730. local i = forStart
  1731. while i <= forLimit do
  1732. if not rangeList[i] then
  1733. rangeList["n"] = rangeList["n"] + 1
  1734. rangeList[i] = true
  1735. if i < rangeList["min"] then
  1736. rangeList["min"] = i
  1737. end
  1738. if i > rangeList["max"] then
  1739. rangeList["max"] = i
  1740. end
  1741. end
  1742. i = i + 1
  1743. end
  1744. temp1 = next1(ranges, temp1)
  1745. end
  1746. local bestName, bestLines, bestCount = nil, nil, 0
  1747. local temp1, lines1 = next1(rangeLists)
  1748. while temp1 ~= nil do
  1749. if lines1["n"] > bestCount then
  1750. bestName = temp1
  1751. bestLines = lines1
  1752. bestCount = lines1["n"]
  1753. end
  1754. temp1, lines1 = next1(rangeLists, temp1)
  1755. end
  1756. outLines[temp] = (function()
  1757. if bestLines["min"] == bestLines["max"] then
  1758. return format1("%s:%d", bestName, bestLines["min"])
  1759. else
  1760. return format1("%s:%d-%d", bestName, bestLines["min"], bestLines["max"])
  1761. end
  1762. end)()
  1763. temp, ranges = next1(lines, temp)
  1764. end
  1765. return outLines
  1766. end
  1767. metatable1 = {__tostring=function(self)
  1768. return self["message"]
  1769. end}
  1770. compilerError_3f_1 = function(err)
  1771. return type_23_1(err) == "table" and getmetatable1(err) == metatable1
  1772. end
  1773. compilerError_21_1 = function(message)
  1774. if type1(message) ~= "string" then
  1775. error1(demandFailure1(nil, "(= (type message) \"string\")"))
  1776. end
  1777. return error1(setmetatable1({type="compiler-error", message=message}, metatable1))
  1778. end
  1779. doNodeError_21_1 = function(logger, msg, source, explain, ...)
  1780. local lines = _pack(...) lines.tag = "list"
  1781. apply1(putNodeError_21_1, logger, msg, source, explain, lines)
  1782. return compilerError_21_1(match1(msg, "^([^\n]+)\n") or msg)
  1783. end
  1784. traceback3 = function(err)
  1785. if compilerError_3f_1(err) then
  1786. return err
  1787. elseif string_3f_1(err) then
  1788. return tracebackPlain1(err, 2)
  1789. else
  1790. return tracebackPlain1(pretty1(err), 2)
  1791. end
  1792. end
  1793. parseTemplate1 = function(template)
  1794. local buffer, idx, max, len = {tag="list", n=0}, 0, 0, n1(template)
  1795. while idx <= len do
  1796. local start, finish = find1(template, "%${(%d+)}", idx)
  1797. if start then
  1798. if start > idx then
  1799. push_21_1(buffer, sub1(template, idx, start - 1))
  1800. end
  1801. local val = tonumber1(sub1(template, start + 2, finish - 1))
  1802. push_21_1(buffer, val)
  1803. if val > max then
  1804. max = val
  1805. end
  1806. idx = finish + 1
  1807. else
  1808. push_21_1(buffer, sub1(template, idx, len))
  1809. idx = len + 1
  1810. end
  1811. end
  1812. return splice1(list1(buffer, max))
  1813. end
  1814. child1 = function(parent, kind)
  1815. if parent ~= nil then
  1816. if type1(parent) ~= "scope" then
  1817. error1(demandFailure1(nil, "(= (type parent) \"scope\")"))
  1818. end
  1819. end
  1820. if kind == nil then
  1821. kind = "normal"
  1822. elseif kind == "normal" or kind == "top-level" or kind == "builtin" then
  1823. else
  1824. formatOutput_21_1(1, "Unknown scope kind " .. display1(kind))
  1825. end
  1826. return {tag="scope", parent=parent, kind=kind, variables={}, exported={}, prefix=(function()
  1827. if parent then
  1828. return parent["prefix"]
  1829. else
  1830. return ""
  1831. end
  1832. end)(), ["unique-prefix"]=(function()
  1833. if parent then
  1834. return parent["unique-prefix"]
  1835. else
  1836. return ""
  1837. end
  1838. end)()}
  1839. end
  1840. var1 = function(name, kind, scope, node)
  1841. if type1(name) ~= "string" then
  1842. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1843. end
  1844. if type1(kind) ~= "string" then
  1845. error1(demandFailure1(nil, "(= (type kind) \"string\")"))
  1846. end
  1847. if type1(scope) ~= "scope" then
  1848. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  1849. end
  1850. return {tag="var", name=name, kind=kind, scope=scope, ["full-name"]=scope["prefix"] .. name, ["unique-name"]=scope["unique-prefix"] .. name, node=node, const=kind ~= "arg", ["is-variadic"]=false, doc=nil, ["display-name"]=nil, deprecated=false, intrinsic=nil, native=nil}
  1851. end
  1852. varDoc1 = function(var)
  1853. return var["doc"]
  1854. end
  1855. varNative1 = function(var)
  1856. if var["kind"] ~= "native" then
  1857. error1(demandFailure1("VAR must be a native definition.", "(= (var-kind var) \"native\")"))
  1858. end
  1859. local vNative = var["native"]
  1860. if not vNative then
  1861. vNative = {tag="native", pure=false, signature=nil, ["bind-to"]=nil, syntax=nil, ["syntax-arity"]=nil, ["syntax-fold"]=nil, ["syntax-stmt"]=false, ["syntax-precedence"]=nil}
  1862. setVarNative_21_1(var, vNative)
  1863. end
  1864. return vNative
  1865. end
  1866. setVarNative_21_1 = function(var, native)
  1867. if type1(native) ~= "native" then
  1868. error1(demandFailure1(nil, "(= (type native) \"native\")"))
  1869. end
  1870. if var["kind"] ~= "native" then
  1871. error1(demandFailure1("VAR must be a native definition.", "(= (var-kind var) \"native\")"))
  1872. end
  1873. if var["native"] ~= nil then
  1874. error1(demandFailure1("VAR already has native metadata.", "(= (var-native# var) nil)"))
  1875. end
  1876. var["native"] = native
  1877. return nil
  1878. end
  1879. lookup1 = function(scope, name)
  1880. while true do
  1881. if scope then
  1882. local temp = scope["variables"][name]
  1883. if temp then
  1884. return temp
  1885. else
  1886. scope = scope["parent"]
  1887. end
  1888. else
  1889. return nil
  1890. end
  1891. end
  1892. end
  1893. lookupAlways_21_1 = function(scope, name, user)
  1894. return lookup1(scope, name) or yield1({tag="define", name=name, node=user, scope=scope})
  1895. end
  1896. _2a_tempScope_2a_1 = child1()
  1897. tempVar1 = function(name, node)
  1898. return var1(name or "temp", "arg", _2a_tempScope_2a_1, node)
  1899. end
  1900. kinds1 = {defined=true, native=true, macro=true, arg=true, builtin=true}
  1901. add_21_1 = function(scope, name, kind, node)
  1902. if type1(scope) ~= "scope" then
  1903. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  1904. end
  1905. if type1(name) ~= "string" then
  1906. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1907. end
  1908. if type1(kind) ~= "string" then
  1909. error1(demandFailure1(nil, "(= (type kind) \"string\")"))
  1910. end
  1911. if not kinds1[kind] then
  1912. formatOutput_21_1(1, "Unknown kind " .. display1(kind))
  1913. end
  1914. if scope["variables"][name] then
  1915. formatOutput_21_1(1, "Previous declaration of " .. display1(name))
  1916. end
  1917. if name == "_" and scope["kind"] == "top-level" then
  1918. error1("Cannot declare \"_\" as a top level definition", 0)
  1919. end
  1920. local var = var1(name, kind, scope, node)
  1921. if not (name == "_") then
  1922. scope["variables"][name] = var
  1923. scope["exported"][name] = var
  1924. end
  1925. return var
  1926. end
  1927. addVerbose_21_1 = function(scope, name, kind, node, logger)
  1928. if type1(scope) ~= "scope" then
  1929. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  1930. end
  1931. if type1(name) ~= "string" then
  1932. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1933. end
  1934. if type1(kind) ~= "string" then
  1935. error1(demandFailure1(nil, "(= (type kind) \"string\")"))
  1936. end
  1937. if not kinds1[kind] then
  1938. formatOutput_21_1(1, "Unknown kind " .. display1(kind))
  1939. end
  1940. local previous = scope["variables"][name]
  1941. if previous then
  1942. doNodeError_21_1(logger, "Previous declaration of " .. quoted1(name), node["source"], nil, sourceRange1(node["source"]), "new definition here", sourceRange1(previous["node"]["source"]), "old definition here")
  1943. end
  1944. if name == "_" and scope["kind"] == "top-level" then
  1945. doNodeError_21_1(logger, "Cannot declare \"_\" as a top level definition", node["source"], nil, sourceRange1(node["source"]), "declared here")
  1946. end
  1947. return add_21_1(scope, name, kind, node)
  1948. end
  1949. import_21_1 = function(scope, name, var, export)
  1950. if type1(scope) ~= "scope" then
  1951. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  1952. end
  1953. if type1(name) ~= "string" then
  1954. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1955. end
  1956. if type1(var) ~= "var" then
  1957. error1(demandFailure1(nil, "(= (type var) \"var\")"))
  1958. end
  1959. if scope["variables"][name] and scope["variables"][name] ~= var then
  1960. formatOutput_21_1(1, "Previous declaration of " .. display1(name))
  1961. end
  1962. scope["variables"][name] = var
  1963. if export then
  1964. scope["exported"][name] = var
  1965. end
  1966. return var
  1967. end
  1968. importVerbose_21_1 = function(scope, name, var, node, export, logger)
  1969. if type1(scope) ~= "scope" then
  1970. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  1971. end
  1972. if type1(name) ~= "string" then
  1973. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  1974. end
  1975. if type1(var) ~= "var" then
  1976. error1(demandFailure1(nil, "(= (type var) \"var\")"))
  1977. end
  1978. if scope["variables"][name] and scope["variables"][name] ~= var then
  1979. doNodeError_21_1(logger, "Previous declaration of " .. name, node["source"], nil, sourceRange1(node["source"]), "imported here", sourceRange1(var["node"]["source"]), "new definition here", sourceRange1(scope["variables"][name]["node"]["source"]), "old definition here")
  1980. end
  1981. return import_21_1(scope, name, var, export)
  1982. end
  1983. rootScope1 = child1(nil, "builtin")
  1984. builtins1 = {}
  1985. builtinVars1 = {}
  1986. local temp = {tag="list", n=12, "define", "define-macro", "define-native", "lambda", "set!", "cond", "import", "struct-literal", "quote", "syntax-quote", "unquote", "unquote-splice"}
  1987. local forLimit = n1(temp)
  1988. local i = 1
  1989. while i <= forLimit do
  1990. local symbol = temp[i]
  1991. local var = add_21_1(rootScope1, symbol, "builtin", nil)
  1992. import_21_1(rootScope1, "builtin/" .. symbol, var, true)
  1993. builtins1[symbol] = var
  1994. i = i + 1
  1995. end
  1996. local temp = {tag="list", n=3, "nil", "true", "false"}
  1997. local forLimit = n1(temp)
  1998. local i = 1
  1999. while i <= forLimit do
  2000. local symbol = temp[i]
  2001. local var = add_21_1(rootScope1, symbol, "defined", nil)
  2002. import_21_1(rootScope1, "builtin/" .. symbol, var, true)
  2003. builtinVars1[var] = true
  2004. builtins1[symbol] = var
  2005. i = i + 1
  2006. end
  2007. builtin1 = function(name)
  2008. return builtins1[name]
  2009. end
  2010. builtin_3f_1 = function(node, name)
  2011. return type1(node) == "symbol" and node["var"] == builtins1[name]
  2012. end
  2013. sideEffect_3f_1 = function(node)
  2014. local tag = type1(node)
  2015. if tag == "number" or tag == "string" or tag == "key" or tag == "symbol" then
  2016. return false
  2017. elseif tag == "list" then
  2018. local head = car1(node)
  2019. local temp = type1(head) ~= "symbol"
  2020. if temp then
  2021. return temp
  2022. else
  2023. local var = head["var"]
  2024. if var["kind"] ~= "builtin" then
  2025. return true
  2026. elseif var == builtins1["lambda"] then
  2027. return false
  2028. elseif var == builtins1["quote"] then
  2029. return false
  2030. elseif var == builtins1["struct-literal"] then
  2031. return n1(node) ~= 1
  2032. else
  2033. return true
  2034. end
  2035. end
  2036. else
  2037. _error("unmatched item")
  2038. end
  2039. end
  2040. constant_3f_1 = function(node)
  2041. return string_3f_1(node) or (number_3f_1(node) or type1(node) == "key")
  2042. end
  2043. urn_2d3e_val1 = function(node)
  2044. if string_3f_1(node) then
  2045. return node["value"]
  2046. elseif number_3f_1(node) then
  2047. return node["value"]
  2048. elseif type1(node) == "key" then
  2049. return node["value"]
  2050. else
  2051. _error("unmatched item")
  2052. end
  2053. end
  2054. val_2d3e_urn1 = function(val)
  2055. local ty = type_23_1(val)
  2056. if ty == "string" then
  2057. return {tag="string", value=val}
  2058. elseif ty == "number" then
  2059. return {tag="number", value=val}
  2060. elseif ty == "nil" then
  2061. return {tag="symbol", contents="nil", var=builtins1["nil"]}
  2062. elseif ty == "boolean" then
  2063. return {tag="symbol", contents=tostring1(val), var=builtins1[(tostring1(val))]}
  2064. else
  2065. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(ty) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"nil\"`\n Tried: `\"boolean\"`")
  2066. end
  2067. end
  2068. urn_2d3e_bool1 = function(node)
  2069. if string_3f_1(node) or type1(node) == "key" or number_3f_1(node) then
  2070. return true
  2071. elseif type1(node) == "symbol" then
  2072. if builtins1["true"] == node["var"] then
  2073. return true
  2074. elseif builtins1["false"] == node["var"] then
  2075. return false
  2076. elseif builtins1["nil"] == node["var"] then
  2077. return false
  2078. else
  2079. return nil
  2080. end
  2081. else
  2082. return nil
  2083. end
  2084. end
  2085. makeProgn1 = function(body)
  2086. return {tag="list", n=1, (function()
  2087. local _offset, _result, _temp = 0, {tag="list"}
  2088. _result[1 + _offset] = (function()
  2089. local var = builtins1["lambda"]
  2090. return {tag="symbol", contents=var["name"], var=var}
  2091. end)()
  2092. _result[2 + _offset] = {tag="list", n=0}
  2093. _temp = body
  2094. for _c = 1, _temp.n do _result[2 + _c + _offset] = _temp[_c] end
  2095. _offset = _offset + _temp.n
  2096. _result.n = _offset + 2
  2097. return _result
  2098. end)()
  2099. }
  2100. end
  2101. makeSymbol1 = function(var)
  2102. return {tag="symbol", contents=var["name"], var=var}
  2103. end
  2104. local temp = builtins1["nil"]
  2105. makeNil1 = function()
  2106. return {tag="symbol", contents=temp["name"], var=temp}
  2107. end
  2108. simpleBinding_3f_1 = function(node)
  2109. local temp = type1(node) == "list"
  2110. if temp then
  2111. local lam = car1(node)
  2112. return type1(lam) == "list" and (builtin_3f_1(car1(lam), "lambda") and all1(function(x)
  2113. return not x["var"]["is-variadic"]
  2114. end, nth1(lam, 2)))
  2115. else
  2116. return temp
  2117. end
  2118. end
  2119. singleReturn_3f_1 = function(node)
  2120. while true do
  2121. local temp = type1(node) ~= "list"
  2122. if temp then
  2123. return temp
  2124. else
  2125. local head = car1(node)
  2126. local temp1 = type1(head)
  2127. if temp1 == "symbol" then
  2128. local func = head["var"]
  2129. if func["kind"] ~= "builtin" then
  2130. return false
  2131. elseif func == builtins1["lambda"] then
  2132. return true
  2133. elseif func == builtins1["struct-literal"] then
  2134. return true
  2135. elseif func == builtins1["quote"] then
  2136. return true
  2137. elseif func == builtins1["syntax-quote"] then
  2138. return true
  2139. else
  2140. return false
  2141. end
  2142. elseif temp1 == "list" then
  2143. local temp2 = builtin_3f_1(car1(head), "lambda")
  2144. if temp2 then
  2145. local temp3 = n1(head) >= 3
  2146. if temp3 then
  2147. node = last1(head)
  2148. else
  2149. return temp3
  2150. end
  2151. else
  2152. return temp2
  2153. end
  2154. else
  2155. return false
  2156. end
  2157. end
  2158. end
  2159. end
  2160. fastAll1 = function(fn, li, i)
  2161. while true do
  2162. if i > n1(li) then
  2163. return true
  2164. elseif fn(nth1(li, i)) then
  2165. i = i + 1
  2166. else
  2167. return false
  2168. end
  2169. end
  2170. end
  2171. fastAny1 = function(fn, li, i)
  2172. while true do
  2173. if i > n1(li) then
  2174. return false
  2175. elseif fn(nth1(li, i)) then
  2176. return true
  2177. else
  2178. i = i + 1
  2179. end
  2180. end
  2181. end
  2182. zipArgs1 = function(args, argsStart, vals, valsStart)
  2183. local res, an, vn, _ = {tag="list", n=0}, n1(args), n1(vals)
  2184. local ai, vi = argsStart, valsStart
  2185. while true do
  2186. if ai > an and vi > vn then
  2187. return res
  2188. else
  2189. local arg = args[ai]
  2190. if not arg then
  2191. push_21_1(res, list1({tag="list", n=0}, list1(nth1(vals, vi))))
  2192. vi = vi + 1
  2193. elseif vi > vn then
  2194. push_21_1(res, list1(list1(arg), {tag="list", n=0}))
  2195. ai = ai + 1
  2196. elseif arg["var"]["is-variadic"] then
  2197. if singleReturn_3f_1(nth1(vals, vn)) then
  2198. local vEnd = vn - (an - ai)
  2199. if vEnd < vi then
  2200. vEnd = vi - 1
  2201. end
  2202. push_21_1(res, list1(list1(arg), slice1(vals, vi, vEnd)))
  2203. ai, vi = ai + 1, vEnd + 1
  2204. else
  2205. return push_21_1(res, list1(slice1(args, ai), slice1(vals, vi)))
  2206. end
  2207. elseif vi < vn or singleReturn_3f_1(nth1(vals, vi)) then
  2208. push_21_1(res, list1(list1(arg), list1(nth1(vals, vi))))
  2209. ai, vi = ai + 1, vi + 1
  2210. else
  2211. return push_21_1(res, list1(slice1(args, ai), list1(nth1(vals, vi))))
  2212. end
  2213. end
  2214. end
  2215. end
  2216. tokens1 = {tag="list", n=7, {tag="list", n=2, "arg", "(%f[%a][%u-]+%f[^%a%d%-])"}, {tag="list", n=2, "mono", "```[^\n]*\n(.-)\n```"}, {tag="list", n=2, "mono", "`([^`\n]*)`"}, {tag="list", n=2, "bolic", "(%*%*%*%w.-%w%*%*%*)"}, {tag="list", n=2, "bold", "(%*%*%w.-%w%*%*)"}, {tag="list", n=2, "italic", "(%*%w.-%w%*)"}, {tag="list", n=2, "link", "%[%[([^\n]-)%]%]"}}
  2217. stars1 = {text=0, italic=1, bold=2, bolid=3}
  2218. extractSignature1 = function(var, history)
  2219. local ty = var["kind"]
  2220. if history and history[var] then
  2221. return nil
  2222. elseif ty == "macro" or ty == "defined" then
  2223. local root = var["node"]
  2224. if root then
  2225. local node = nth1(root, n1(root))
  2226. while true do
  2227. if not node then
  2228. return nil
  2229. elseif type1(node) == "symbol" then
  2230. if not history then
  2231. history = {}
  2232. end
  2233. history[var] = true
  2234. return extractSignature1(node["var"], history)
  2235. elseif type1(node) == "list" and builtin_3f_1(car1(node), "lambda") then
  2236. return map2(function(sym)
  2237. return sym["display-name"] or sym["contents"]
  2238. end, nth1(node, 2))
  2239. elseif type1(node) == "list" and (type1((car1(node))) == "list" and (builtin_3f_1(caar1(node), "lambda") and n1(car1(node)) >= 3)) then
  2240. node = last1(car1(node))
  2241. else
  2242. return nil
  2243. end
  2244. end
  2245. else
  2246. return nil
  2247. end
  2248. elseif ty == "native" then
  2249. local sig = varNative1(var)["signature"]
  2250. if sig then
  2251. return map2(function(sym)
  2252. return sym["display-name"] or sym["contents"]
  2253. end, sig)
  2254. else
  2255. return nil
  2256. end
  2257. else
  2258. return nil
  2259. end
  2260. end
  2261. parseDocstring1 = function(str)
  2262. local out, pos, len = {tag="list", n=0}, 1, n1(str)
  2263. while pos <= len do
  2264. local spos, epos, name, ptrn = len, nil, nil, nil
  2265. local forLimit = n1(tokens1)
  2266. local i = 1
  2267. while i <= forLimit do
  2268. local tok = tokens1[i]
  2269. local npos = list1(find1(str, nth1(tok, 2), pos))
  2270. if car1(npos) and car1(npos) < spos then
  2271. spos = car1(npos)
  2272. epos = nth1(npos, 2)
  2273. name = car1(tok)
  2274. ptrn = nth1(tok, 2)
  2275. end
  2276. i = i + 1
  2277. end
  2278. if name then
  2279. if pos < spos then
  2280. push_21_1(out, {kind="text", contents=sub1(str, pos, spos - 1)})
  2281. end
  2282. push_21_1(out, {kind=name, whole=sub1(str, spos, epos), contents=match1(sub1(str, spos, epos), ptrn)})
  2283. pos = epos + 1
  2284. else
  2285. push_21_1(out, {kind="text", contents=sub1(str, pos, len)})
  2286. pos = len + 1
  2287. end
  2288. end
  2289. return out
  2290. end
  2291. extractSummary1 = function(toks)
  2292. local result = {tag="list", n=0}
  2293. local i = 1
  2294. while true do
  2295. if (i > n1(toks)) then
  2296. break
  2297. else
  2298. local tok = nth1(toks, i)
  2299. local kind = tok["kind"]
  2300. if kind == "mono" then
  2301. if sub1(tok["whole"], 1, 3) == "```" then
  2302. push_21_1(result, {kind="text", contents="..."})
  2303. break
  2304. else
  2305. push_21_1(result, tok)
  2306. i = i + 1
  2307. end
  2308. elseif kind == "arg" or kind == "link" then
  2309. push_21_1(result, tok)
  2310. i = i + 1
  2311. else
  2312. local newline, sentence = find1(tok["contents"], "\n\n"), find1(tok["contents"], "[.!?]")
  2313. local _eend
  2314. if newline and sentence then
  2315. _eend = min1(newline - 1, sentence)
  2316. elseif newline then
  2317. _eend = newline - 1
  2318. else
  2319. _eend = sentence
  2320. end
  2321. if _eend then
  2322. push_21_1(result, {kind=kind, contents=gsub1(sub1(tok["contents"], 1, _eend), "\n", " ") .. rep1("*", stars1[kind])})
  2323. break
  2324. else
  2325. push_21_1(result, {kind=kind, contents=gsub1(tok["contents"], "\n", " "), whole=tok["whole"] and gsub1(tok["whole"], "\n", " ")})
  2326. i = i + 1
  2327. end
  2328. end
  2329. end
  2330. end
  2331. return result
  2332. end
  2333. libraryCache1 = function()
  2334. return {tag="library-cache", values={}, metas={}, paths={}, names={}, loaded={tag="list", n=0}}
  2335. end
  2336. libraryOf1 = function(name, uniqueName, path, parentScope)
  2337. return {tag="library", name=name, ["unique-name"]=uniqueName, path=path, scope=scopeForLibrary1(parentScope, name, uniqueName), nodes=nil, docs=nil, ["lisp-lines"]=nil, ["lua-contents"]=nil, depends={}}
  2338. end
  2339. libraryName1 = function(library)
  2340. return library["name"]
  2341. end
  2342. scopeForLibrary1 = function(parent, name, uniqueName)
  2343. if type1(name) ~= "string" then
  2344. error1(demandFailure1(nil, "(= (type name) \"string\")"))
  2345. end
  2346. if type1(uniqueName) ~= "string" then
  2347. error1(demandFailure1(nil, "(= (type unique-name) \"string\")"))
  2348. end
  2349. local scope = child1(parent, "top-level")
  2350. scope["prefix"] = (name .. "/")
  2351. scope["unique-prefix"] = (uniqueName .. "/")
  2352. return scope
  2353. end
  2354. local discard = function()
  2355. return nil
  2356. end
  2357. void1 = {["put-error!"]=discard, ["put-warning!"]=discard, ["put-verbose!"]=discard, ["put-debug!"]=discard, ["put-time!"]=discard, ["put-node-error!"]=discard, ["put-node-warning!"]=discard}
  2358. _2a_romanDigits_2a_1 = {I=1, V=5, X=10, L=50, C=100, D=500, M=1000}
  2359. romanDigit_3f_1 = function(char)
  2360. return _2a_romanDigits_2a_1[char] or false
  2361. end
  2362. hexDigit_3f_1 = function(char)
  2363. return between_3f_1(char, "0", "9") or (between_3f_1(char, "a", "f") or between_3f_1(char, "A", "F"))
  2364. end
  2365. binDigit_3f_1 = function(char)
  2366. return char == "0" or char == "1"
  2367. end
  2368. terminator_3f_1 = function(char)
  2369. return char == "\n" or (char == " " or (char == "\9" or (char == ";" or (char == "(" or (char == ")" or (char == "[" or (char == "]" or (char == "{" or (char == "}" or (char == "\11" or (char == "\12" or char == "")))))))))))
  2370. end
  2371. closingTerminator_3f_1 = function(char)
  2372. return char == "\n" or (char == " " or (char == "\9" or (char == ";" or (char == ")" or (char == "]" or (char == "}" or (char == "\11" or (char == "\12" or char == ""))))))))
  2373. end
  2374. digitError_21_1 = function(logger, pos, name, char)
  2375. return doNodeError_21_1(logger, format1("Expected %s digit, got %s", name, (function()
  2376. if char == "" then
  2377. return "eof"
  2378. else
  2379. return quoted1(char)
  2380. end
  2381. end)()), pos, nil, pos, "Invalid digit here")
  2382. end
  2383. eofError_21_1 = function(context, tokens, logger, msg, source, explain, ...)
  2384. local lines = _pack(...) lines.tag = "list"
  2385. if context then
  2386. return error1({msg=msg, context=context, tokens=tokens}, 0)
  2387. else
  2388. return apply1(doNodeError_21_1, logger, msg, source, explain, lines)
  2389. end
  2390. end
  2391. lex1 = function(logger, str, name, cont)
  2392. str = gsub1(str, "\13\n?", "\n")
  2393. local lines, line, column, offset, length, out = split1(str, "\n"), 1, 1, 1, n1(str), {tag="list", n=0}
  2394. local consume_21_, range = function()
  2395. if (function()
  2396. local xs, x = str, offset
  2397. return sub1(xs, x, x)
  2398. end)() == "\n" then
  2399. line = line + 1
  2400. column = 1
  2401. else
  2402. column = column + 1
  2403. end
  2404. offset = offset + 1
  2405. return nil
  2406. end, function(start, finish)
  2407. return {tag="range", name=name, start=start, finish=finish or start, lines=lines}
  2408. end
  2409. local appendWith_21_, parseBase = function(data, start, finish)
  2410. local start1, finish1 = start or {tag="position", offset=offset, line=line, column=column}, finish or {tag="position", offset=offset, line=line, column=column}
  2411. data["source"] = range(start1, finish1)
  2412. data["contents"] = sub1(str, start1["offset"], finish1["offset"])
  2413. return push_21_1(out, data)
  2414. end, function(name2, p, base)
  2415. local start = offset
  2416. local char
  2417. local xs, x = str, offset
  2418. char = sub1(xs, x, x)
  2419. if not p(char) then
  2420. digitError_21_1(logger, range({tag="position", offset=offset, line=line, column=column}), name2, char)
  2421. end
  2422. local xs, x = str, offset + 1
  2423. char = sub1(xs, x, x)
  2424. while p(char) or "'" == char do
  2425. consume_21_()
  2426. local xs, x = str, offset + 1
  2427. char = sub1(xs, x, x)
  2428. end
  2429. return tonumber1(gsub1(sub1(str, start, offset), "'", ""), base)
  2430. end
  2431. while offset <= length do
  2432. local char
  2433. local xs, x = str, offset
  2434. char = sub1(xs, x, x)
  2435. if char == "\n" or char == "\9" or char == " " or char == "\11" or char == "\12" then
  2436. elseif char == "(" then
  2437. appendWith_21_({tag="open", close=")"})
  2438. elseif char == ")" then
  2439. appendWith_21_({tag="close", open="("})
  2440. elseif char == "[" then
  2441. appendWith_21_({tag="open", close="]"})
  2442. elseif char == "]" then
  2443. appendWith_21_({tag="close", open="["})
  2444. elseif char == "{" then
  2445. appendWith_21_({tag="open-struct", close="}"})
  2446. elseif char == "}" then
  2447. appendWith_21_({tag="close", open="{"})
  2448. elseif char == "'" then
  2449. appendWith_21_({tag="quote"}, nil, nil)
  2450. elseif char == "`" then
  2451. appendWith_21_({tag="syntax-quote"}, nil, nil)
  2452. elseif char == "~" then
  2453. appendWith_21_({tag="quasiquote"}, nil, nil)
  2454. elseif char == "@" and not closingTerminator_3f_1((function()
  2455. local xs, x = str, offset + 1
  2456. return sub1(xs, x, x)
  2457. end)()) then
  2458. appendWith_21_({tag="splice"}, nil, nil)
  2459. elseif char == "," then
  2460. if (function()
  2461. local xs, x = str, offset + 1
  2462. return sub1(xs, x, x)
  2463. end)() == "@" then
  2464. local start = {tag="position", offset=offset, line=line, column=column}
  2465. consume_21_()
  2466. appendWith_21_({tag="unquote-splice"}, start, nil)
  2467. else
  2468. appendWith_21_({tag="unquote"}, nil, nil)
  2469. end
  2470. elseif find1(str, "^%-?%.?[#0-9]", offset) then
  2471. local start, negative = {tag="position", offset=offset, line=line, column=column}, char == "-"
  2472. if negative then
  2473. consume_21_()
  2474. local xs, x = str, offset
  2475. char = sub1(xs, x, x)
  2476. end
  2477. if char == "#" and lower1((function()
  2478. local xs, x = str, offset + 1
  2479. return sub1(xs, x, x)
  2480. end)()) == "x" then
  2481. consume_21_()
  2482. consume_21_()
  2483. local res = parseBase("hexadecimal", hexDigit_3f_1, 16)
  2484. if negative then
  2485. res = 0 - res
  2486. end
  2487. appendWith_21_({tag="number", value=res}, start)
  2488. elseif char == "#" and lower1((function()
  2489. local xs, x = str, offset + 1
  2490. return sub1(xs, x, x)
  2491. end)()) == "b" then
  2492. consume_21_()
  2493. consume_21_()
  2494. local res = parseBase("binary", binDigit_3f_1, 2)
  2495. if negative then
  2496. res = 0 - res
  2497. end
  2498. appendWith_21_({tag="number", value=res}, start)
  2499. elseif char == "#" and lower1((function()
  2500. local xs, x = str, offset + 1
  2501. return sub1(xs, x, x)
  2502. end)()) == "r" then
  2503. consume_21_()
  2504. consume_21_()
  2505. local res
  2506. local start1 = offset
  2507. local char2
  2508. local xs, x = str, offset
  2509. char2 = sub1(xs, x, x)
  2510. if not romanDigit_3f_1(char2) then
  2511. digitError_21_1(logger, range({tag="position", offset=offset, line=line, column=column}), "roman", char2)
  2512. end
  2513. local xs, x = str, offset + 1
  2514. char2 = sub1(xs, x, x)
  2515. while romanDigit_3f_1(char2) or char2 == "'" do
  2516. consume_21_()
  2517. local xs, x = str, offset + 1
  2518. char2 = sub1(xs, x, x)
  2519. end
  2520. local str1 = gsub1(reverse1(sub1(str, start1, offset)), "'", "")
  2521. res = car1(reduce1(function(_e1, _e2, ...)
  2522. local remainingArguments = _pack(...) remainingArguments.tag = "list"
  2523. local temp = append1(list1(_e1, _e2), remainingArguments)
  2524. local temp1
  2525. if type1(temp) == "list" then
  2526. if n1(temp) >= 2 then
  2527. if n1(temp) <= 2 then
  2528. local temp2
  2529. local temp3 = nth1(temp, 1)
  2530. temp2 = type1(temp3) == "list" and (n1(temp3) >= 2 and (n1(temp3) <= 2 and true))
  2531. if temp2 then
  2532. temp1 = true
  2533. else
  2534. temp1 = false
  2535. end
  2536. else
  2537. temp1 = false
  2538. end
  2539. else
  2540. temp1 = false
  2541. end
  2542. else
  2543. temp1 = false
  2544. end
  2545. if temp1 then
  2546. local acc, prev, n = nth1(nth1(temp, 1), 1), nth1(nth1(temp, 1), 2), nth1(temp, 2)
  2547. return list1((function()
  2548. if n < prev then
  2549. return _2d_1
  2550. else
  2551. return _2b_1
  2552. end
  2553. end)()(acc, n), max1(n, prev))
  2554. else
  2555. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `((?acc ?prev) ?n)`")
  2556. end
  2557. end, list1(0, 0), map2(comp1(function(temp)
  2558. return _2a_romanDigits_2a_1[temp]
  2559. end, upper1, function(temp)
  2560. return sub1(str1, temp, temp)
  2561. end), range1("from", 1, "to", n1(str1)))))
  2562. if negative then
  2563. res = 0 - res
  2564. end
  2565. appendWith_21_({tag="number", value=res}, start)
  2566. elseif char == "#" and terminator_3f_1(lower1((function()
  2567. local xs, x = str, offset + 1
  2568. return sub1(xs, x, x)
  2569. end)())) then
  2570. doNodeError_21_1(logger, "Expected hexadecimal (#x), binary (#b), or Roman (#r) digit specifier.", range({tag="position", offset=offset, line=line, column=column}), "The '#' character is used for various number representations, such as binary\nand hexadecimal digits.\n\nIf you're looking for the '#' function, this has been replaced with 'n'. We\napologise for the inconvenience.", range({tag="position", offset=offset, line=line, column=column}), "# must be followed by x, b or r")
  2571. elseif char == "#" then
  2572. consume_21_()
  2573. doNodeError_21_1(logger, "Expected hexadecimal (#x), binary (#b), or Roman (#r) digit specifier.", range({tag="position", offset=offset, line=line, column=column}), "The '#' character is used for various number representations, namely binary,\nhexadecimal and roman numbers.", range({tag="position", offset=offset, line=line, column=column}), "# must be followed by x, b or r")
  2574. else
  2575. while between_3f_1((function()
  2576. local xs, x = str, offset + 1
  2577. return sub1(xs, x, x)
  2578. end)(), "0", "9") or (function()
  2579. local xs, x = str, offset + 1
  2580. return sub1(xs, x, x)
  2581. end)() == "'" do
  2582. consume_21_()
  2583. end
  2584. if (function()
  2585. local xs, x = str, offset + 1
  2586. return sub1(xs, x, x)
  2587. end)() == "/" then
  2588. local numEnd, _5f_, _5f_1, domStart = {tag="position", offset=offset, line=line, column=column}, consume_21_(), consume_21_(), {tag="position", offset=offset, line=line, column=column}
  2589. if not (between_3f_1((function()
  2590. local xs, x = str, offset
  2591. return sub1(xs, x, x)
  2592. end)(), "0", "9") or (function()
  2593. local xs, x = str, offset
  2594. return sub1(xs, x, x)
  2595. end)() == "'") then
  2596. doNodeError_21_1(logger, formatOutput_21_1(nil, "Expected digit, got " .. quoted1((function()
  2597. local xs, x = str, offset
  2598. return sub1(xs, x, x)
  2599. end)())), range(domStart), "", range(domStart), "")
  2600. end
  2601. while between_3f_1((function()
  2602. local xs, x = str, offset + 1
  2603. return sub1(xs, x, x)
  2604. end)(), "0", "9") or (function()
  2605. local xs, x = str, offset + 1
  2606. return sub1(xs, x, x)
  2607. end)() == "'" do
  2608. consume_21_()
  2609. end
  2610. local domEnd, num = {tag="position", offset=offset, line=line, column=column}, tonumber1(gsub1(sub1(str, start["offset"], numEnd["offset"]), "'", ""), 10)
  2611. local dom = tonumber1(gsub1(sub1(str, domStart["offset"], domEnd["offset"]), "'", ""), 10)
  2612. if not num then
  2613. doNodeError_21_1(logger, "Invalid numerator in rational literal", range(start, numEnd), "", range(start, numEnd), "There should be at least one number before the division symbol.")
  2614. end
  2615. if not dom then
  2616. doNodeError_21_1(logger, "Invalid denominator in rational literal", range(domStart, domEnd), "", range(domStart, domEnd), "There should be at least one number after the division symbol.")
  2617. end
  2618. appendWith_21_({tag="rational", num={tag="number", value=num, source=range(start, numEnd)}, dom={tag="number", value=dom, source=range(domStart, domEnd)}}, start)
  2619. else
  2620. if (function()
  2621. local xs, x = str, offset + 1
  2622. return sub1(xs, x, x)
  2623. end)() == "." then
  2624. consume_21_()
  2625. while between_3f_1((function()
  2626. local xs, x = str, offset + 1
  2627. return sub1(xs, x, x)
  2628. end)(), "0", "9") or (function()
  2629. local xs, x = str, offset + 1
  2630. return sub1(xs, x, x)
  2631. end)() == "'" do
  2632. consume_21_()
  2633. end
  2634. end
  2635. local xs, x = str, offset + 1
  2636. char = sub1(xs, x, x)
  2637. if char == "e" or char == "E" then
  2638. consume_21_()
  2639. local xs, x = str, offset + 1
  2640. char = sub1(xs, x, x)
  2641. if char == "-" or char == "+" then
  2642. consume_21_()
  2643. end
  2644. while between_3f_1((function()
  2645. local xs, x = str, offset + 1
  2646. return sub1(xs, x, x)
  2647. end)(), "0", "9") or (function()
  2648. local xs, x = str, offset + 1
  2649. return sub1(xs, x, x)
  2650. end)() == "'" do
  2651. consume_21_()
  2652. end
  2653. end
  2654. local res = tonumber1((gsub1(sub1(str, start["offset"], offset), "'", "")))
  2655. if not res then
  2656. doNodeError_21_1(logger, format1("Expected digit, got %s", (function()
  2657. if char == "" then
  2658. return "eof"
  2659. else
  2660. return quoted1(char)
  2661. end
  2662. end)()), range({tag="position", offset=offset, line=line, column=column}), nil, range({tag="position", offset=offset, line=line, column=column}), "Illegal character here. Are you missing whitespace?")
  2663. end
  2664. appendWith_21_({tag="number", value=res}, start)
  2665. end
  2666. end
  2667. local xs, x = str, offset + 1
  2668. char = sub1(xs, x, x)
  2669. if not terminator_3f_1(char) then
  2670. consume_21_()
  2671. doNodeError_21_1(logger, format1("Expected digit, got %s", (function()
  2672. if char == "" then
  2673. return "eof"
  2674. else
  2675. return quoted1(char)
  2676. end
  2677. end)()), range({tag="position", offset=offset, line=line, column=column}), nil, range({tag="position", offset=offset, line=line, column=column}), "Illegal character here. Are you missing whitespace?")
  2678. end
  2679. elseif char == "\"" or char == "$" and (function()
  2680. local xs, x = str, offset + 1
  2681. return sub1(xs, x, x)
  2682. end)() == "\"" then
  2683. local start, startCol, buffer, interpolate = {tag="position", offset=offset, line=line, column=column}, column + 1, {tag="list", n=0}, char == "$"
  2684. if interpolate then
  2685. consume_21_()
  2686. end
  2687. consume_21_()
  2688. local xs, x = str, offset
  2689. char = sub1(xs, x, x)
  2690. while char ~= "\"" do
  2691. if column == 1 then
  2692. local running, lineOff = true, offset
  2693. while running and column < startCol do
  2694. if char == " " then
  2695. consume_21_()
  2696. elseif char == "\n" then
  2697. consume_21_()
  2698. push_21_1(buffer, "\n")
  2699. lineOff = offset
  2700. elseif char == "" then
  2701. running = false
  2702. else
  2703. putNodeWarning_21_1(logger, format1("Expected leading indent, got %q", char), range({tag="position", offset=offset, line=line, column=column}), "You should try to align multi-line strings at the initial quote\nmark. This helps keep programs neat and tidy.", range(start), "String started with indent here", range({tag="position", offset=offset, line=line, column=column}), "Mis-aligned character here")
  2704. push_21_1(buffer, sub1(str, lineOff, offset - 1))
  2705. running = false
  2706. end
  2707. local xs, x = str, offset
  2708. char = sub1(xs, x, x)
  2709. end
  2710. end
  2711. if char == "" then
  2712. local start1, finish = range(start), range({tag="position", offset=offset, line=line, column=column})
  2713. eofError_21_1(cont and "string", out, logger, "Expected '\"', got eof", finish, nil, start1, "string started here", finish, "end of file here")
  2714. elseif char == "\\" then
  2715. consume_21_()
  2716. local xs, x = str, offset
  2717. char = sub1(xs, x, x)
  2718. if char == "\n" then
  2719. elseif char == "a" then
  2720. push_21_1(buffer, "\7")
  2721. elseif char == "b" then
  2722. push_21_1(buffer, "\8")
  2723. elseif char == "f" then
  2724. push_21_1(buffer, "\12")
  2725. elseif char == "n" then
  2726. push_21_1(buffer, "\n")
  2727. elseif char == "r" then
  2728. push_21_1(buffer, "\13")
  2729. elseif char == "t" then
  2730. push_21_1(buffer, "\9")
  2731. elseif char == "v" then
  2732. push_21_1(buffer, "\11")
  2733. elseif char == "\"" then
  2734. push_21_1(buffer, "\"")
  2735. elseif char == "\\" then
  2736. push_21_1(buffer, "\\")
  2737. elseif char == "x" or char == "X" or between_3f_1(char, "0", "9") then
  2738. local start1 = {tag="position", offset=offset, line=line, column=column}
  2739. local val
  2740. if char == "x" or char == "X" then
  2741. consume_21_()
  2742. local start2 = offset
  2743. if not hexDigit_3f_1((function()
  2744. local xs, x = str, offset
  2745. return sub1(xs, x, x)
  2746. end)()) then
  2747. digitError_21_1(logger, range({tag="position", offset=offset, line=line, column=column}), "hexadecimal", (function()
  2748. local xs, x = str, offset
  2749. return sub1(xs, x, x)
  2750. end)())
  2751. end
  2752. if hexDigit_3f_1((function()
  2753. local xs, x = str, offset + 1
  2754. return sub1(xs, x, x)
  2755. end)()) then
  2756. consume_21_()
  2757. end
  2758. val = tonumber1(sub1(str, start2, offset), 16)
  2759. else
  2760. local start2, ctr = {tag="position", offset=offset, line=line, column=column}, 0
  2761. local xs, x = str, offset + 1
  2762. char = sub1(xs, x, x)
  2763. while ctr < 2 and between_3f_1(char, "0", "9") do
  2764. consume_21_()
  2765. local xs, x = str, offset + 1
  2766. char = sub1(xs, x, x)
  2767. ctr = ctr + 1
  2768. end
  2769. val = tonumber1(sub1(str, start2["offset"], offset))
  2770. end
  2771. if val >= 256 then
  2772. doNodeError_21_1(logger, "Invalid escape code", range(start1), nil, range(start1, {tag="position", offset=offset, line=line, column=column}), "Must be between 0 and 255, is " .. val)
  2773. end
  2774. push_21_1(buffer, char1(val))
  2775. elseif char == "" then
  2776. eofError_21_1(cont and "string", out, logger, "Expected escape code, got eof", range({tag="position", offset=offset, line=line, column=column}), nil, range({tag="position", offset=offset, line=line, column=column}), "end of file here")
  2777. else
  2778. doNodeError_21_1(logger, "Illegal escape character", range({tag="position", offset=offset, line=line, column=column}), nil, range({tag="position", offset=offset, line=line, column=column}), "Unknown escape character")
  2779. end
  2780. else
  2781. push_21_1(buffer, char)
  2782. end
  2783. consume_21_()
  2784. local xs, x = str, offset
  2785. char = sub1(xs, x, x)
  2786. end
  2787. if interpolate then
  2788. local value, sections, len = concat2(buffer), {tag="list", n=0}, n1(str)
  2789. local i = 1
  2790. while true do
  2791. local rs, re, rm = find1(value, "~%{([^%} ]+)%}", i)
  2792. local is, ie, im = find1(value, "%$%{([^%} ]+)%}", i)
  2793. if rs and (not is or rs < is) then
  2794. push_21_1(sections, sub1(value, i, rs - 1))
  2795. push_21_1(sections, "{#" .. rm .. "}")
  2796. i = re + 1
  2797. elseif is then
  2798. push_21_1(sections, sub1(value, i, is - 1))
  2799. push_21_1(sections, "{#" .. im .. ":id}")
  2800. i = ie + 1
  2801. else
  2802. push_21_1(sections, sub1(value, i, len))
  2803. break
  2804. end
  2805. end
  2806. putNodeWarning_21_1(logger, "The $ syntax is deprecated and should be replaced with format.", range(start, {tag="position", offset=offset, line=line, column=column}), nil, range(start, {tag="position", offset=offset, line=line, column=column}), "Can be replaced with (format nil " .. quoted1(concat2(sections)) .. ")")
  2807. appendWith_21_({tag="interpolate", value=value}, start)
  2808. else
  2809. appendWith_21_({tag="string", value=concat2(buffer)}, start)
  2810. end
  2811. elseif char == ";" then
  2812. while offset <= length and (function()
  2813. local xs, x = str, offset + 1
  2814. return sub1(xs, x, x)
  2815. end)() ~= "\n" do
  2816. consume_21_()
  2817. end
  2818. else
  2819. local start, key = {tag="position", offset=offset, line=line, column=column}, char == ":"
  2820. local xs, x = str, offset + 1
  2821. char = sub1(xs, x, x)
  2822. while not terminator_3f_1(char) do
  2823. consume_21_()
  2824. local xs, x = str, offset + 1
  2825. char = sub1(xs, x, x)
  2826. end
  2827. if key then
  2828. appendWith_21_({tag="key", value=sub1(str, start["offset"] + 1, offset)}, start)
  2829. else
  2830. appendWith_21_({tag="symbol"}, start, nil)
  2831. end
  2832. end
  2833. consume_21_()
  2834. end
  2835. appendWith_21_({tag="eof"}, nil, nil)
  2836. return splice1(list1(out, (range({tag="position", offset=1, line=1, column=nil}, {tag="position", offset=offset, line=line, column=column}))))
  2837. end
  2838. parse1 = function(logger, toks, cont)
  2839. local head, stack = {tag="list", n=0}, {tag="list", n=0}
  2840. local pop_21_ = function()
  2841. head["open"] = nil
  2842. head["close"] = nil
  2843. head["auto-close"] = nil
  2844. head["last-node"] = nil
  2845. head = last1(stack)
  2846. return popLast_21_1(stack)
  2847. end
  2848. local forLimit = n1(toks)
  2849. local i = 1
  2850. while i <= forLimit do
  2851. local tok = toks[i]
  2852. local tag, autoClose = type1(tok), false
  2853. local previous, tokPos = head["last-node"], tok["source"]
  2854. local temp
  2855. if tag ~= "eof" then
  2856. if tag ~= "close" then
  2857. if head["source"] then
  2858. temp = tokPos["start"]["line"] ~= head["source"]["start"]["line"]
  2859. else
  2860. temp = true
  2861. end
  2862. else
  2863. temp = false
  2864. end
  2865. else
  2866. temp = false
  2867. end
  2868. if temp then
  2869. if previous then
  2870. local prevPos = previous["source"]
  2871. if tokPos["start"]["line"] ~= prevPos["start"]["line"] then
  2872. head["last-node"] = tok
  2873. if tokPos["start"]["column"] ~= prevPos["start"]["column"] then
  2874. putNodeWarning_21_1(logger, "Different indent compared with previous expressions.", tok["source"], "You should try to maintain consistent indentation across a program,\ntry to ensure all expressions are lined up.\nIf this looks OK to you, check you're not missing a closing ')'.", prevPos, "", tokPos, "")
  2875. end
  2876. end
  2877. else
  2878. head["last-node"] = tok
  2879. end
  2880. end
  2881. if tag == "string" or tag == "number" or tag == "symbol" or tag == "key" then
  2882. push_21_1(head, tok)
  2883. elseif tag == "interpolate" then
  2884. local node = {tag="list", n=2, source=tok["source"], [1]={tag="symbol", contents="$", source=rangeOfStart1(tok["source"])}, [2]={tag="string", value=tok["value"], source=tok["source"]}}
  2885. push_21_1(head, node)
  2886. elseif tag == "rational" then
  2887. local node = {tag="list", n=3, source=tok["source"], [1]={tag="symbol", contents="rational", source=tok["source"]}, [2]=tok["num"], [3]=tok["dom"]}
  2888. push_21_1(head, node)
  2889. elseif tag == "open" then
  2890. local next = {tag="list", n=0}
  2891. push_21_1(stack, head)
  2892. push_21_1(head, next)
  2893. head = next
  2894. head["open"] = tok["contents"]
  2895. head["close"] = tok["close"]
  2896. head["source"] = tok["source"]
  2897. elseif tag == "open-struct" then
  2898. local next = {tag="list", n=0}
  2899. push_21_1(stack, head)
  2900. push_21_1(head, next)
  2901. head = next
  2902. head["open"] = tok["contents"]
  2903. head["close"] = tok["close"]
  2904. head["source"] = tok["source"]
  2905. local node = {tag="symbol", contents="struct-literal", source=head["source"]}
  2906. push_21_1(head, node)
  2907. elseif tag == "close" then
  2908. if empty_3f_1(stack) then
  2909. doNodeError_21_1(logger, format1("'%s' without matching '%s'", tok["contents"], tok["open"]), tok["source"], nil, sourceRange1(tok["source"]), "")
  2910. elseif head["auto-close"] then
  2911. doNodeError_21_1(logger, format1("'%s' without matching '%s' inside quote", tok["contents"], tok["open"]), tok["source"], nil, head["source"], "quote opened here", tok["source"], "attempting to close here")
  2912. elseif head["close"] ~= tok["contents"] then
  2913. doNodeError_21_1(logger, format1("Expected '%s', got '%s'", head["close"], tok["contents"]), tok["source"], nil, head["source"], format1("block opened with '%s'", head["open"]), tok["source"], format1("'%s' used here", tok["contents"]))
  2914. else
  2915. head["source"] = rangeOfSpan1(head["source"], tok["source"])
  2916. pop_21_()
  2917. end
  2918. elseif tag == "quote" or tag == "unquote" or tag == "syntax-quote" or tag == "unquote-splice" or tag == "quasiquote" or tag == "splice" then
  2919. local next = {tag="list", n=0}
  2920. push_21_1(stack, head)
  2921. push_21_1(head, next)
  2922. head = next
  2923. head["source"] = tok["source"]
  2924. local node = {tag="symbol", contents=tag, source=tok["source"]}
  2925. push_21_1(head, node)
  2926. autoClose = true
  2927. head["auto-close"] = true
  2928. elseif tag == "eof" then
  2929. if 0 ~= n1(stack) then
  2930. eofError_21_1(cont and "list", toks, logger, (function()
  2931. if head["auto-close"] then
  2932. return format1("Expected expression quote, got eof", head["close"])
  2933. else
  2934. return format1("Expected '%s', got eof", head["close"])
  2935. end
  2936. end)(), tok["source"], nil, head["source"], "block opened here", tok["source"], "end of file here")
  2937. end
  2938. else
  2939. error1("Unsupported type " .. tag)
  2940. end
  2941. if not autoClose then
  2942. while head["auto-close"] do
  2943. if empty_3f_1(stack) then
  2944. doNodeError_21_1(logger, format1("'%s' without matching '%s'", tok["contents"], tok["open"]), tok["source"], nil, sourceRange1(tok["source"]), "")
  2945. end
  2946. head["source"] = rangeOfSpan1(head["source"], tok["source"])
  2947. pop_21_()
  2948. end
  2949. end
  2950. i = i + 1
  2951. end
  2952. return head
  2953. end
  2954. read2 = function(x, path)
  2955. return parse1(void1, lex1(void1, x, path or "", nil), nil)
  2956. end
  2957. visitQuote1 = function(node, visitor, level)
  2958. while true do
  2959. if level == 0 then
  2960. return visitNode1(node, visitor)
  2961. else
  2962. local tag = type1(node)
  2963. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  2964. return nil
  2965. elseif tag == "list" then
  2966. local first = nth1(node, 1)
  2967. if type1(first) == "symbol" then
  2968. if first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  2969. node, level = nth1(node, 2), level - 1
  2970. elseif first["contents"] == "syntax-quote" then
  2971. node, level = nth1(node, 2), level + 1
  2972. else
  2973. local forLimit = n1(node)
  2974. local i = 1
  2975. while i <= forLimit do
  2976. visitQuote1(node[i], visitor, level)
  2977. i = i + 1
  2978. end
  2979. return nil
  2980. end
  2981. else
  2982. local forLimit = n1(node)
  2983. local i = 1
  2984. while i <= forLimit do
  2985. visitQuote1(node[i], visitor, level)
  2986. i = i + 1
  2987. end
  2988. return nil
  2989. end
  2990. elseif error1 then
  2991. return "Unknown tag " .. tag
  2992. else
  2993. _error("unmatched item")
  2994. end
  2995. end
  2996. end
  2997. end
  2998. visitNode1 = function(node, visitor)
  2999. while true do
  3000. if visitor(node, visitor) ~= false then
  3001. local tag = type1(node)
  3002. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  3003. return nil
  3004. elseif tag == "list" then
  3005. local first = nth1(node, 1)
  3006. if type1(first) == "symbol" then
  3007. local func = first["var"]
  3008. local funct = func["kind"]
  3009. if funct == "defined" or funct == "arg" or funct == "native" or funct == "macro" then
  3010. return visitBlock1(node, 1, visitor)
  3011. elseif func == builtins1["lambda"] then
  3012. return visitBlock1(node, 3, visitor)
  3013. elseif func == builtins1["cond"] then
  3014. local forLimit = n1(node)
  3015. local i = 2
  3016. while i <= forLimit do
  3017. local case = nth1(node, i)
  3018. visitNode1(nth1(case, 1), visitor)
  3019. visitBlock1(case, 2, visitor)
  3020. i = i + 1
  3021. end
  3022. return nil
  3023. elseif func == builtins1["set!"] then
  3024. node = nth1(node, 3)
  3025. elseif func == builtins1["quote"] then
  3026. return nil
  3027. elseif func == builtins1["syntax-quote"] then
  3028. return visitQuote1(nth1(node, 2), visitor, 1)
  3029. elseif func == builtins1["unquote"] or func == builtins1["unquote-splice"] then
  3030. return error1("unquote/unquote-splice should never appear here", 0)
  3031. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  3032. node = nth1(node, n1(node))
  3033. elseif func == builtins1["define-native"] then
  3034. return nil
  3035. elseif func == builtins1["import"] then
  3036. return nil
  3037. elseif func == builtins1["struct-literal"] then
  3038. return visitBlock1(node, 2, visitor)
  3039. else
  3040. return error1("Unknown kind " .. funct .. " for variable " .. func["name"], 0)
  3041. end
  3042. else
  3043. return visitBlock1(node, 1, visitor)
  3044. end
  3045. else
  3046. return error1("Unknown tag " .. tag)
  3047. end
  3048. else
  3049. return nil
  3050. end
  3051. end
  3052. end
  3053. visitBlock1 = function(node, start, visitor)
  3054. local forLimit = n1(node)
  3055. local i = start
  3056. while i <= forLimit do
  3057. visitNode1(nth1(node, i), visitor)
  3058. i = i + 1
  3059. end
  3060. return nil
  3061. end
  3062. startTimer_21_1 = function(timer, name, level)
  3063. local instance = timer["timers"][name]
  3064. if not instance then
  3065. instance = {name=name, level=level or 1, running=false, total=0}
  3066. timer["timers"][name] = instance
  3067. end
  3068. if instance["running"] then
  3069. error1("Timer " .. name .. " is already running")
  3070. end
  3071. instance["running"] = true
  3072. instance["start"] = clock1()
  3073. return nil
  3074. end
  3075. pauseTimer_21_1 = function(timer, name)
  3076. local instance = timer["timers"][name]
  3077. if not instance then
  3078. error1("Timer " .. name .. " does not exist")
  3079. end
  3080. if not instance["running"] then
  3081. error1("Timer " .. name .. " is not running")
  3082. end
  3083. instance["running"] = false
  3084. instance["total"] = (clock1() - instance["start"]) + instance["total"]
  3085. return nil
  3086. end
  3087. stopTimer_21_1 = function(timer, name)
  3088. local instance = timer["timers"][name]
  3089. if not instance then
  3090. error1("Timer " .. name .. " does not exist")
  3091. end
  3092. if not instance["running"] then
  3093. error1("Timer " .. name .. " is not running")
  3094. end
  3095. timer["timers"][name] = nil
  3096. instance["total"] = (clock1() - instance["start"]) + instance["total"]
  3097. return timer["callback"](instance["name"], instance["total"], instance["level"])
  3098. end
  3099. passEnabled_3f_1 = function(pass, options)
  3100. local override = options["override"]
  3101. if override[pass["name"]] == true then
  3102. return true
  3103. elseif override[pass["name"]] == false then
  3104. return false
  3105. elseif any1(function(cat)
  3106. return override[cat] == true
  3107. end, pass["cat"]) then
  3108. return true
  3109. elseif any1(function(cat)
  3110. return override[cat] == false
  3111. end, pass["cat"]) then
  3112. return false
  3113. else
  3114. return pass["on"] ~= false and options["level"] >= (pass["level"] or 1)
  3115. end
  3116. end
  3117. filterPasses1 = function(passes, options)
  3118. local res = {}
  3119. local temp, v = next1(passes)
  3120. while temp ~= nil do
  3121. res[temp] = first1(partition1(function(temp1)
  3122. return passEnabled_3f_1(temp1, options)
  3123. end, v))
  3124. temp, v = next1(passes, temp)
  3125. end
  3126. return res
  3127. end
  3128. runPass1 = function(pass, options, tracker, ...)
  3129. local args = _pack(...) args.tag = "list"
  3130. local ptracker, name = {changed=0}, "[" .. concat2(pass["cat"], " ") .. "] " .. pass["name"]
  3131. startTimer_21_1(options["timer"], name, 2)
  3132. pass["run"](ptracker, options, splice1(args))
  3133. stopTimer_21_1(options["timer"], name)
  3134. if options["track"] then
  3135. self1(options["logger"], "put-verbose!", (sprintf1("%s made %d changes", name, ptracker["changed"])))
  3136. end
  3137. if tracker then
  3138. tracker["changed"] = tracker["changed"] + ptracker["changed"]
  3139. end
  3140. return ptracker["changed"] > 0
  3141. end
  3142. visitQuote2 = function(node, level, lookup)
  3143. while true do
  3144. if level == 0 then
  3145. return visitNode2(node, nil, nil, lookup)
  3146. else
  3147. local tag = type1(node)
  3148. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  3149. return nil
  3150. elseif tag == "list" then
  3151. local first = nth1(node, 1)
  3152. if type1(node) == "symbol" then
  3153. if first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  3154. node, level = nth1(node, 2), level - 1
  3155. elseif first["contents"] == "syntax-quote" then
  3156. node, level = nth1(node, 2), level + 1
  3157. else
  3158. local forLimit = n1(node)
  3159. local i = 1
  3160. while i <= forLimit do
  3161. visitQuote2(node[i], level, lookup)
  3162. i = i + 1
  3163. end
  3164. return nil
  3165. end
  3166. else
  3167. local forLimit = n1(node)
  3168. local i = 1
  3169. while i <= forLimit do
  3170. visitQuote2(node[i], level, lookup)
  3171. i = i + 1
  3172. end
  3173. return nil
  3174. end
  3175. elseif error1 then
  3176. return "Unknown tag " .. tag
  3177. else
  3178. _error("unmatched item")
  3179. end
  3180. end
  3181. end
  3182. end
  3183. visitNode2 = function(node, parents, active, lookup)
  3184. while true do
  3185. local temp = type1(node)
  3186. if temp == "string" then
  3187. return nil
  3188. elseif temp == "number" then
  3189. return nil
  3190. elseif temp == "key" then
  3191. return nil
  3192. elseif temp == "symbol" then
  3193. local func = lookup[node["var"]]
  3194. if func then
  3195. func["var"] = (func["var"] + 1)
  3196. return nil
  3197. else
  3198. return nil
  3199. end
  3200. elseif temp == "list" then
  3201. local head = car1(node)
  3202. local temp1 = type1(head)
  3203. if temp1 == "symbol" then
  3204. local func = head["var"]
  3205. if func["kind"] ~= "builtin" then
  3206. local func1 = lookup[func]
  3207. if not func1 then
  3208. elseif active == func1 then
  3209. func1["recur"] = (func1["recur"] + 1)
  3210. elseif parents and parents[func1["parent"]] then
  3211. func1["direct"] = (func1["direct"] + 1)
  3212. else
  3213. func1["var"] = (func1["var"] + 1)
  3214. end
  3215. return visitNodes1(node, 2, nil, lookup)
  3216. elseif func == builtins1["lambda"] then
  3217. return visitBlock2(node, 3, nil, nil, lookup)
  3218. elseif func == builtins1["set!"] then
  3219. local var = nth1(node, 2)["var"]
  3220. local func1, val = lookup[var], nth1(node, 3)
  3221. if func1 and (func1["lambda"] == nil and (parents and (parents[func1["parent"]] and (type1(val) == "list" and builtin_3f_1(car1(val), "lambda"))))) then
  3222. func1["lambda"] = val
  3223. func1["setter"] = node
  3224. visitBlock2(val, 3, nil, func1, lookup)
  3225. if func1["recur"] == 0 then
  3226. lookup[var] = nil
  3227. return nil
  3228. else
  3229. return nil
  3230. end
  3231. else
  3232. lookup[var] = nil
  3233. node, parents, active = val, nil, nil
  3234. end
  3235. elseif func == builtins1["cond"] then
  3236. local forLimit = n1(node)
  3237. local i = 2
  3238. while i <= forLimit do
  3239. local case = nth1(node, i)
  3240. visitNode2(car1(case), nil, nil, lookup)
  3241. visitBlock2(case, 2, nil, active, lookup)
  3242. i = i + 1
  3243. end
  3244. return nil
  3245. elseif func == builtins1["quote"] then
  3246. return nil
  3247. elseif func == builtins1["syntax-quote"] then
  3248. return visitQuote2(nth1(node, 2), 1, lookup)
  3249. elseif func == builtins1["unquote"] or func == builtins1["unquote-splice"] then
  3250. return error1("unquote/unquote-splice should never appear here", 0)
  3251. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  3252. node, parents, active = nth1(node, n1(node)), nil, nil
  3253. elseif func == builtins1["define-native"] then
  3254. return nil
  3255. elseif func == builtins1["import"] then
  3256. return nil
  3257. elseif func == builtins1["struct-literal"] then
  3258. return visitNodes1(node, 2, nil, lookup)
  3259. else
  3260. return error1("Unknown builtin for variable " .. func["name"], 0)
  3261. end
  3262. elseif temp1 == "list" then
  3263. local first = car1(node)
  3264. if type1(first) == "list" and builtin_3f_1(car1(first), "lambda") then
  3265. local args = nth1(first, 2)
  3266. local forLimit = n1(args)
  3267. local i = 1
  3268. while i <= forLimit do
  3269. local val = nth1(node, i + 1)
  3270. if val == nil or builtin_3f_1(val, "nil") then
  3271. lookup[nth1(args, i)["var"]] = {tag="rec-func", parent=node, setter=nil, lambda=nil, recur=0, direct=0, var=0}
  3272. end
  3273. i = i + 1
  3274. end
  3275. if parents then
  3276. parents[node] = true
  3277. else
  3278. parents = {[node]=true}
  3279. end
  3280. visitBlock2(first, 3, parents, active, lookup)
  3281. parents[node] = nil
  3282. return visitNodes1(node, 2, nil, lookup)
  3283. else
  3284. return visitNodes1(node, 1, nil, lookup)
  3285. end
  3286. else
  3287. return visitNodes1(node, 1, nil, lookup)
  3288. end
  3289. else
  3290. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  3291. end
  3292. end
  3293. end
  3294. visitNodes1 = function(node, start, parents, lookup)
  3295. local forLimit = n1(node)
  3296. local i = start
  3297. while i <= forLimit do
  3298. visitNode2(nth1(node, i), parents, nil, lookup)
  3299. i = i + 1
  3300. end
  3301. return nil
  3302. end
  3303. visitBlock2 = function(node, start, parents, active, lookup)
  3304. local forLimit = n1(node) - 1
  3305. local i = start
  3306. while i <= forLimit do
  3307. visitNode2(nth1(node, i), parents, nil, lookup)
  3308. i = i + 1
  3309. end
  3310. if n1(node) >= start then
  3311. return visitNode2(last1(node), parents, active, lookup)
  3312. else
  3313. return nil
  3314. end
  3315. end
  3316. letrecNodes1 = {name="letrec-nodes", help="Find letrec constructs in a list of NODES", cat={tag="list", n=1, "categorise"}, run=function(temp, compiler, nodes, state)
  3317. return visitNodes1(nodes, 1, nil, state["rec-lookup"])
  3318. end}
  3319. letrecNode1 = {name="letrec-node", help="Find letrec constructs in a node", cat={tag="list", n=1, "categorise"}, run=function(temp, compiler, node, state)
  3320. return visitNode2(node, nil, nil, state["rec-lookup"])
  3321. end}
  3322. nodeContainsVar_3f_1 = function(node, var)
  3323. local found = false
  3324. visitNode1(node, function(node1)
  3325. if found then
  3326. return false
  3327. elseif type1(node1) == "list" and builtin_3f_1(car1(node1), "set!") then
  3328. found = var == nth1(node1, 2)["var"]
  3329. return nil
  3330. elseif type1(node1) == "symbol" then
  3331. found = var == node1["var"]
  3332. return nil
  3333. else
  3334. return nil
  3335. end
  3336. end)
  3337. return found
  3338. end
  3339. nodeContainsVars_3f_1 = function(node, vars)
  3340. local found = false
  3341. visitNode1(node, function(node1)
  3342. if found then
  3343. return false
  3344. elseif type1(node1) == "list" and builtin_3f_1(car1(node1), "set!") then
  3345. found = vars[nth1(node1, 2)["var"]]
  3346. return nil
  3347. elseif type1(node1) == "symbol" then
  3348. found = vars[node1["var"]]
  3349. return nil
  3350. else
  3351. return nil
  3352. end
  3353. end)
  3354. return found
  3355. end
  3356. capturedBoundary_3f_1 = function(node)
  3357. return type1(node) == "list" and builtin_3f_1(car1(node), "lambda")
  3358. end
  3359. nodeCaptured1 = function(node, captured, boundary_3f_)
  3360. if not boundary_3f_ then
  3361. boundary_3f_ = capturedBoundary_3f_1
  3362. end
  3363. local capturedVisitor = function(node1)
  3364. if type1(node1) == "symbol" then
  3365. captured[node1["var"]] = true
  3366. return nil
  3367. else
  3368. return nil
  3369. end
  3370. end
  3371. visitNode1(node, function(node1, visitor)
  3372. if boundary_3f_(node1) then
  3373. visitNode1(node1, capturedVisitor)
  3374. return false
  3375. elseif type1(node1) == "list" and (type1((car1(node1))) == "list" and builtin_3f_1(caar1(node1), "lambda")) then
  3376. visitBlock1(car1(node1), 3, visitor)
  3377. visitBlock1(node1, 2, visitor)
  3378. return false
  3379. else
  3380. return true
  3381. end
  3382. end)
  3383. return captured
  3384. end
  3385. partAll1 = function(xs, i, e, f)
  3386. while true do
  3387. if i > e then
  3388. return true
  3389. elseif f(nth1(xs, i)) then
  3390. i = i + 1
  3391. else
  3392. return false
  3393. end
  3394. end
  3395. end
  3396. recurDirect_3f_1 = function(state, var)
  3397. local rec = state["rec-lookup"][var]
  3398. return rec and (rec["var"] == 0 and rec["direct"] == 1)
  3399. end
  3400. notCond_3f_1 = function(first, second)
  3401. return n1(first) == 2 and (builtin_3f_1(nth1(first, 2), "false") and (n1(second) == 2 and (builtin_3f_1(nth1(second, 1), "true") and builtin_3f_1(nth1(second, 2), "true"))))
  3402. end
  3403. andCond_3f_1 = function(lookup, first, second, test)
  3404. local branch, last, temp = car1(first), nth1(second, 2), n1(first) == 2
  3405. return temp and (n1(second) == 2 and (not lookup[nth1(first, 2)]["stmt"] and (builtin_3f_1(car1(second), "true") and (type1(last) == "symbol" and (type1(branch) == "symbol" and branch["var"] == last["var"] or test and (not lookup[branch]["stmt"] and last["var"] == builtins1["false"]))))))
  3406. end
  3407. orCond_3f_1 = function(lookup, branch, test)
  3408. local head, tail, temp = car1(branch), nth1(branch, 2), n1(branch) == 2
  3409. return temp and (type1(tail) == "symbol" and (type1(head) == "symbol" and head["var"] == tail["var"] or test and (not lookup[head]["stmt"] and tail["var"] == builtins1["true"])))
  3410. end
  3411. visitNode3 = function(lookup, state, node, stmt, test, recur)
  3412. local cat
  3413. local temp = type1(node)
  3414. if temp == "string" then
  3415. cat = {category="const", prec=100}
  3416. elseif temp == "number" then
  3417. cat = {category="const", prec=100}
  3418. elseif temp == "key" then
  3419. cat = {category="const", prec=100}
  3420. elseif temp == "symbol" then
  3421. cat = {category="const"}
  3422. elseif temp == "list" then
  3423. local head = car1(node)
  3424. local temp1 = type1(head)
  3425. if temp1 == "symbol" then
  3426. local func = head["var"]
  3427. if func == builtins1["lambda"] then
  3428. visitNodes2(lookup, state, node, 3, true)
  3429. cat = {category="lambda", prec=100}
  3430. elseif func == builtins1["cond"] then
  3431. local forLimit = n1(node)
  3432. local i = 2
  3433. while i <= forLimit do
  3434. local case = nth1(node, i)
  3435. visitNode3(lookup, state, car1(case), true, true)
  3436. visitNodes2(lookup, state, case, 2, true, test, recur)
  3437. i = i + 1
  3438. end
  3439. if n1(node) == 3 and notCond_3f_1(nth1(node, 2), nth1(node, 3)) then
  3440. addParen1(lookup, car1(nth1(node, 2)), 11)
  3441. cat = {category="not", stmt=lookup[car1(nth1(node, 2))]["stmt"], prec=11}
  3442. elseif n1(node) == 3 and andCond_3f_1(lookup, nth1(node, 2), nth1(node, 3), test) then
  3443. addParen1(lookup, nth1(nth1(node, 2), 1), 2)
  3444. addParen1(lookup, nth1(nth1(node, 2), 2), 2)
  3445. cat = {category="and", prec=2}
  3446. else
  3447. local temp2
  3448. if n1(node) >= 3 then
  3449. if partAll1(node, 2, n1(node) - 2, function(temp3)
  3450. return orCond_3f_1(lookup, temp3, test)
  3451. end) then
  3452. local first, second = nth1(node, n1(node) - 1), nth1(node, n1(node))
  3453. temp2 = notCond_3f_1(first, second) or andCond_3f_1(lookup, first, second, test) or orCond_3f_1(lookup, first, test) and (n1(second) == 2 and (builtin_3f_1(car1(second), "true") and not lookup[nth1(second, 2)]["stmt"]))
  3454. else
  3455. temp2 = false
  3456. end
  3457. else
  3458. temp2 = false
  3459. end
  3460. if temp2 then
  3461. local len, first, second = n1(node), nth1(node, n1(node) - 1), nth1(node, n1(node))
  3462. local forLimit = len - 2
  3463. local i = 2
  3464. while i <= forLimit do
  3465. addParen1(lookup, car1(nth1(node, i)), 1)
  3466. i = i + 1
  3467. end
  3468. if notCond_3f_1(first, second) then
  3469. addParen1(lookup, nth1(first, 1), 11)
  3470. cat = {category="or", prec=1, kind="not"}
  3471. elseif andCond_3f_1(lookup, first, second, test) then
  3472. addParen1(lookup, nth1(first, 1), 2)
  3473. addParen1(lookup, nth1(first, 2), 2)
  3474. cat = {category="or", prec=1, kind="and"}
  3475. else
  3476. addParen1(lookup, nth1(first, 1), 1)
  3477. addParen1(lookup, nth1(second, 2), 1)
  3478. cat = {category="or", prec=1, kind="or"}
  3479. end
  3480. elseif n1(node) == 3 and (n1(nth1(node, 2)) == 1 and (builtin_3f_1(car1(nth1(node, 3)), "true") and n1(nth1(node, 3)) > 1)) then
  3481. addParen1(lookup, car1(nth1(node, 2)), 11)
  3482. cat = {category="unless", stmt=true}
  3483. else
  3484. cat = {category="cond", stmt=true}
  3485. end
  3486. end
  3487. elseif func == builtins1["set!"] then
  3488. local def, var = nth1(node, 3), nth1(node, 2)["var"]
  3489. if type1(def) == "list" and (builtin_3f_1(car1(def), "lambda") and state["rec-lookup"][var]) then
  3490. local recur1 = {var=var, def=def}
  3491. visitNodes2(lookup, state, def, 3, true, nil, recur1)
  3492. if not recur1["tail"] then
  3493. error1("Expected tail recursive function from letrec")
  3494. end
  3495. lookup[def] = {category="lambda", prec=100, recur=visitRecur1(lookup, recur1)}
  3496. else
  3497. visitNode3(lookup, state, def, true)
  3498. end
  3499. cat = {category="set!", stmt=true}
  3500. elseif func == builtins1["quote"] then
  3501. visitQuote3(lookup, node)
  3502. cat = {category="quote", prec=100}
  3503. elseif func == builtins1["syntax-quote"] then
  3504. visitSyntaxQuote1(lookup, state, nth1(node, 2), 1)
  3505. cat = {category="syntax-quote", prec=100}
  3506. elseif func == builtins1["unquote"] then
  3507. cat = error1("unquote should never appear", 0)
  3508. elseif func == builtins1["unquote-splice"] then
  3509. cat = error1("unquote should never appear", 0)
  3510. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  3511. local def = nth1(node, n1(node))
  3512. if type1(def) == "list" and builtin_3f_1(car1(def), "lambda") then
  3513. local recur1 = {var=node["def-var"], def=def}
  3514. visitNodes2(lookup, state, def, 3, true, nil, recur1)
  3515. lookup[def] = (function()
  3516. if recur1["tail"] then
  3517. return {category="lambda", prec=100, recur=visitRecur1(lookup, recur1)}
  3518. else
  3519. return {category="lambda", prec=100}
  3520. end
  3521. end)()
  3522. else
  3523. visitNode3(lookup, state, def, true)
  3524. end
  3525. cat = {category="define"}
  3526. elseif func == builtins1["define-native"] then
  3527. cat = {category="define-native"}
  3528. elseif func == builtins1["import"] then
  3529. cat = {category="import"}
  3530. elseif func == builtins1["struct-literal"] then
  3531. visitNodes2(lookup, state, node, 2, false)
  3532. cat = {category="struct-literal", prec=100}
  3533. elseif func == builtins1["true"] then
  3534. visitNodes2(lookup, state, node, 1, false)
  3535. lookup[head]["parens"] = true
  3536. cat = {category="call"}
  3537. elseif func == builtins1["false"] then
  3538. visitNodes2(lookup, state, node, 1, false)
  3539. lookup[head]["parens"] = true
  3540. cat = {category="call"}
  3541. elseif func == builtins1["nil"] then
  3542. visitNodes2(lookup, state, node, 1, false)
  3543. lookup[head]["parens"] = true
  3544. cat = {category="call"}
  3545. else
  3546. local meta = func["kind"] == "native" and varNative1(func)
  3547. if meta and (meta["bind-to"] or not stmt and meta["syntax-stmt"]) then
  3548. meta = nil
  3549. end
  3550. local temp2
  3551. if meta then
  3552. if meta["syntax-fold"] then
  3553. temp2 = n1(node) - 1 >= meta["syntax-arity"]
  3554. else
  3555. temp2 = n1(node) - 1 == meta["syntax-arity"]
  3556. end
  3557. else
  3558. temp2 = false
  3559. end
  3560. if temp2 then
  3561. visitNodes2(lookup, state, node, 1, false)
  3562. local prec = meta["syntax-precedence"]
  3563. if type1(prec) == "list" then
  3564. addParens1(lookup, node, 2, nil, prec)
  3565. elseif number_3f_1(prec) then
  3566. addParens1(lookup, node, 2, prec, nil)
  3567. end
  3568. cat = {category="call-meta", meta=meta, stmt=meta["syntax-stmt"], prec=number_3f_1(prec) and prec}
  3569. elseif recur and func == recur["var"] then
  3570. recur["tail"] = true
  3571. visitNodes2(lookup, state, node, 1, false)
  3572. cat = {category="call-tail", recur=recur, stmt=true}
  3573. elseif stmt and recurDirect_3f_1(state, func) then
  3574. local rec = state["rec-lookup"][func]
  3575. local lam = rec["lambda"]
  3576. local recur1 = lookup[lam]["recur"]
  3577. if not recur1 then
  3578. print1("Cannot find recursion for ", func["name"])
  3579. end
  3580. local temp2 = zipArgs1(cadr1(lam), 1, node, 2)
  3581. local forLimit = n1(temp2)
  3582. local i = 1
  3583. while i <= forLimit do
  3584. local zip = temp2[i]
  3585. local args, vals = car1(zip), cadr1(zip)
  3586. if n1(vals) == 0 then
  3587. elseif n1(vals) > 1 or car1(args)["var"]["is-variadic"] then
  3588. local forLimit1 = n1(vals)
  3589. local i1 = 1
  3590. while i1 <= forLimit1 do
  3591. visitNode3(lookup, state, vals[i1], false)
  3592. i1 = i1 + 1
  3593. end
  3594. else
  3595. visitNode3(lookup, state, car1(vals), true)
  3596. end
  3597. i = i + 1
  3598. end
  3599. lookup[rec["setter"]] = {category="void"}
  3600. state["var-skip"][func] = true
  3601. cat = {category="call-recur", recur=recur1}
  3602. else
  3603. visitNodes2(lookup, state, node, 1, false)
  3604. cat = {category="call-symbol"}
  3605. end
  3606. end
  3607. elseif temp1 == "list" then
  3608. if n1(node) == 2 and (builtin_3f_1(car1(head), "lambda") and (n1(head) == 3 and (n1(nth1(head, 2)) == 1 and (not car1(nth1(head, 2))["var"]["is-variadic"] and (type1((nth1(head, 3))) == "symbol" and nth1(head, 3)["var"] == car1(nth1(head, 2))["var"]))))) then
  3609. if visitNode3(lookup, state, nth1(node, 2), stmt, test)["stmt"] then
  3610. lookup[head] = {category="lambda", prec=100, parens=true}
  3611. visitNode3(lookup, state, nth1(head, 3), true, false)
  3612. cat = {category="call-lambda", stmt=stmt}
  3613. else
  3614. cat = {category="wrap-value"}
  3615. end
  3616. elseif builtin_3f_1(car1(head), "lambda") and (n1(head) == 3 and (n1(nth1(head, 2)) == 1 and (car1(nth1(head, 2))["var"]["is-variadic"] and (type1((nth1(head, 3))) == "symbol" and (nth1(head, 3)["var"] == car1(nth1(head, 2))["var"] and (n1(node) == 1 or singleReturn_3f_1(last1(node)))))))) then
  3617. local nodeStmt = false
  3618. local forLimit = n1(node)
  3619. local i = 2
  3620. while i <= forLimit do
  3621. if visitNode3(lookup, state, nth1(node, i), stmt, test)["stmt"] and not nodeStmt then
  3622. nodeStmt = true
  3623. lookup[head] = {category="lambda", prec=100, parens=true}
  3624. visitNode3(lookup, state, nth1(head, 3), true, false)
  3625. end
  3626. i = i + 1
  3627. end
  3628. if nodeStmt then
  3629. cat = {category="call-lambda", stmt=stmt}
  3630. else
  3631. cat = {category="wrap-list", prec=100}
  3632. end
  3633. else
  3634. local temp2
  3635. if n1(node) == 2 then
  3636. if builtin_3f_1(car1(head), "lambda") then
  3637. if n1(head) == 3 then
  3638. if n1(nth1(head, 2)) == 1 then
  3639. local elem = nth1(head, 3)
  3640. temp2 = type1(elem) == "list" and (builtin_3f_1(car1(elem), "cond") and (type1((car1(nth1(elem, 2)))) == "symbol" and car1(nth1(elem, 2))["var"] == car1(nth1(head, 2))["var"]))
  3641. else
  3642. temp2 = false
  3643. end
  3644. else
  3645. temp2 = false
  3646. end
  3647. else
  3648. temp2 = false
  3649. end
  3650. else
  3651. temp2 = false
  3652. end
  3653. if temp2 then
  3654. if visitNode3(lookup, state, nth1(node, 2), stmt, test)["stmt"] then
  3655. lookup[head] = {category="lambda", prec=100, parens=true}
  3656. visitNode3(lookup, state, nth1(head, 3), true, test, recur)
  3657. cat = {category="call-lambda", stmt=stmt}
  3658. else
  3659. local res = visitNode3(lookup, state, nth1(head, 3), true, test, recur)
  3660. local ty, unused_3f_ = res["category"], function()
  3661. local condNode, var, working = nth1(head, 3), car1(nth1(head, 2))["var"], true
  3662. local forLimit = n1(condNode)
  3663. local i = 2
  3664. while i <= forLimit do
  3665. if working then
  3666. local case = nth1(condNode, i)
  3667. local forLimit1 = n1(case)
  3668. local i1 = 2
  3669. while i1 <= forLimit1 do
  3670. if working then
  3671. local sub = nth1(case, i1)
  3672. if type1(sub) ~= "symbol" then
  3673. working = not nodeContainsVar_3f_1(sub, var)
  3674. end
  3675. end
  3676. i1 = i1 + 1
  3677. end
  3678. end
  3679. i = i + 1
  3680. end
  3681. return working
  3682. end
  3683. lookup[head] = {category="lambda", prec=100, parens=true}
  3684. if ty == "and" and unused_3f_() then
  3685. addParen1(lookup, nth1(node, 2), 2)
  3686. cat = {category="and-lambda", prec=2}
  3687. elseif ty == "or" and unused_3f_() then
  3688. addParen1(lookup, nth1(node, 2), 1)
  3689. cat = {category="or-lambda", prec=1, kind=res["kind"]}
  3690. else
  3691. cat = {category="call-lambda", stmt=stmt}
  3692. end
  3693. end
  3694. elseif builtin_3f_1(car1(head), "lambda") then
  3695. visitNodes2(lookup, state, head, 3, true, test, recur)
  3696. local temp2 = zipArgs1(cadr1(head), 1, node, 2)
  3697. local forLimit = n1(temp2)
  3698. local i = 1
  3699. while i <= forLimit do
  3700. local zip = temp2[i]
  3701. local args, vals = car1(zip), cadr1(zip)
  3702. if n1(vals) == 0 then
  3703. elseif n1(vals) > 1 or car1(args)["var"]["is-variadic"] then
  3704. local forLimit1 = n1(vals)
  3705. local i1 = 1
  3706. while i1 <= forLimit1 do
  3707. visitNode3(lookup, state, vals[i1], false)
  3708. i1 = i1 + 1
  3709. end
  3710. else
  3711. visitNode3(lookup, state, car1(vals), true)
  3712. end
  3713. i = i + 1
  3714. end
  3715. cat = {category="call-lambda", stmt=stmt}
  3716. else
  3717. visitNodes2(lookup, state, node, 1, false)
  3718. addParen1(lookup, car1(node), 100)
  3719. cat = {category="call"}
  3720. end
  3721. end
  3722. else
  3723. visitNodes2(lookup, state, node, 1, false)
  3724. lookup[car1(node)]["parens"] = true
  3725. cat = {category="call"}
  3726. end
  3727. else
  3728. cat = error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  3729. end
  3730. if cat == nil then
  3731. error1("Node returned nil " .. pretty1(node), 0)
  3732. end
  3733. lookup[node] = cat
  3734. return cat
  3735. end
  3736. visitNodes2 = function(lookup, state, nodes, start, stmt, test, recur)
  3737. local len = n1(nodes)
  3738. local i = start
  3739. while i <= len do
  3740. visitNode3(lookup, state, nth1(nodes, i), stmt, test and i == len, i == len and recur)
  3741. i = i + 1
  3742. end
  3743. return nil
  3744. end
  3745. visitSyntaxQuote1 = function(lookup, state, node, level)
  3746. if level == 0 then
  3747. return visitNode3(lookup, state, node, false)
  3748. else
  3749. local cat
  3750. local temp = type1(node)
  3751. if temp == "string" then
  3752. cat = {category="quote-const"}
  3753. elseif temp == "number" then
  3754. cat = {category="quote-const"}
  3755. elseif temp == "key" then
  3756. cat = {category="quote-const"}
  3757. elseif temp == "symbol" then
  3758. cat = {category="quote-const"}
  3759. elseif temp == "list" then
  3760. local temp1 = car1(node)
  3761. if eq_3f_1(temp1, {tag="symbol", contents="unquote"}) then
  3762. visitSyntaxQuote1(lookup, state, nth1(node, 2), level - 1)
  3763. cat = {category="unquote"}
  3764. elseif eq_3f_1(temp1, {tag="symbol", contents="unquote-splice"}) then
  3765. visitSyntaxQuote1(lookup, state, nth1(node, 2), level - 1)
  3766. cat = {category="unquote-splice"}
  3767. elseif eq_3f_1(temp1, {tag="symbol", contents="syntax-quote"}) then
  3768. local forLimit = n1(node)
  3769. local i = 1
  3770. while i <= forLimit do
  3771. visitSyntaxQuote1(lookup, state, node[i], level + 1)
  3772. i = i + 1
  3773. end
  3774. cat = {category="quote-list"}
  3775. else
  3776. local hasSplice = false
  3777. local forLimit = n1(node)
  3778. local i = 1
  3779. while i <= forLimit do
  3780. if visitSyntaxQuote1(lookup, state, node[i], level)["category"] == "unquote-splice" then
  3781. hasSplice = true
  3782. end
  3783. i = i + 1
  3784. end
  3785. if hasSplice then
  3786. cat = {category="quote-splice", stmt=true}
  3787. else
  3788. cat = {category="quote-list"}
  3789. end
  3790. end
  3791. else
  3792. cat = error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  3793. end
  3794. if cat == nil then
  3795. error1("Node returned nil " .. pretty1(node), 0)
  3796. end
  3797. lookup[node] = cat
  3798. return cat
  3799. end
  3800. end
  3801. visitQuote3 = function(lookup, node)
  3802. if type1(node) == "list" then
  3803. local forLimit = n1(node)
  3804. local i = 1
  3805. while i <= forLimit do
  3806. visitQuote3(lookup, (node[i]))
  3807. i = i + 1
  3808. end
  3809. lookup[node] = {category="quote-list"}
  3810. return nil
  3811. else
  3812. lookup[node] = {category="quote-const"}
  3813. return nil
  3814. end
  3815. end
  3816. visitRecur1 = function(lookup, recur)
  3817. local lam, allCaptured, argCaptured, recBoundary = recur["def"], {}, {}, function(node)
  3818. if type1(node) == "list" and builtin_3f_1(car1(node), "lambda") then
  3819. local cat = lookup[node]
  3820. return not (cat and cat["recur"])
  3821. else
  3822. return false
  3823. end
  3824. end
  3825. local forLimit = n1(lam)
  3826. local i = 3
  3827. while i <= forLimit do
  3828. nodeCaptured1(nth1(lam, i), allCaptured, recBoundary)
  3829. i = i + 1
  3830. end
  3831. local temp = cadr1(lam)
  3832. local forLimit = n1(temp)
  3833. local i = 1
  3834. while i <= forLimit do
  3835. local arg = temp[i]
  3836. if allCaptured[arg["var"]] then
  3837. argCaptured[arg["var"]] = tempVar1(arg["var"]["name"])
  3838. end
  3839. i = i + 1
  3840. end
  3841. recur["captured"] = argCaptured
  3842. local temp
  3843. if n1(lam) == 3 then
  3844. local child = nth1(lam, 3)
  3845. temp = type1(child) == "list" and (builtin_3f_1(car1(child), "cond") and (n1(child) == 3 and (builtin_3f_1(car1(nth1(child, 3)), "true") and not lookup[car1(nth1(child, 2))]["stmt"])))
  3846. else
  3847. temp = false
  3848. end
  3849. if temp then
  3850. local fstCase, sndCase = nth1(nth1(lam, 3), 2), nth1(nth1(lam, 3), 3)
  3851. local fst, snd = n1(fstCase) >= 2 and justRecur_3f_1(lookup, last1(fstCase), recur), n1(sndCase) >= 2 and justRecur_3f_1(lookup, last1(sndCase), recur)
  3852. if fst and snd then
  3853. recur["category"] = "forever"
  3854. elseif fst then
  3855. recur["category"] = "while"
  3856. elseif snd then
  3857. recur["category"] = "while-not"
  3858. else
  3859. recur["category"] = "forever"
  3860. end
  3861. else
  3862. recur["category"] = "forever"
  3863. end
  3864. return recur
  3865. end
  3866. justRecur_3f_1 = function(lookup, node, recur)
  3867. while true do
  3868. if type1(node) == "list" then
  3869. local cat, head = lookup[node], car1(node)
  3870. if cat["category"] == "call-tail" then
  3871. if cat["recur"] ~= recur then
  3872. error1("Incorrect recur")
  3873. end
  3874. return true
  3875. elseif type1(head) == "list" and builtin_3f_1(car1(head), "lambda") then
  3876. local temp = n1(head) >= 3
  3877. if temp then
  3878. node = last1(head)
  3879. else
  3880. return temp
  3881. end
  3882. elseif builtin_3f_1(head, "cond") then
  3883. local found = true
  3884. local forLimit = n1(node)
  3885. local i = 2
  3886. while i <= forLimit do
  3887. if found then
  3888. local case = nth1(node, i)
  3889. found = n1(case) >= 2 and justRecur_3f_1(lookup, last1(case), recur)
  3890. end
  3891. i = i + 1
  3892. end
  3893. return found
  3894. else
  3895. return false
  3896. end
  3897. else
  3898. return false
  3899. end
  3900. end
  3901. end
  3902. addParens1 = function(lookup, nodes, start, prec, precs)
  3903. local forLimit = n1(nodes)
  3904. local i = start
  3905. while i <= forLimit do
  3906. local childCat = lookup[nth1(nodes, i)]
  3907. if childCat["prec"] and childCat["prec"] <= (function()
  3908. if precs then
  3909. return nth1(precs, i - 1)
  3910. else
  3911. return prec
  3912. end
  3913. end)() then
  3914. childCat["parens"] = true
  3915. end
  3916. i = i + 1
  3917. end
  3918. return nil
  3919. end
  3920. addParen1 = function(lookup, node, prec)
  3921. local childCat = lookup[node]
  3922. if childCat["prec"] and childCat["prec"] <= prec then
  3923. childCat["parens"] = true
  3924. return nil
  3925. else
  3926. return nil
  3927. end
  3928. end
  3929. categoriseNodes1 = {name="categorise-nodes", help="Categorise a group of NODES, annotating their appropriate node type.", cat={tag="list", n=1, "categorise"}, run=function(temp, compiler, nodes, state)
  3930. return visitNodes2(state["cat-lookup"], state, nodes, 1, true)
  3931. end}
  3932. categoriseNode1 = {name="categorise-node", help="Categorise a NODE, annotating it's appropriate node type.", cat={tag="list", n=1, "categorise"}, run=function(temp, compiler, node, state, stmt)
  3933. return visitNode3(state["cat-lookup"], state, node, stmt)
  3934. end}
  3935. formatRange1 = function(range)
  3936. if range["finish"] then
  3937. return format1("%s:[%s .. %s]", range["name"], (function()
  3938. local pos = range["start"]
  3939. return pos["line"] .. ":" .. pos["column"]
  3940. end)(), (function()
  3941. local pos = range["finish"]
  3942. return pos["line"] .. ":" .. pos["column"]
  3943. end)())
  3944. else
  3945. return format1("%s:[%s]", range["name"], (function()
  3946. local pos = range["start"]
  3947. return pos["line"] .. ":" .. pos["column"]
  3948. end)())
  3949. end
  3950. end
  3951. formatNodeSource1 = function(source)
  3952. local owner, range = source["owner"], sourceFullRange1(source)
  3953. local rangef
  3954. if range then
  3955. rangef = formatRange1(range)
  3956. else
  3957. rangef = "?"
  3958. end
  3959. if owner then
  3960. return format1("macro expansion of %s (at %s)", owner["name"], rangef)
  3961. else
  3962. return format1("unquote expansion (at %s)", rangef)
  3963. end
  3964. end
  3965. formatNodeSourceName1 = function(source)
  3966. local owner = source["owner"]
  3967. if owner then
  3968. return owner["name"]
  3969. else
  3970. return "?"
  3971. end
  3972. end
  3973. formatSource1 = function(source)
  3974. local temp = type1(source)
  3975. if temp == "node-source" then
  3976. return formatNodeSource1(source)
  3977. elseif temp == "range" then
  3978. return formatRange1(source)
  3979. elseif temp == "nil" then
  3980. return "?"
  3981. else
  3982. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"node-source\"`\n Tried: `\"range\"`\n Tried: `\"nil\"`")
  3983. end
  3984. end
  3985. formatNode1 = function(node)
  3986. if node then
  3987. return formatSource1(node["source"])
  3988. else
  3989. return "?"
  3990. end
  3991. end
  3992. keywords1 = createLookup1({tag="list", n=21, "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"})
  3993. luaIdent_3f_1 = function(ident)
  3994. return match1(ident, "^[%a_][%w_]*$") and keywords1[ident] == nil
  3995. end
  3996. escape1 = function(name)
  3997. if name == "" then
  3998. return "_e"
  3999. elseif keywords1[name] then
  4000. return "_e" .. name
  4001. elseif find1(name, "^%a%w*$") then
  4002. return name
  4003. else
  4004. local out
  4005. if find1(sub1(name, 1, 1), "%d") then
  4006. out = "_e"
  4007. else
  4008. out = ""
  4009. end
  4010. local upper, esc = false, false
  4011. local forLimit = n1(name)
  4012. local i = 1
  4013. while i <= forLimit do
  4014. local char = sub1(name, i, i)
  4015. if char == "-" and (find1((function()
  4016. local x = i - 1
  4017. return sub1(name, x, x)
  4018. end)(), "[%a%d']") and find1((function()
  4019. local x = i + 1
  4020. return sub1(name, x, x)
  4021. end)(), "[%a%d']")) then
  4022. upper = true
  4023. elseif find1(char, "[^%w%d]") then
  4024. char = format1("%02x", (byte1(char)))
  4025. upper = false
  4026. if not esc then
  4027. esc = true
  4028. out = out .. "_"
  4029. end
  4030. out = out .. char
  4031. else
  4032. if esc then
  4033. esc = false
  4034. out = out .. "_"
  4035. end
  4036. if upper then
  4037. upper = false
  4038. char = upper1(char)
  4039. end
  4040. out = out .. char
  4041. end
  4042. i = i + 1
  4043. end
  4044. if esc then
  4045. out = out .. "_"
  4046. end
  4047. return out
  4048. end
  4049. end
  4050. pushEscapeVar_21_1 = function(var, state, forceNum)
  4051. local temp = state["var-lookup"][var]
  4052. if temp then
  4053. return temp
  4054. else
  4055. local esc = escape1(var["display-name"] or var["name"])
  4056. local existing = state["var-cache"][esc]
  4057. if forceNum or existing then
  4058. local ctr, finding = 1, true
  4059. while finding do
  4060. local esc_27_ = esc .. ctr
  4061. if state["var-cache"][esc_27_] then
  4062. ctr = ctr + 1
  4063. else
  4064. finding = false
  4065. esc = esc_27_
  4066. end
  4067. end
  4068. end
  4069. state["var-cache"][esc] = true
  4070. state["var-lookup"][var] = esc
  4071. return esc
  4072. end
  4073. end
  4074. popEscapeVar_21_1 = function(var, state)
  4075. local esc = state["var-lookup"][var]
  4076. if not esc then
  4077. error1(var["name"] .. " has not been escaped (when popping).", 0)
  4078. end
  4079. state["var-cache"][esc] = nil
  4080. state["var-lookup"][var] = nil
  4081. return nil
  4082. end
  4083. renameEscapeVar_21_1 = function(from, to, state)
  4084. local esc = state["var-lookup"][from]
  4085. if not esc then
  4086. error1(from["name"] .. " has not been escaped (when renaming).", 0)
  4087. end
  4088. if state["var-lookup"][to] then
  4089. error1(to["name"] .. " already has a name (when renaming).", 0)
  4090. end
  4091. state["var-lookup"][from] = nil
  4092. state["var-lookup"][to] = esc
  4093. return nil
  4094. end
  4095. escapeVar1 = function(var, state)
  4096. if builtinVars1[var] ~= nil then
  4097. return var["name"]
  4098. else
  4099. local esc = state["var-lookup"][var]
  4100. if not esc then
  4101. formatOutput_21_1(1, "" .. var["name"] .. " has not been escaped (at " .. (function()
  4102. if var["node"] then
  4103. return formatNode1(var["node"])
  4104. else
  4105. return "?"
  4106. end
  4107. end)() .. ")")
  4108. end
  4109. return esc
  4110. end
  4111. end
  4112. createPassState1 = function(state)
  4113. return {["var-cache"]=state["var-cache"], ["var-lookup"]=state["var-lookup"], ["var-skip"]={}, ["cat-lookup"]={}, ["rec-lookup"]={}}
  4114. end
  4115. symVariadic_3f_1 = function(sym)
  4116. return sym["var"]["is-variadic"]
  4117. end
  4118. breakCategories1 = {cond=true, unless=true, ["call-lambda"]=true, ["call-tail"]=true}
  4119. constCategories1 = {const=true, quote=true, ["quote-const"]=true}
  4120. compileNativeFold1 = function(out, meta, a, b)
  4121. local temp = meta["syntax"]
  4122. local forLimit = n1(temp)
  4123. local i = 1
  4124. while i <= forLimit do
  4125. local entry = temp[i]
  4126. if entry == 1 then
  4127. append_21_1(out, a)
  4128. elseif entry == 2 then
  4129. append_21_1(out, b)
  4130. elseif string_3f_1(entry) then
  4131. append_21_1(out, entry)
  4132. else
  4133. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(entry) .. ", but none matched.\n" .. " Tried: `1`\n Tried: `2`\n Tried: `string?`")
  4134. end
  4135. i = i + 1
  4136. end
  4137. return nil
  4138. end
  4139. compileNative1 = function(out, var, meta)
  4140. if meta["bind-to"] then
  4141. return append_21_1(out, meta["bind-to"], out["active-pos"])
  4142. elseif meta["syntax"] then
  4143. append_21_1(out, "function(")
  4144. if meta["syntax-fold"] then
  4145. append_21_1(out, "x, ...")
  4146. else
  4147. local forLimit = meta["syntax-arity"]
  4148. local i = 1
  4149. while i <= forLimit do
  4150. if i ~= 1 then
  4151. append_21_1(out, ", ")
  4152. end
  4153. append_21_1(out, "v" .. tonumber1(i))
  4154. i = i + 1
  4155. end
  4156. end
  4157. append_21_1(out, ") ")
  4158. local temp = meta["syntax-fold"]
  4159. if temp == nil then
  4160. if not meta["syntax-stmt"] then
  4161. append_21_1(out, "return ")
  4162. end
  4163. local temp1 = meta["syntax"]
  4164. local forLimit = n1(temp1)
  4165. local i = 1
  4166. while i <= forLimit do
  4167. local entry = temp1[i]
  4168. if number_3f_1(entry) then
  4169. append_21_1(out, "v" .. tonumber1(entry))
  4170. else
  4171. append_21_1(out, entry)
  4172. end
  4173. i = i + 1
  4174. end
  4175. elseif temp == "left" then
  4176. append_21_1(out, "local t = ")
  4177. compileNativeFold1(out, meta, "x", "...")
  4178. append_21_1(out, " for i = 2, _select('#', ...) do t = ")
  4179. compileNativeFold1(out, meta, "t", "_select(i, ...)")
  4180. append_21_1(out, " end return t")
  4181. elseif temp == "right" then
  4182. append_21_1(out, "local n = _select('#', ...) local t = _select(n, ...) for i = n - 1, 1, -1 do t = ")
  4183. compileNativeFold1(out, meta, "_select(i, ...)", "t")
  4184. append_21_1(out, " end return ")
  4185. compileNativeFold1(out, meta, "x", "t")
  4186. else
  4187. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `nil`\n Tried: `\"left\"`\n Tried: `\"right\"`")
  4188. end
  4189. return append_21_1(out, " end")
  4190. else
  4191. append_21_1(out, "_libs[")
  4192. append_21_1(out, quoted1(var["unique-name"]))
  4193. return append_21_1(out, "]")
  4194. end
  4195. end
  4196. compileExpression1 = function(node, out, state, ret, _ebreak)
  4197. local catLookup = state["cat-lookup"]
  4198. local cat = catLookup[node]
  4199. local _5f_
  4200. if cat then
  4201. _5f_ = nil
  4202. else
  4203. _5f_ = print1("Cannot find", pretty1(node), formatNode1(node))
  4204. end
  4205. local catTag = cat["category"]
  4206. pushNode_21_1(out, node)
  4207. if catTag == "void" then
  4208. if not (ret == "") then
  4209. if ret then
  4210. append_21_1(out, ret)
  4211. end
  4212. append_21_1(out, "nil")
  4213. end
  4214. elseif catTag == "const" then
  4215. if not (ret == "") then
  4216. if ret then
  4217. append_21_1(out, ret, out["active-pos"])
  4218. end
  4219. if cat["parens"] then
  4220. append_21_1(out, "(")
  4221. end
  4222. if type1(node) == "symbol" then
  4223. append_21_1(out, escapeVar1(node["var"], state), out["active-pos"])
  4224. elseif string_3f_1(node) then
  4225. append_21_1(out, quoted1(node["value"]), out["active-pos"])
  4226. elseif number_3f_1(node) then
  4227. append_21_1(out, tostring1(node["value"]), out["active-pos"])
  4228. elseif type1(node) == "key" then
  4229. append_21_1(out, quoted1(node["value"]), out["active-pos"])
  4230. else
  4231. error1("Unknown type: " .. type1(node))
  4232. end
  4233. if cat["parens"] then
  4234. append_21_1(out, ")")
  4235. end
  4236. end
  4237. elseif catTag == "lambda" then
  4238. if not (ret == "") then
  4239. if ret then
  4240. local pos = sourceRange1(node["source"])
  4241. append_21_1(out, ret, pos and rangeOfStart1(pos))
  4242. end
  4243. local args, variadic, i = nth1(node, 2), nil, 1
  4244. if cat["parens"] then
  4245. append_21_1(out, "(")
  4246. end
  4247. append_21_1(out, "function(")
  4248. while i <= n1(args) and not variadic do
  4249. if i > 1 then
  4250. append_21_1(out, ", ")
  4251. end
  4252. local var = args[i]["var"]
  4253. if var["is-variadic"] then
  4254. append_21_1(out, "...")
  4255. variadic = i
  4256. else
  4257. append_21_1(out, pushEscapeVar_21_1(var, state))
  4258. end
  4259. i = i + 1
  4260. end
  4261. beginBlock_21_1(out, ")")
  4262. if variadic then
  4263. local argsVar = pushEscapeVar_21_1(args[variadic]["var"], state)
  4264. if variadic == n1(args) then
  4265. line_21_1(out, "local " .. argsVar .. " = _pack(...) " .. argsVar .. ".tag = \"list\"")
  4266. else
  4267. line_21_1(out, "local _n = _select(\"#\", ...) - " .. tostring1((n1(args) - variadic)))
  4268. append_21_1(out, "local " .. argsVar)
  4269. local forStart, forLimit = variadic + 1, n1(args)
  4270. local i1 = forStart
  4271. while i1 <= forLimit do
  4272. append_21_1(out, ", ")
  4273. append_21_1(out, pushEscapeVar_21_1(args[i1]["var"], state))
  4274. i1 = i1 + 1
  4275. end
  4276. line_21_1(out)
  4277. beginBlock_21_1(out, "if _n > 0 then")
  4278. append_21_1(out, argsVar)
  4279. line_21_1(out, " = {tag=\"list\", n=_n, _unpack(_pack(...), 1, _n)}")
  4280. local forStart, forLimit = variadic + 1, n1(args)
  4281. local i1 = forStart
  4282. while i1 <= forLimit do
  4283. append_21_1(out, escapeVar1(args[i1]["var"], state))
  4284. if i1 < n1(args) then
  4285. append_21_1(out, ", ")
  4286. end
  4287. i1 = i1 + 1
  4288. end
  4289. line_21_1(out, " = select(_n + 1, ...)")
  4290. nextBlock_21_1(out, "else")
  4291. append_21_1(out, argsVar)
  4292. line_21_1(out, " = {tag=\"list\", n=0}")
  4293. local forStart, forLimit = variadic + 1, n1(args)
  4294. local i1 = forStart
  4295. while i1 <= forLimit do
  4296. append_21_1(out, escapeVar1(args[i1]["var"], state))
  4297. if i1 < n1(args) then
  4298. append_21_1(out, ", ")
  4299. end
  4300. i1 = i1 + 1
  4301. end
  4302. line_21_1(out, " = ...")
  4303. endBlock_21_1(out, "end")
  4304. end
  4305. end
  4306. if cat["recur"] then
  4307. compileRecur1(cat["recur"], out, state, "return ")
  4308. else
  4309. compileBlock1(node, out, state, 3, "return ")
  4310. end
  4311. out["indent"] = out["indent"] - 1
  4312. local forLimit = n1(args)
  4313. local i1 = 1
  4314. while i1 <= forLimit do
  4315. popEscapeVar_21_1(args[i1]["var"], state)
  4316. i1 = i1 + 1
  4317. end
  4318. append_21_1(out, "end")
  4319. if cat["parens"] then
  4320. append_21_1(out, ")")
  4321. end
  4322. end
  4323. elseif catTag == "cond" then
  4324. local closure, hadFinal, ends = not ret, false, 1
  4325. if closure then
  4326. beginBlock_21_1(out, "(function()")
  4327. ret = "return "
  4328. end
  4329. local i = 2
  4330. while not hadFinal and i <= n1(node) do
  4331. local item = nth1(node, i)
  4332. local case = nth1(item, 1)
  4333. local isFinal = builtin_3f_1(case, "true")
  4334. if i > 2 and (not isFinal or ret ~= "" or _ebreak or n1(item) ~= 1 and fastAny1(function(x)
  4335. return not constCategories1[catLookup[x]["category"]]
  4336. end, item, 2)) then
  4337. append_21_1(out, "else")
  4338. end
  4339. if isFinal then
  4340. if i == 2 then
  4341. append_21_1(out, "do")
  4342. end
  4343. elseif catLookup[case]["stmt"] then
  4344. if i > 2 then
  4345. out["indent"] = out["indent"] + 1
  4346. line_21_1(out)
  4347. ends = ends + 1
  4348. end
  4349. local var = tempVar1("temp", node)
  4350. local tmp = pushEscapeVar_21_1(var, state)
  4351. line_21_1(out, "local " .. tmp)
  4352. compileExpression1(case, out, state, tmp .. " = ")
  4353. line_21_1(out)
  4354. popEscapeVar_21_1(var, state)
  4355. line_21_1(out, "if " .. tmp .. " then")
  4356. else
  4357. append_21_1(out, "if ")
  4358. compileExpression1(case, out, state)
  4359. append_21_1(out, " then")
  4360. end
  4361. out["indent"] = out["indent"] + 1
  4362. line_21_1(out)
  4363. compileBlock1(item, out, state, 2, ret, _ebreak)
  4364. out["indent"] = out["indent"] - 1
  4365. if isFinal then
  4366. hadFinal = true
  4367. end
  4368. i = i + 1
  4369. end
  4370. if not hadFinal then
  4371. append_21_1(out, "else")
  4372. out["indent"] = out["indent"] + 1
  4373. line_21_1(out)
  4374. local source = sourceRange1(node["source"])
  4375. append_21_1(out, "_error(\"unmatched item\")", source and rangeOfStart1(source))
  4376. out["indent"] = out["indent"] - 1
  4377. line_21_1(out)
  4378. end
  4379. local forLimit = ends
  4380. local i = 1
  4381. while i <= forLimit do
  4382. append_21_1(out, "end")
  4383. if i < ends then
  4384. out["indent"] = out["indent"] - 1
  4385. line_21_1(out)
  4386. end
  4387. i = i + 1
  4388. end
  4389. if closure then
  4390. line_21_1(out)
  4391. out["indent"] = out["indent"] - 1
  4392. append_21_1(out, "end)()")
  4393. end
  4394. elseif catTag == "unless" then
  4395. local closure = not ret
  4396. if closure then
  4397. beginBlock_21_1(out, "(function()")
  4398. ret = "return "
  4399. end
  4400. local test = car1(nth1(node, 2))
  4401. if catLookup[test]["stmt"] then
  4402. local var = tempVar1("temp", node)
  4403. local tmp = pushEscapeVar_21_1(var, state)
  4404. line_21_1(out, "local " .. tmp)
  4405. compileExpression1(test, out, state, tmp .. " = ")
  4406. line_21_1(out)
  4407. popEscapeVar_21_1(var, state)
  4408. if _ebreak or ret and ret ~= "" then
  4409. beginBlock_21_1(out, formatOutput_21_1(nil, "if " .. tmp .. " then"))
  4410. compileBlock1(nth1(node, 2), out, state, 2, ret, _ebreak)
  4411. nextBlock_21_1(out, "else")
  4412. else
  4413. beginBlock_21_1(out, formatOutput_21_1(nil, "if not " .. tmp .. " then"))
  4414. end
  4415. elseif _ebreak or ret and ret ~= "" then
  4416. append_21_1(out, "if ")
  4417. compileExpression1(test, out, state)
  4418. beginBlock_21_1(out, " then")
  4419. compileBlock1(nth1(node, 2), out, state, 2, ret, _ebreak)
  4420. nextBlock_21_1(out, "else")
  4421. else
  4422. append_21_1(out, "if not ")
  4423. compileExpression1(test, out, state)
  4424. beginBlock_21_1(out, " then")
  4425. end
  4426. compileBlock1(nth1(node, 3), out, state, 2, ret, _ebreak)
  4427. endBlock_21_1(out, "end")
  4428. if closure then
  4429. line_21_1(out)
  4430. out["indent"] = out["indent"] - 1
  4431. append_21_1(out, "end)()")
  4432. end
  4433. elseif catTag == "not" then
  4434. if cat["parens"] then
  4435. append_21_1(out, "(")
  4436. end
  4437. if ret then
  4438. ret = ret .. "not "
  4439. else
  4440. append_21_1(out, "not ")
  4441. end
  4442. compileExpression1(car1(nth1(node, 2)), out, state, ret)
  4443. if cat["parens"] then
  4444. append_21_1(out, ")")
  4445. end
  4446. elseif catTag == "or" then
  4447. if ret then
  4448. append_21_1(out, ret)
  4449. end
  4450. if cat["parens"] then
  4451. append_21_1(out, "(")
  4452. end
  4453. local len = n1(node)
  4454. local forLimit = len - 2
  4455. local i = 2
  4456. while i <= forLimit do
  4457. compileExpression1(car1(nth1(node, i)), out, state)
  4458. append_21_1(out, " or ")
  4459. i = i + 1
  4460. end
  4461. local temp = cat["kind"]
  4462. if temp == "not" then
  4463. append_21_1(out, "not ")
  4464. compileExpression1(nth1(nth1(node, len - 1), 1), out, state)
  4465. elseif temp == "and" then
  4466. compileExpression1(nth1(nth1(node, len - 1), 1), out, state)
  4467. append_21_1(out, " and ")
  4468. compileExpression1(nth1(nth1(node, len - 1), 2), out, state)
  4469. elseif temp == "or" then
  4470. compileExpression1(nth1(nth1(node, len - 1), 1), out, state)
  4471. append_21_1(out, " or ")
  4472. compileExpression1(nth1(nth1(node, len), 2), out, state)
  4473. else
  4474. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"not\"`\n Tried: `\"and\"`\n Tried: `\"or\"`")
  4475. end
  4476. if cat["parens"] then
  4477. append_21_1(out, ")")
  4478. end
  4479. elseif catTag == "or-lambda" then
  4480. if ret then
  4481. append_21_1(out, ret)
  4482. end
  4483. if cat["parens"] then
  4484. append_21_1(out, "(")
  4485. end
  4486. compileExpression1(nth1(node, 2), out, state)
  4487. local branch = nth1(car1(node), 3)
  4488. local len = n1(branch)
  4489. append_21_1(out, " or ")
  4490. local forLimit = len - 2
  4491. local i = 3
  4492. while i <= forLimit do
  4493. compileExpression1(car1(nth1(branch, i)), out, state)
  4494. append_21_1(out, " or ")
  4495. i = i + 1
  4496. end
  4497. local temp = cat["kind"]
  4498. if temp == "not" then
  4499. append_21_1(out, "not ")
  4500. compileExpression1(nth1(nth1(branch, len - 1), 1), out, state)
  4501. elseif temp == "and" then
  4502. compileExpression1(nth1(nth1(branch, len - 1), 1), out, state)
  4503. append_21_1(out, " and ")
  4504. compileExpression1(nth1(nth1(branch, len - 1), 2), out, state)
  4505. elseif temp == "or" then
  4506. if len > 3 then
  4507. compileExpression1(nth1(nth1(branch, len - 1), 1), out, state)
  4508. append_21_1(out, " or ")
  4509. end
  4510. compileExpression1(nth1(nth1(branch, len), 2), out, state)
  4511. else
  4512. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"not\"`\n Tried: `\"and\"`\n Tried: `\"or\"`")
  4513. end
  4514. if cat["parens"] then
  4515. append_21_1(out, ")")
  4516. end
  4517. elseif catTag == "and" then
  4518. if ret then
  4519. append_21_1(out, ret)
  4520. end
  4521. if cat["parens"] then
  4522. append_21_1(out, "(")
  4523. end
  4524. compileExpression1(nth1(nth1(node, 2), 1), out, state)
  4525. append_21_1(out, " and ")
  4526. compileExpression1(nth1(nth1(node, 2), 2), out, state)
  4527. if cat["parens"] then
  4528. append_21_1(out, ")")
  4529. end
  4530. elseif catTag == "and-lambda" then
  4531. if ret then
  4532. append_21_1(out, ret)
  4533. end
  4534. if cat["parens"] then
  4535. append_21_1(out, "(")
  4536. end
  4537. compileExpression1(nth1(node, 2), out, state)
  4538. append_21_1(out, " and ")
  4539. compileExpression1(nth1(nth1(nth1(car1(node), 3), 2), 2), out, state)
  4540. if cat["parens"] then
  4541. append_21_1(out, ")")
  4542. end
  4543. elseif catTag == "set!" then
  4544. if not ret then
  4545. beginBlock_21_1(out, "(function()")
  4546. end
  4547. compileExpression1(nth1(node, 3), out, state, escapeVar1(node[2]["var"], state) .. " = ")
  4548. if not ret then
  4549. line_21_1(out)
  4550. out["indent"] = out["indent"] - 1
  4551. append_21_1(out, "end)()")
  4552. elseif ret == "" then
  4553. else
  4554. line_21_1(out)
  4555. append_21_1(out, ret)
  4556. append_21_1(out, "nil")
  4557. end
  4558. elseif catTag == "struct-literal" then
  4559. if ret == "" then
  4560. append_21_1(out, "local _ = ")
  4561. elseif ret then
  4562. append_21_1(out, ret)
  4563. end
  4564. if cat["parens"] then
  4565. append_21_1(out, "(")
  4566. end
  4567. local temp = n1(node)
  4568. if temp == 1 then
  4569. append_21_1(out, "{}", out["active-pos"])
  4570. else
  4571. append_21_1(out, "{")
  4572. local i = 2
  4573. while i <= temp do
  4574. if i > 2 then
  4575. append_21_1(out, ", ")
  4576. end
  4577. local key = nth1(node, i)
  4578. local tkey = type1(key)
  4579. if (tkey == "string" or tkey == "key") and luaIdent_3f_1(key["value"]) then
  4580. append_21_1(out, key["value"])
  4581. append_21_1(out, "=")
  4582. else
  4583. append_21_1(out, "[")
  4584. compileExpression1(key, out, state)
  4585. append_21_1(out, "]=")
  4586. end
  4587. compileExpression1(nth1(node, i + 1), out, state)
  4588. i = i + 2
  4589. end
  4590. append_21_1(out, "}")
  4591. end
  4592. if cat["parens"] then
  4593. append_21_1(out, ")")
  4594. end
  4595. elseif catTag == "define" then
  4596. compileExpression1(nth1(node, n1(node)), out, state, pushEscapeVar_21_1(node["def-var"], state) .. " = ")
  4597. elseif catTag == "define-native" then
  4598. local var = node["def-var"]
  4599. append_21_1(out, format1("%s = ", escapeVar1(var, state)), out["active-pos"])
  4600. compileNative1(out, var, varNative1(var))
  4601. elseif catTag == "quote" then
  4602. if not (ret == "") then
  4603. if ret then
  4604. append_21_1(out, ret)
  4605. end
  4606. if cat["parens"] then
  4607. append_21_1(out, "(")
  4608. end
  4609. compileExpression1(nth1(node, 2), out, state)
  4610. if cat["parens"] then
  4611. append_21_1(out, ")")
  4612. end
  4613. end
  4614. elseif catTag == "quote-const" then
  4615. if not (ret == "") then
  4616. if ret then
  4617. append_21_1(out, ret)
  4618. end
  4619. if cat["parens"] then
  4620. append_21_1(out, "(")
  4621. end
  4622. local temp = type1(node)
  4623. if temp == "string" then
  4624. append_21_1(out, quoted1(node["value"]), out["active-pos"])
  4625. elseif temp == "number" then
  4626. append_21_1(out, tostring1(node["value"]), out["active-pos"])
  4627. elseif temp == "symbol" then
  4628. append_21_1(out, "{tag=\"symbol\", contents=" .. quoted1(node["contents"]), out["active-pos"])
  4629. if node["var"] then
  4630. append_21_1(out, ", var=" .. quoted1(tostring1(node["var"])), out["active-pos"])
  4631. end
  4632. append_21_1(out, "}", out["active-pos"])
  4633. elseif temp == "key" then
  4634. append_21_1(out, "{tag=\"key\", value=" .. quoted1(node["value"]) .. "}", out["active-pos"])
  4635. else
  4636. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"symbol\"`\n Tried: `\"key\"`")
  4637. end
  4638. if cat["parens"] then
  4639. append_21_1(out, ")")
  4640. end
  4641. end
  4642. elseif catTag == "quote-list" then
  4643. if ret == "" then
  4644. append_21_1(out, "local _ = ")
  4645. elseif ret then
  4646. append_21_1(out, ret)
  4647. end
  4648. local temp = n1(node)
  4649. if temp == 0 then
  4650. append_21_1(out, "{tag=\"list\", n=0}", out["active-pos"])
  4651. else
  4652. append_21_1(out, "{tag=\"list\", n=" .. tostring1(temp))
  4653. local forLimit = n1(node)
  4654. local i = 1
  4655. while i <= forLimit do
  4656. local sub = node[i]
  4657. append_21_1(out, ", ")
  4658. compileExpression1(sub, out, state)
  4659. i = i + 1
  4660. end
  4661. append_21_1(out, "}")
  4662. end
  4663. elseif catTag == "quote-splice" then
  4664. if not ret then
  4665. beginBlock_21_1(out, "(function()")
  4666. end
  4667. line_21_1(out, "local _offset, _result, _temp = 0, {tag=\"list\"}")
  4668. local offset = 0
  4669. local forLimit = n1(node)
  4670. local i = 1
  4671. while i <= forLimit do
  4672. local sub = nth1(node, i)
  4673. local cat1 = state["cat-lookup"][sub]
  4674. if not cat1 then
  4675. print1("Cannot find", pretty1(sub), formatNode1(sub))
  4676. end
  4677. if cat1["category"] == "unquote-splice" then
  4678. offset = offset + 1
  4679. append_21_1(out, "_temp = ")
  4680. compileExpression1(nth1(sub, 2), out, state)
  4681. line_21_1(out)
  4682. local pos = sourceRange1(sub["source"])
  4683. append_21_1(out, "for _c = 1, _temp.n do _result[" .. tostring1(i - offset) .. " + _c + _offset] = _temp[_c] end", pos and rangeOfStart1(pos))
  4684. line_21_1(out)
  4685. line_21_1(out, "_offset = _offset + _temp.n")
  4686. else
  4687. append_21_1(out, "_result[" .. tostring1(i - offset) .. " + _offset] = ")
  4688. compileExpression1(sub, out, state)
  4689. line_21_1(out)
  4690. end
  4691. i = i + 1
  4692. end
  4693. line_21_1(out, "_result.n = _offset + " .. tostring1(n1(node) - offset))
  4694. if ret == "" then
  4695. elseif ret then
  4696. append_21_1(out, ret .. "_result")
  4697. else
  4698. line_21_1(out, "return _result")
  4699. endBlock_21_1(out, "end)()")
  4700. end
  4701. elseif catTag == "syntax-quote" then
  4702. if cat["parens"] then
  4703. append_21_1(out, "(")
  4704. end
  4705. compileExpression1(nth1(node, 2), out, state, ret)
  4706. if cat["parens"] then
  4707. append_21_1(out, ")")
  4708. end
  4709. elseif catTag == "unquote" then
  4710. compileExpression1(nth1(node, 2), out, state, ret)
  4711. elseif catTag == "unquote-splice" then
  4712. error1("Should never have explicit unquote-splice", 0)
  4713. elseif catTag == "import" then
  4714. if ret == nil then
  4715. append_21_1(out, "nil")
  4716. elseif ret ~= "" then
  4717. append_21_1(out, ret)
  4718. append_21_1(out, "nil")
  4719. end
  4720. elseif catTag == "call-symbol" then
  4721. local head = car1(node)
  4722. if ret then
  4723. append_21_1(out, ret)
  4724. end
  4725. compileExpression1(head, out, state)
  4726. append_21_1(out, "(")
  4727. local forLimit = n1(node)
  4728. local i = 2
  4729. while i <= forLimit do
  4730. if i > 2 then
  4731. append_21_1(out, ", ")
  4732. end
  4733. compileExpression1(nth1(node, i), out, state)
  4734. i = i + 1
  4735. end
  4736. append_21_1(out, ")")
  4737. elseif catTag == "call-meta" then
  4738. local meta = cat["meta"]
  4739. if meta["syntax-stmt"] then
  4740. elseif ret == "" then
  4741. append_21_1(out, "local _ = ")
  4742. elseif ret then
  4743. append_21_1(out, ret)
  4744. end
  4745. if cat["parens"] then
  4746. append_21_1(out, "(")
  4747. end
  4748. local contents, fold, count, build = meta["syntax"], meta["syntax-fold"], meta["syntax-arity"]
  4749. build = function(start, _eend)
  4750. local forLimit = n1(contents)
  4751. local i = 1
  4752. while i <= forLimit do
  4753. local entry = contents[i]
  4754. if string_3f_1(entry) then
  4755. append_21_1(out, entry)
  4756. elseif fold == "left" and (entry == 1 and start < _eend) then
  4757. build(start, _eend - 1)
  4758. start = _eend
  4759. elseif fold == "right" and (entry == 2 and start < _eend) then
  4760. build(start + 1, _eend)
  4761. else
  4762. compileExpression1(nth1(node, entry + start), out, state)
  4763. end
  4764. i = i + 1
  4765. end
  4766. return nil
  4767. end
  4768. build(1, n1(node) - count)
  4769. if cat["parens"] then
  4770. append_21_1(out, ")")
  4771. end
  4772. if meta["syntax-stmt"] and ret ~= "" then
  4773. line_21_1(out)
  4774. append_21_1(out, ret)
  4775. append_21_1(out, "nil")
  4776. line_21_1(out)
  4777. end
  4778. elseif catTag == "call-recur" then
  4779. if ret == nil then
  4780. print1(pretty1(node), " marked as call-recur for ", ret)
  4781. end
  4782. local args = nth1(cat["recur"]["def"], 2)
  4783. compileBind1(args, 1, node, 2, out, state)
  4784. if ret == "return " then
  4785. compileRecur1(cat["recur"], out, state, "return ")
  4786. else
  4787. compileRecur1(cat["recur"], out, state, ret, cat["recur"])
  4788. end
  4789. local forLimit = n1(args)
  4790. local i = 1
  4791. while i <= forLimit do
  4792. local arg = args[i]
  4793. if not state["var-skip"][arg["var"]] then
  4794. popEscapeVar_21_1(arg["var"], state)
  4795. end
  4796. i = i + 1
  4797. end
  4798. elseif catTag == "call-tail" then
  4799. if ret == nil then
  4800. print1(pretty1(node), " marked as call-tail for ", ret)
  4801. end
  4802. if _ebreak and _ebreak ~= cat["recur"] then
  4803. print1(pretty1(node) .. " Got a different break then defined for.\n Expected: " .. pretty1(cat["recur"]["def"]) .. "\n Got: " .. pretty1(_ebreak["def"]))
  4804. end
  4805. local zipped, mapping, packArgs = zipArgs1(cadr1(cat["recur"]["def"]), 1, node, 2), cat["recur"]["captured"], nil
  4806. local forStart = n1(zipped)
  4807. local i = forStart
  4808. while i >= 1 do
  4809. local zip = nth1(zipped, i)
  4810. local args, vals = car1(zip), cadr1(zip)
  4811. if n1(args) == 1 and (n1(vals) == 1 and (type1((car1(vals))) == "symbol" and (car1(args)["var"] == car1(vals)["var"] and mapping[car1(vals)["var"]] == nil))) then
  4812. removeNth_21_1(zipped, i)
  4813. elseif any1(symVariadic_3f_1, args) then
  4814. packArgs = args
  4815. end
  4816. i = i + -1
  4817. end
  4818. if empty_3f_1(zipped) then
  4819. elseif n1(zipped) == 1 and empty_3f_1(caar1(zipped)) then
  4820. local temp = cadar1(zipped)
  4821. local forLimit = n1(temp)
  4822. local i = 1
  4823. while i <= forLimit do
  4824. compileExpression1(temp[i], out, state, "")
  4825. line_21_1(out)
  4826. i = i + 1
  4827. end
  4828. else
  4829. if packArgs and n1(packArgs) > 1 then
  4830. if n1(zipped) == 1 then
  4831. append_21_1(out, "local ")
  4832. else
  4833. line_21_1(out, "local _p")
  4834. end
  4835. end
  4836. local first, forLimit = true, n1(zipped)
  4837. local i = 1
  4838. while i <= forLimit do
  4839. local zip = zipped[i]
  4840. local args = car1(zip)
  4841. if args == packArgs and n1(args) > 1 then
  4842. if first then
  4843. first = false
  4844. else
  4845. append_21_1(out, ", ")
  4846. end
  4847. append_21_1(out, "_p")
  4848. else
  4849. local temp = car1(zip)
  4850. local forLimit1 = n1(temp)
  4851. local i1 = 1
  4852. while i1 <= forLimit1 do
  4853. local arg = temp[i1]
  4854. if first then
  4855. first = false
  4856. else
  4857. append_21_1(out, ", ")
  4858. end
  4859. append_21_1(out, escapeVar1(mapVar1(mapping, arg["var"]), state))
  4860. i1 = i1 + 1
  4861. end
  4862. end
  4863. i = i + 1
  4864. end
  4865. append_21_1(out, " = ")
  4866. local first, packZip = true, nil
  4867. local forLimit = n1(zipped)
  4868. local i = 1
  4869. while i <= forLimit do
  4870. local zip = zipped[i]
  4871. if first then
  4872. first = false
  4873. else
  4874. append_21_1(out, ", ")
  4875. end
  4876. local args, vals = car1(zip), cadr1(zip)
  4877. if any1(symVariadic_3f_1, args) then
  4878. packZip = zip
  4879. append_21_1(out, "_pack(")
  4880. local forLimit1 = n1(vals)
  4881. local i1 = 1
  4882. while i1 <= forLimit1 do
  4883. if i1 > 1 then
  4884. append_21_1(out, ", ")
  4885. end
  4886. compileExpression1(nth1(vals, i1), out, state)
  4887. i1 = i1 + 1
  4888. end
  4889. append_21_1(out, ")")
  4890. elseif empty_3f_1(vals) then
  4891. append_21_1(out, "nil")
  4892. else
  4893. local forLimit1 = n1(vals)
  4894. local i1 = 1
  4895. while i1 <= forLimit1 do
  4896. if i1 > 1 then
  4897. append_21_1(out, ", ")
  4898. end
  4899. compileExpression1(nth1(vals, i1), out, state)
  4900. i1 = i1 + 1
  4901. end
  4902. end
  4903. i = i + 1
  4904. end
  4905. line_21_1(out)
  4906. if packZip == nil then
  4907. elseif n1(car1(packZip)) == 1 then
  4908. append_21_1(out, escapeVar1(mapVar1(mapping, caar1(packZip)["var"]), state))
  4909. append_21_1(out, ".tag = \"list\"")
  4910. line_21_1(out)
  4911. else
  4912. local args = car1(packZip)
  4913. local varIdx = findIndex1(symVariadic_3f_1, args)
  4914. if varIdx > 1 then
  4915. local forLimit = varIdx - 1
  4916. local i = 1
  4917. while i <= forLimit do
  4918. if i > 1 then
  4919. append_21_1(out, ", ")
  4920. end
  4921. append_21_1(out, escapeVar1(mapVar1(mapping, nth1(args, i)["var"]), state))
  4922. i = i + 1
  4923. end
  4924. append_21_1(out, " = ")
  4925. local forLimit = varIdx - 1
  4926. local i = 1
  4927. while i <= forLimit do
  4928. if i > 1 then
  4929. append_21_1(out, ", ")
  4930. end
  4931. append_21_1(out, format1("_p[%d]", i))
  4932. i = i + 1
  4933. end
  4934. line_21_1(out)
  4935. end
  4936. compileBindVariadic1(out, car1(packZip), cadr1(packZip), state, mapping)
  4937. end
  4938. end
  4939. elseif catTag == "wrap-value" then
  4940. if ret then
  4941. append_21_1(out, ret)
  4942. end
  4943. append_21_1(out, "(")
  4944. compileExpression1(nth1(node, 2), out, state)
  4945. append_21_1(out, ")")
  4946. elseif catTag == "wrap-list" then
  4947. if ret then
  4948. append_21_1(out, ret)
  4949. end
  4950. if cat["parens"] then
  4951. append_21_1(out, "(")
  4952. end
  4953. append_21_1(out, "{tag=\"list\", n=")
  4954. append_21_1(out, tostring1(n1(node) - 1))
  4955. local forLimit = n1(node)
  4956. local i = 2
  4957. while i <= forLimit do
  4958. append_21_1(out, ", ")
  4959. compileExpression1(nth1(node, i), out, state)
  4960. i = i + 1
  4961. end
  4962. append_21_1(out, "}")
  4963. if cat["parens"] then
  4964. append_21_1(out, ")")
  4965. end
  4966. elseif catTag == "call-lambda" then
  4967. local empty = ret == nil
  4968. if empty then
  4969. ret = "return "
  4970. beginBlock_21_1(out, "(function()")
  4971. end
  4972. local head = car1(node)
  4973. local args = nth1(head, 2)
  4974. compileBind1(args, 1, node, 2, out, state)
  4975. compileBlock1(head, out, state, 3, ret, _ebreak)
  4976. local forLimit = n1(args)
  4977. local i = 1
  4978. while i <= forLimit do
  4979. local arg = args[i]
  4980. if not state["var-skip"][arg["var"]] then
  4981. popEscapeVar_21_1(arg["var"], state)
  4982. end
  4983. i = i + 1
  4984. end
  4985. if empty then
  4986. out["indent"] = out["indent"] - 1
  4987. append_21_1(out, "end)()")
  4988. end
  4989. elseif catTag == "call" then
  4990. if ret then
  4991. append_21_1(out, ret)
  4992. end
  4993. compileExpression1(car1(node), out, state)
  4994. append_21_1(out, "(")
  4995. local forLimit = n1(node)
  4996. local i = 2
  4997. while i <= forLimit do
  4998. if i > 2 then
  4999. append_21_1(out, ", ")
  5000. end
  5001. compileExpression1(nth1(node, i), out, state)
  5002. i = i + 1
  5003. end
  5004. append_21_1(out, ")")
  5005. else
  5006. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(catTag) .. ", but none matched.\n" .. " Tried: `\"void\"`\n Tried: `\"const\"`\n Tried: `\"lambda\"`\n Tried: `\"cond\"`\n Tried: `\"unless\"`\n Tried: `\"not\"`\n Tried: `\"or\"`\n Tried: `\"or-lambda\"`\n Tried: `\"and\"`\n Tried: `\"and-lambda\"`\n Tried: `\"set!\"`\n Tried: `\"struct-literal\"`\n Tried: `\"define\"`\n Tried: `\"define-native\"`\n Tried: `\"quote\"`\n Tried: `\"quote-const\"`\n Tried: `\"quote-list\"`\n Tried: `\"quote-splice\"`\n Tried: `\"syntax-quote\"`\n Tried: `\"unquote\"`\n Tried: `\"unquote-splice\"`\n Tried: `\"import\"`\n Tried: `\"call-symbol\"`\n Tried: `\"call-meta\"`\n Tried: `\"call-recur\"`\n Tried: `\"call-tail\"`\n Tried: `\"wrap-value\"`\n Tried: `\"wrap-list\"`\n Tried: `\"call-lambda\"`\n Tried: `\"call\"`")
  5007. end
  5008. return popNode_21_1(out, node)
  5009. end
  5010. compileBind1 = function(args, argsStart, vals, valsStart, out, state)
  5011. local zipped = zipArgs1(args, argsStart, vals, valsStart)
  5012. local zippedN, zippedI, skip, catLookup = n1(zipped), 1, state["var-skip"], state["cat-lookup"]
  5013. while zippedI <= zippedN do
  5014. local zip = nth1(zipped, zippedI)
  5015. local args1, vals1 = car1(zip), cadr1(zip)
  5016. if empty_3f_1(args1) then
  5017. local forLimit = n1(vals1)
  5018. local i = 1
  5019. while i <= forLimit do
  5020. compileExpression1(vals1[i], out, state, "")
  5021. line_21_1(out)
  5022. i = i + 1
  5023. end
  5024. elseif car1(args1)["var"]["is-variadic"] or n1(args1) > 1 and any1(symVariadic_3f_1, args1) then
  5025. if n1(args1) > 1 then
  5026. append_21_1(out, "local _p = _pack(")
  5027. local forLimit = n1(vals1)
  5028. local i = 1
  5029. while i <= forLimit do
  5030. if i > 1 then
  5031. append_21_1(out, ", ")
  5032. end
  5033. compileExpression1(nth1(vals1, i), out, state)
  5034. i = i + 1
  5035. end
  5036. append_21_1(out, ")")
  5037. line_21_1(out)
  5038. append_21_1(out, "local ")
  5039. local forLimit = n1(args1)
  5040. local i = 1
  5041. while i <= forLimit do
  5042. if i > 1 then
  5043. append_21_1(out, ", ")
  5044. end
  5045. append_21_1(out, pushEscapeVar_21_1(nth1(args1, i)["var"], state))
  5046. i = i + 1
  5047. end
  5048. local varIdx = findIndex1(symVariadic_3f_1, args1)
  5049. if varIdx > 1 then
  5050. append_21_1(out, " = ")
  5051. local forLimit = varIdx - 1
  5052. local i = 1
  5053. while i <= forLimit do
  5054. if i > 1 then
  5055. append_21_1(out, ", ")
  5056. end
  5057. append_21_1(out, format1("_p[%d]", i))
  5058. i = i + 1
  5059. end
  5060. end
  5061. line_21_1(out)
  5062. compileBindVariadic1(out, args1, vals1, state)
  5063. elseif empty_3f_1(vals1) or singleReturn_3f_1(last1(vals1)) then
  5064. append_21_1(out, "local ")
  5065. append_21_1(out, pushEscapeVar_21_1(car1(args1)["var"], state))
  5066. append_21_1(out, " = {tag=\"list\", n=")
  5067. append_21_1(out, tostring1(n1(vals1)))
  5068. local forLimit = n1(vals1)
  5069. local i = 1
  5070. while i <= forLimit do
  5071. append_21_1(out, ", ")
  5072. compileExpression1(nth1(vals1, i), out, state)
  5073. i = i + 1
  5074. end
  5075. append_21_1(out, "}")
  5076. line_21_1(out)
  5077. else
  5078. local name = pushEscapeVar_21_1(car1(args1)["var"], state)
  5079. append_21_1(out, "local ")
  5080. append_21_1(out, name)
  5081. append_21_1(out, " = _pack(")
  5082. local forLimit = n1(vals1)
  5083. local i = 1
  5084. while i <= forLimit do
  5085. if i > 1 then
  5086. append_21_1(out, ", ")
  5087. end
  5088. compileExpression1(nth1(vals1, i), out, state)
  5089. i = i + 1
  5090. end
  5091. append_21_1(out, ") ")
  5092. append_21_1(out, name)
  5093. append_21_1(out, ".tag = \"list\"")
  5094. line_21_1(out)
  5095. end
  5096. elseif n1(args1) == 1 and skip[car1(args1)["var"]] then
  5097. else
  5098. local zippedLim, working = zippedI, true
  5099. while working and zippedLim <= zippedN do
  5100. local zip1 = nth1(zipped, zippedLim)
  5101. local args2, vals2 = car1(zip1), cadr1(zip1)
  5102. if empty_3f_1(args2) then
  5103. working = false
  5104. elseif car1(args2)["var"]["is-variadic"] or n1(args2) > 1 and any1(symVariadic_3f_1, args2) then
  5105. working = false
  5106. elseif n1(vals2) == 1 and catLookup[car1(vals2)]["stmt"] then
  5107. working = false
  5108. else
  5109. zippedLim = zippedLim + 1
  5110. end
  5111. end
  5112. if zippedLim == zippedI then
  5113. local esc
  5114. if n1(args1) == 1 then
  5115. esc = pushEscapeVar_21_1(car1(args1)["var"], state)
  5116. else
  5117. local escs = {tag="list", n=0}
  5118. local forLimit = n1(args1)
  5119. local i = 1
  5120. while i <= forLimit do
  5121. push_21_1(escs, pushEscapeVar_21_1(args1[i]["var"], state))
  5122. i = i + 1
  5123. end
  5124. esc = concat2(escs, ", ")
  5125. end
  5126. if not (n1(vals1) == 1 and catLookup[car1(vals1)]["stmt"]) then
  5127. error1("Expected statement, got something " .. pretty1(zip))
  5128. end
  5129. line_21_1(out, "local " .. esc)
  5130. compileExpression1(car1(vals1), out, state, esc .. " = ")
  5131. line_21_1(out)
  5132. else
  5133. local hasVal = false
  5134. append_21_1(out, "local ")
  5135. local first, forStart, forLimit = true, zippedI, zippedLim - 1
  5136. local i = forStart
  5137. while i <= forLimit do
  5138. local zip1 = nth1(zipped, i)
  5139. local args2 = car1(zip1)
  5140. if not empty_3f_1((cadr1(zip1))) then
  5141. hasVal = true
  5142. end
  5143. if not (n1(args2) == 1 and skip[car1(args2)["var"]]) then
  5144. local forLimit1 = n1(args2)
  5145. local i1 = 1
  5146. while i1 <= forLimit1 do
  5147. local arg = args2[i1]
  5148. if first then
  5149. first = false
  5150. else
  5151. append_21_1(out, ", ")
  5152. end
  5153. local var = arg["var"]
  5154. if skip[var] then
  5155. append_21_1(out, "_")
  5156. else
  5157. append_21_1(out, pushEscapeVar_21_1(var, state))
  5158. end
  5159. i1 = i1 + 1
  5160. end
  5161. end
  5162. i = i + 1
  5163. end
  5164. if hasVal then
  5165. append_21_1(out, " = ")
  5166. local first, forStart, forLimit = true, zippedI, zippedLim - 1
  5167. local i = forStart
  5168. while i <= forLimit do
  5169. local zip1 = nth1(zipped, i)
  5170. local args2, vals2 = car1(zip1), cadr1(zip1)
  5171. if not (n1(args2) == 1 and skip[car1(args2)["var"]]) then
  5172. local forLimit1 = n1(vals2)
  5173. local i1 = 1
  5174. while i1 <= forLimit1 do
  5175. local val = vals2[i1]
  5176. if first then
  5177. first = false
  5178. else
  5179. append_21_1(out, ", ")
  5180. end
  5181. compileExpression1(val, out, state)
  5182. i1 = i1 + 1
  5183. end
  5184. end
  5185. i = i + 1
  5186. end
  5187. end
  5188. line_21_1(out)
  5189. zippedI = zippedLim - 1
  5190. end
  5191. end
  5192. zippedI = zippedI + 1
  5193. end
  5194. return nil
  5195. end
  5196. compileBindVariadic1 = function(out, args, vals, state, mapping)
  5197. local varIdx = findIndex1(symVariadic_3f_1, args)
  5198. local varEsc, nargs = escapeVar1(mapVar1(mapping, nth1(args, varIdx)["var"]), state), n1(args)
  5199. line_21_1(out, "local _n = _p.n")
  5200. beginBlock_21_1(out, format1("if _n > %d then", nargs - 1))
  5201. line_21_1(out, format1("%s = {tag=\"list\", n=_n-%d}", varEsc, nargs - 1))
  5202. line_21_1(out, format1("for i=%d, _n-%d do %s[i-%d]=_p[i] end", varIdx, nargs - varIdx, varEsc, varIdx - 1))
  5203. if varIdx < nargs then
  5204. local forStart = varIdx + 1
  5205. local i = forStart
  5206. while i <= nargs do
  5207. if i > varIdx + 1 then
  5208. append_21_1(out, ", ")
  5209. end
  5210. append_21_1(out, escapeVar1(mapVar1(mapping, nth1(args, i)["var"]), state))
  5211. i = i + 1
  5212. end
  5213. append_21_1(out, " = ")
  5214. local forStart = varIdx + 1
  5215. local i = forStart
  5216. while i <= nargs do
  5217. if i > varIdx + 1 then
  5218. append_21_1(out, ", ")
  5219. end
  5220. append_21_1(out, format1("_p[_n-%d]", nargs - i))
  5221. i = i + 1
  5222. end
  5223. line_21_1(out)
  5224. end
  5225. nextBlock_21_1(out, "else")
  5226. line_21_1(out, format1("%s = {tag=\"list\", n=0}", varEsc))
  5227. if varIdx < nargs then
  5228. local forStart = varIdx + 1
  5229. local i = forStart
  5230. while i <= nargs do
  5231. if i > varIdx + 1 then
  5232. append_21_1(out, ", ")
  5233. end
  5234. append_21_1(out, escapeVar1(mapVar1(mapping, nth1(args, i)["var"]), state))
  5235. i = i + 1
  5236. end
  5237. append_21_1(out, " = ")
  5238. local forStart = varIdx + 1
  5239. local i = forStart
  5240. while i <= nargs do
  5241. if i > varIdx + 1 then
  5242. append_21_1(out, ", ")
  5243. end
  5244. append_21_1(out, format1("_p[%d]", i - 1))
  5245. i = i + 1
  5246. end
  5247. line_21_1(out)
  5248. end
  5249. return endBlock_21_1(out, "end")
  5250. end
  5251. compileRecur1 = function(recur, out, state, ret, _ebreak)
  5252. local temp = recur["category"]
  5253. if temp == "while" then
  5254. local node = nth1(recur["def"], 3)
  5255. append_21_1(out, "while ")
  5256. compileExpression1(car1(nth1(node, 2)), out, state)
  5257. beginBlock_21_1(out, " do")
  5258. compileRecurPush1(recur, out, state)
  5259. compileBlock1(nth1(node, 2), out, state, 2, ret, _ebreak)
  5260. compileRecurPop1(recur, state)
  5261. endBlock_21_1(out, "end")
  5262. return compileBlock1(nth1(node, 3), out, state, 2, ret)
  5263. elseif temp == "while-not" then
  5264. local node = nth1(recur["def"], 3)
  5265. append_21_1(out, "while not (")
  5266. compileExpression1(car1(nth1(node, 2)), out, state)
  5267. beginBlock_21_1(out, ") do")
  5268. compileRecurPush1(recur, out, state)
  5269. compileBlock1(nth1(node, 3), out, state, 2, ret, _ebreak)
  5270. compileRecurPop1(recur, state)
  5271. endBlock_21_1(out, "end")
  5272. return compileBlock1(nth1(node, 2), out, state, 2, ret)
  5273. elseif temp == "forever" then
  5274. beginBlock_21_1(out, "while true do")
  5275. compileRecurPush1(recur, out, state)
  5276. compileBlock1(recur["def"], out, state, 3, ret, _ebreak)
  5277. compileRecurPop1(recur, state)
  5278. return endBlock_21_1(out, "end")
  5279. else
  5280. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"while\"`\n Tried: `\"while-not\"`\n Tried: `\"forever\"`")
  5281. end
  5282. end
  5283. compileRecurPush1 = function(recur, out, state)
  5284. local mapping = recur["captured"]
  5285. if (not next1(mapping)) then
  5286. return nil
  5287. else
  5288. append_21_1(out, "local ")
  5289. local first = true
  5290. local temp, to = next1(mapping)
  5291. while temp ~= nil do
  5292. if first then
  5293. first = false
  5294. else
  5295. append_21_1(out, ", ")
  5296. end
  5297. renameEscapeVar_21_1(temp, to, state)
  5298. append_21_1(out, pushEscapeVar_21_1(temp, state))
  5299. temp, to = next1(mapping, temp)
  5300. end
  5301. append_21_1(out, " = ")
  5302. local first = true
  5303. local temp, to = next1(mapping)
  5304. while temp ~= nil do
  5305. if first then
  5306. first = false
  5307. else
  5308. append_21_1(out, ", ")
  5309. end
  5310. append_21_1(out, escapeVar1(to, state))
  5311. temp, to = next1(mapping, temp)
  5312. end
  5313. return line_21_1(out)
  5314. end
  5315. end
  5316. compileRecurPop1 = function(recur, state)
  5317. local temp = recur["captured"]
  5318. local temp1, to = next1(temp)
  5319. while temp1 ~= nil do
  5320. popEscapeVar_21_1(temp1, state)
  5321. renameEscapeVar_21_1(to, temp1, state)
  5322. temp1, to = next1(temp, temp1)
  5323. end
  5324. return nil
  5325. end
  5326. mapVar1 = function(mapping, var)
  5327. return mapping and mapping[var] or var
  5328. end
  5329. compileBlock1 = function(nodes, out, state, start, ret, _ebreak)
  5330. local len = n1(nodes)
  5331. local forLimit = len - 1
  5332. local i = start
  5333. while i <= forLimit do
  5334. compileExpression1(nth1(nodes, i), out, state, "")
  5335. line_21_1(out)
  5336. i = i + 1
  5337. end
  5338. if len >= start then
  5339. local node = nth1(nodes, len)
  5340. compileExpression1(node, out, state, ret, _ebreak)
  5341. line_21_1(out)
  5342. if _ebreak and not breakCategories1[state["cat-lookup"][node]["category"]] then
  5343. return line_21_1(out, "break")
  5344. else
  5345. return nil
  5346. end
  5347. else
  5348. if ret and ret ~= "" then
  5349. append_21_1(out, ret)
  5350. line_21_1(out, "nil")
  5351. end
  5352. if _ebreak then
  5353. return line_21_1(out, "break")
  5354. else
  5355. return nil
  5356. end
  5357. end
  5358. end
  5359. prelude1 = function(out)
  5360. line_21_1(out, "if not table.pack then table.pack = function(...) return { n = select(\"#\", ...), ... } end end")
  5361. line_21_1(out, "if not table.unpack then table.unpack = unpack end")
  5362. line_21_1(out, "local load = load if _VERSION:find(\"5.1\") then load = function(x, n, _, env) local f, e = loadstring(x, n) if not f then return f, e end if env then setfenv(f, env) end return f end end")
  5363. return line_21_1(out, "local _select, _unpack, _pack, _error = select, table.unpack, table.pack, error")
  5364. end
  5365. expression1 = function(node, out, state, ret)
  5366. local passState = createPassState1(state)
  5367. runPass1(letrecNode1, state, nil, node, passState)
  5368. runPass1(categoriseNode1, state, nil, node, passState, ret ~= nil)
  5369. return compileExpression1(node, out, passState, ret)
  5370. end
  5371. block1 = function(nodes, out, state, start, ret)
  5372. local passState = createPassState1(state)
  5373. runPass1(letrecNodes1, state, nil, nodes, passState)
  5374. runPass1(categoriseNodes1, state, nil, nodes, passState)
  5375. return compileBlock1(nodes, out, passState, start, ret)
  5376. end
  5377. create3 = function(scope, compiler)
  5378. if type1(scope) ~= "scope" then
  5379. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  5380. end
  5381. if compiler == nil then
  5382. error1("compiler cannot be nil")
  5383. end
  5384. return {tag="resolve-state", scope=scope, compiler=compiler, required={tag="list", n=0}, ["required-set"]={}, stage="parsed", var=nil, node=nil, value=nil}
  5385. end
  5386. rsNode1 = function(resolveState)
  5387. return resolveState["node"]
  5388. end
  5389. require_21_1 = function(state, var, user)
  5390. if state["stage"] ~= "parsed" then
  5391. error1("Cannot add requirement when in stage " .. state["stage"])
  5392. end
  5393. if not var then
  5394. error1("var is nil")
  5395. end
  5396. if not user then
  5397. error1("user is nil")
  5398. end
  5399. if var["scope"]["kind"] == "top-level" then
  5400. local other = state["compiler"]["states"][var]
  5401. if other and not state["required-set"][other] then
  5402. state["required-set"][other] = user
  5403. push_21_1(state["required"], other)
  5404. end
  5405. return other
  5406. else
  5407. return nil
  5408. end
  5409. end
  5410. define_21_1 = function(state, var)
  5411. if state["stage"] ~= "parsed" then
  5412. error1("Cannot add definition when in stage " .. state["stage"])
  5413. end
  5414. if var["scope"] ~= state["scope"] then
  5415. error1("Defining variable in different scope")
  5416. end
  5417. if state["var"] then
  5418. error1("Cannot redeclare variable for given state")
  5419. end
  5420. state["var"] = var
  5421. state["compiler"]["states"][var] = state
  5422. state["compiler"]["variables"][tostring1(var)] = var
  5423. return nil
  5424. end
  5425. built_21_1 = function(state, node)
  5426. if not node then
  5427. error1("node cannot be nil")
  5428. end
  5429. if state["stage"] ~= "parsed" then
  5430. error1("Cannot transition from " .. state["stage"] .. " to built")
  5431. end
  5432. if node["def-var"] ~= state["var"] then
  5433. error1("Variables are different")
  5434. end
  5435. state["node"] = node
  5436. state["stage"] = "built"
  5437. return nil
  5438. end
  5439. executed_21_1 = function(state, value)
  5440. if state["stage"] ~= "built" then
  5441. error1("Cannot transition from " .. state["stage"] .. " to executed")
  5442. end
  5443. state["value"] = value
  5444. state["stage"] = "executed"
  5445. return nil
  5446. end
  5447. get_21_1 = function(state)
  5448. if state["stage"] == "executed" then
  5449. return state["value"]
  5450. else
  5451. local required, requiredSet = {tag="list", n=0}, {}
  5452. local visit
  5453. visit = function(state1, stack, stackHash)
  5454. local idx = stackHash[state1]
  5455. if idx then
  5456. if state1["var"]["kind"] == "macro" then
  5457. push_21_1(stack, state1)
  5458. local states, nodes, firstNode = {tag="list", n=0}, {tag="list", n=0}, nil
  5459. local forLimit = n1(stack)
  5460. local i = idx
  5461. while i <= forLimit do
  5462. local current, previous = nth1(stack, i), nth1(stack, i - 1)
  5463. push_21_1(states, current["var"]["name"])
  5464. if previous then
  5465. local user = previous["required-set"][current]
  5466. if not firstNode then
  5467. firstNode = user
  5468. end
  5469. push_21_1(nodes, sourceRange1(user["source"]))
  5470. push_21_1(nodes, current["var"]["name"] .. " used in " .. previous["var"]["name"])
  5471. end
  5472. i = i + 1
  5473. end
  5474. return doNodeError_21_1(state1["compiler"]["log"], "Loop in macros " .. concat2(states, " -> "), firstNode["source"], nil, splice1(nodes))
  5475. else
  5476. return nil
  5477. end
  5478. elseif state1["stage"] == "executed" then
  5479. return nil
  5480. else
  5481. push_21_1(stack, state1)
  5482. stackHash[state1] = n1(stack)
  5483. if not requiredSet[state1] then
  5484. requiredSet[state1] = true
  5485. push_21_1(required, state1)
  5486. end
  5487. local visited = {}
  5488. local temp = state1["required"]
  5489. local forLimit = n1(temp)
  5490. local i = 1
  5491. while i <= forLimit do
  5492. local inner = temp[i]
  5493. visited[inner] = true
  5494. visit(inner, stack, stackHash)
  5495. i = i + 1
  5496. end
  5497. if state1["stage"] == "parsed" then
  5498. yield1({tag="build", state=state1})
  5499. end
  5500. local temp = state1["required"]
  5501. local forLimit = n1(temp)
  5502. local i = 1
  5503. while i <= forLimit do
  5504. local inner = temp[i]
  5505. if not visited[inner] then
  5506. visit(inner, stack, stackHash)
  5507. end
  5508. i = i + 1
  5509. end
  5510. popLast_21_1(stack)
  5511. stackHash[state1] = nil
  5512. return nil
  5513. end
  5514. end
  5515. visit(state, {tag="list", n=0}, {})
  5516. yield1({tag="execute", states=required})
  5517. return state["value"]
  5518. end
  5519. end
  5520. name1 = function(state)
  5521. if state["var"] then
  5522. return "macro " .. quoted1(state["var"]["name"])
  5523. else
  5524. return "unquote"
  5525. end
  5526. end
  5527. createState1 = function()
  5528. return {timer={callback=function()
  5529. return nil
  5530. end, timers={}}, count=0, mappings={}, ["var-cache"]={}, ["var-lookup"]={}}
  5531. end
  5532. file1 = function(compiler, shebang)
  5533. local state, out = createState1(), {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  5534. if shebang then
  5535. line_21_1(out, "#!/usr/bin/env " .. shebang)
  5536. end
  5537. state["trace"] = true
  5538. prelude1(out)
  5539. line_21_1(out, "local _libs = {}")
  5540. local temp = compiler["libs"]["loaded"]
  5541. local forLimit = n1(temp)
  5542. local i = 1
  5543. while i <= forLimit do
  5544. local lib = temp[i]
  5545. local prefix, native = quoted1(lib["unique-name"] .. "/"), lib["lua-contents"]
  5546. if native then
  5547. beginBlock_21_1(out, "local _temp = (function()")
  5548. local temp1 = split1(native, "\n")
  5549. local forLimit1 = n1(temp1)
  5550. local i1 = 1
  5551. while i1 <= forLimit1 do
  5552. local line = temp1[i1]
  5553. if line ~= "" then
  5554. line_21_1(out, line)
  5555. end
  5556. i1 = i1 + 1
  5557. end
  5558. endBlock_21_1(out, "end)()")
  5559. line_21_1(out, "for k, v in pairs(_temp) do _libs[" .. prefix .. ".. k] = v end")
  5560. end
  5561. i = i + 1
  5562. end
  5563. local count = 0
  5564. local temp = compiler["out"]
  5565. local forLimit = n1(temp)
  5566. local i = 1
  5567. while i <= forLimit do
  5568. if temp[i]["def-var"] then
  5569. count = count + 1
  5570. end
  5571. i = i + 1
  5572. end
  5573. local temp = compiler["out"]
  5574. local forLimit = n1(temp)
  5575. local i = 1
  5576. while i <= forLimit do
  5577. local var = temp[i]["def-var"]
  5578. if var then
  5579. pushEscapeVar_21_1(var, state, true)
  5580. end
  5581. i = i + 1
  5582. end
  5583. if count == 0 then
  5584. elseif count <= 100 then
  5585. append_21_1(out, "local ")
  5586. local first, temp = true, compiler["out"]
  5587. local forLimit = n1(temp)
  5588. local i = 1
  5589. while i <= forLimit do
  5590. local var = temp[i]["def-var"]
  5591. if var then
  5592. if first then
  5593. first = false
  5594. else
  5595. append_21_1(out, ", ")
  5596. end
  5597. append_21_1(out, escapeVar1(var, state))
  5598. end
  5599. i = i + 1
  5600. end
  5601. line_21_1(out)
  5602. else
  5603. local counts, vars = {}, {tag="list", n=0}
  5604. local temp = compiler["out"]
  5605. local forLimit = n1(temp)
  5606. local i = 1
  5607. while i <= forLimit do
  5608. local var = temp[i]["def-var"]
  5609. if var then
  5610. counts[var] = 0
  5611. push_21_1(vars, var)
  5612. end
  5613. i = i + 1
  5614. end
  5615. visitBlock1(compiler["out"], 1, function(x)
  5616. if type1(x) == "symbol" then
  5617. local var = x["var"]
  5618. local count1 = counts[var]
  5619. if count1 then
  5620. counts[var] = count1 + 1
  5621. return nil
  5622. else
  5623. return nil
  5624. end
  5625. else
  5626. return nil
  5627. end
  5628. end)
  5629. sort1(vars, function(x, y)
  5630. return counts[x] > counts[y]
  5631. end)
  5632. append_21_1(out, "local ")
  5633. local mainVars = map2(function(temp)
  5634. return escapeVar1(temp, state)
  5635. end, slice1(vars, 1, min1(100, n1(vars))))
  5636. sort1(mainVars, nil)
  5637. append_21_1(out, concat2(mainVars, ", "))
  5638. line_21_1(out)
  5639. line_21_1(out, "local _ENV = setmetatable({}, {__index=_ENV or (getfenv and getfenv()) or _G}) if setfenv then setfenv(0, _ENV) end")
  5640. end
  5641. block1(compiler["out"], out, state, 1, "return ")
  5642. return out
  5643. end
  5644. executeStates1 = function(backState, states, global)
  5645. local stateList, nameList, exportList, escapeList, localList = {tag="list", n=0}, {tag="list", n=0}, {tag="list", n=0}, {tag="list", n=0}, {tag="list", n=0}
  5646. local forStart = n1(states)
  5647. local i = forStart
  5648. while i >= 1 do
  5649. local state = nth1(states, i)
  5650. if not (state["stage"] == "executed") then
  5651. if not state["node"] then
  5652. error1(demandFailure1("State is in " .. state["stage"] .. " instead", "(state/rs-node state)"))
  5653. end
  5654. local var = state["var"] or tempVar1("temp", state["node"])
  5655. local escaped, name = pushEscapeVar_21_1(var, backState, true), var["name"]
  5656. push_21_1(stateList, state)
  5657. push_21_1(exportList, escaped .. " = " .. escaped)
  5658. push_21_1(nameList, name)
  5659. push_21_1(escapeList, escaped)
  5660. if not var or var["const"] then
  5661. push_21_1(localList, escaped)
  5662. end
  5663. end
  5664. i = i + -1
  5665. end
  5666. if empty_3f_1(stateList) then
  5667. return nil
  5668. else
  5669. local out, id, name = {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}, backState["count"], concat2(nameList, ",")
  5670. backState["count"] = id + 1
  5671. if n1(name) > 20 then
  5672. name = sub1(name, 1, 17) .. "..."
  5673. end
  5674. name = "compile#" .. id .. "{" .. name .. "}"
  5675. prelude1(out)
  5676. if not empty_3f_1(localList) then
  5677. line_21_1(out, "local " .. concat2(localList, ", "))
  5678. end
  5679. local forLimit = n1(stateList)
  5680. local i = 1
  5681. while i <= forLimit do
  5682. local state = nth1(stateList, i)
  5683. expression1(state["node"], out, backState, (function()
  5684. if state["var"] then
  5685. return ""
  5686. else
  5687. return nth1(escapeList, i) .. " = "
  5688. end
  5689. end)())
  5690. line_21_1(out)
  5691. i = i + 1
  5692. end
  5693. line_21_1(out, "return { " .. concat2(exportList, ", ") .. "}")
  5694. local str = concat2(out["out"])
  5695. backState["mappings"][name] = generateMappings1(out["lines"])
  5696. local temp = list1(load1(str, "=" .. name, "t", global))
  5697. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == nil and true))) then
  5698. local msg, buffer, lines = nth1(temp, 2), {tag="list", n=0}, split1(str, "\n")
  5699. local fmt = "%" .. n1(tostring1(n1(lines))) .. "d | %s"
  5700. local forLimit = n1(lines)
  5701. local i = 1
  5702. while i <= forLimit do
  5703. push_21_1(buffer, sprintf1(fmt, i, nth1(lines, i)))
  5704. i = i + 1
  5705. end
  5706. return error1(msg .. ":\n" .. concat2(buffer, "\n"), 0)
  5707. elseif type1(temp) == "list" and (n1(temp) >= 1 and (n1(temp) <= 1 and true)) then
  5708. local temp1 = list1(xpcall1(nth1(temp, 1), traceback2))
  5709. if type1(temp1) == "list" and (n1(temp1) >= 2 and (n1(temp1) <= 2 and (nth1(temp1, 1) == false and true))) then
  5710. local msg = nth1(temp1, 2)
  5711. return error1(remapTraceback1(backState["mappings"], msg), 0)
  5712. elseif type1(temp1) == "list" and (n1(temp1) >= 2 and (n1(temp1) <= 2 and (nth1(temp1, 1) == true and true))) then
  5713. local tbl, forLimit = nth1(temp1, 2), n1(stateList)
  5714. local i = 1
  5715. while i <= forLimit do
  5716. local state, escaped = nth1(stateList, i), nth1(escapeList, i)
  5717. local res = tbl[escaped]
  5718. executed_21_1(state, res)
  5719. if state["var"] then
  5720. global[escaped] = res
  5721. end
  5722. i = i + 1
  5723. end
  5724. return nil
  5725. else
  5726. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp1) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true ?tbl)`")
  5727. end
  5728. else
  5729. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(nil ?msg)`\n Tried: `(?fun)`")
  5730. end
  5731. end
  5732. end
  5733. getNative1 = function(var)
  5734. local native = varNative1(var)
  5735. if not native["has-value"] then
  5736. local out = {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  5737. prelude1(out)
  5738. append_21_1(out, "return ")
  5739. compileNative1(out, var, native)
  5740. native["has-value"] = true
  5741. local fun = load1(concat2(out["out"]), "=" .. var["name"])
  5742. if fun then
  5743. local ok, res = pcall1(fun)
  5744. if ok then
  5745. native["value"] = res
  5746. end
  5747. end
  5748. end
  5749. return native["value"]
  5750. end
  5751. errorPositions_21_1 = function(log, node, message, extra)
  5752. return doNodeError_21_1(log, message, node["source"], extra, sourceRange1(node["source"]), "")
  5753. end
  5754. expectType_21_1 = function(log, node, parent, expectedType, name)
  5755. if type1(node) ~= expectedType then
  5756. return errorPositions_21_1(log, node or parent, "Expected " .. (name or expectedType) .. ", got " .. (function()
  5757. if node then
  5758. return type1(node)
  5759. else
  5760. return "nothing"
  5761. end
  5762. end)())
  5763. else
  5764. return nil
  5765. end
  5766. end
  5767. expect_21_1 = function(log, node, parent, name)
  5768. if node then
  5769. return nil
  5770. else
  5771. return errorPositions_21_1(log, parent, "Expected " .. name .. ", got nothing")
  5772. end
  5773. end
  5774. maxLength_21_1 = function(log, node, len, name)
  5775. if n1(node) > len then
  5776. return errorPositions_21_1(log, nth1(node, len + 1), "Unexpected node in '" .. name .. "' (expected " .. len .. " values, got " .. n1(node) .. ")")
  5777. else
  5778. return nil
  5779. end
  5780. end
  5781. handleMetadata1 = function(log, node, var, start, finish)
  5782. local i = start
  5783. while i <= finish do
  5784. local child = nth1(node, i)
  5785. local temp = type1(child)
  5786. if temp == "nil" then
  5787. expect_21_1(log, child, node, "variable metadata")
  5788. elseif temp == "string" then
  5789. if var["doc"] then
  5790. errorPositions_21_1(log, child, "Multiple doc strings in definition")
  5791. end
  5792. var["doc"] = (child["value"])
  5793. elseif temp == "key" then
  5794. local temp1 = child["value"]
  5795. if temp1 == "hidden" then
  5796. var["scope"]["exported"][var["name"]] = nil
  5797. elseif temp1 == "deprecated" then
  5798. if var["deprecated"] then
  5799. errorPositions_21_1(log, child, "This definition is already deprecated")
  5800. end
  5801. local message = true
  5802. if i < finish and string_3f_1(nth1(node, i + 1)) then
  5803. message = nth1(node, i + 1)["value"]
  5804. i = i + 1
  5805. end
  5806. var["deprecated"] = message
  5807. elseif temp1 == "mutable" then
  5808. if var["kind"] ~= "defined" then
  5809. errorPositions_21_1(log, child, "Can only set conventional definitions as mutable")
  5810. end
  5811. if not var["const"] then
  5812. errorPositions_21_1(log, child, "This definition is already mutable")
  5813. end
  5814. var["const"] = false
  5815. elseif temp1 == "intrinsic" then
  5816. expectType_21_1(log, nth1(node, i + 1), node, "symbol", "intrinsic")
  5817. if var["intrinsic"] then
  5818. errorPositions_21_1(log, child, "Multiple intrinsics set")
  5819. end
  5820. var["intrinsic"] = (nth1(node, i + 1)["contents"])
  5821. i = i + 1
  5822. elseif temp1 == "pure" then
  5823. if var["kind"] ~= "native" then
  5824. errorPositions_21_1(log, child, "Can only set native definitions as pure")
  5825. end
  5826. local native = varNative1(var)
  5827. if native["pure"] then
  5828. errorPositions_21_1(log, child, "This definition is already pure")
  5829. end
  5830. native["pure"] = true
  5831. elseif temp1 == "signature" then
  5832. if var["kind"] ~= "native" then
  5833. errorPositions_21_1(log, child, "Can only set signature for native definitions")
  5834. end
  5835. local native, signature = varNative1(var), nth1(node, i + 1)
  5836. expectType_21_1(log, signature, node, "list", "signature")
  5837. local forLimit = n1(signature)
  5838. local i1 = 1
  5839. while i1 <= forLimit do
  5840. expectType_21_1(log, signature[i1], signature, "symbol", "argument")
  5841. i1 = i1 + 1
  5842. end
  5843. if native["signature"] then
  5844. errorPositions_21_1(log, child, "multiple signatures set")
  5845. end
  5846. native["signature"] = signature
  5847. i = i + 1
  5848. elseif temp1 == "bind-to" then
  5849. if var["kind"] ~= "native" then
  5850. errorPositions_21_1(log, child, "Can only bind native definitions")
  5851. end
  5852. local native = varNative1(var)
  5853. expectType_21_1(log, nth1(node, i + 1), node, "string", "bind expression")
  5854. if native["bind-to"] then
  5855. errorPositions_21_1(log, child, "Multiple bind expressions set")
  5856. end
  5857. native["bind-to"] = (nth1(node, i + 1)["value"])
  5858. i = i + 1
  5859. elseif temp1 == "syntax" then
  5860. if var["kind"] ~= "native" then
  5861. errorPositions_21_1(log, child, "Can only set syntax for native definitions")
  5862. end
  5863. local native, syntax = varNative1(var), nth1(node, i + 1)
  5864. expect_21_1(log, syntax, node, "syntax")
  5865. if native["syntax"] then
  5866. errorPositions_21_1(log, child, "Multiple syntaxes set")
  5867. end
  5868. local temp2 = type1(syntax)
  5869. if temp2 == "string" then
  5870. local syn, arity = parseTemplate1(syntax["value"])
  5871. native["syntax"] = syn
  5872. native["syntax-arity"] = arity
  5873. elseif temp2 == "list" then
  5874. expect_21_1(log, car1(syntax), syntax, "syntax element")
  5875. local syn, arity = {tag="list", n=0}, 0
  5876. local forLimit = n1(syntax)
  5877. local i1 = 1
  5878. while i1 <= forLimit do
  5879. local child2 = syntax[i1]
  5880. local temp3 = type1(child2)
  5881. if temp3 == "string" then
  5882. push_21_1(syn, child2["value"])
  5883. elseif temp3 == "number" then
  5884. local val = child2["value"]
  5885. if val > arity then
  5886. arity = val
  5887. end
  5888. push_21_1(syn, val)
  5889. else
  5890. errorPositions_21_1(log, child2, formatOutput_21_1(nil, "Expected syntax element, got " .. display1((function()
  5891. if temp3 == "nil" then
  5892. return "nothing"
  5893. else
  5894. return temp3
  5895. end
  5896. end)())))
  5897. end
  5898. i1 = i1 + 1
  5899. end
  5900. native["syntax"] = syn
  5901. native["syntax-arity"] = arity
  5902. else
  5903. errorPositions_21_1(log, child, formatOutput_21_1(nil, "Expected syntax, got " .. display1((function()
  5904. if temp2 == "nil" then
  5905. return "nothing"
  5906. else
  5907. return temp2
  5908. end
  5909. end)())))
  5910. end
  5911. i = i + 1
  5912. elseif temp1 == "stmt" then
  5913. if var["kind"] ~= "native" then
  5914. errorPositions_21_1(log, child, "Can only set native definitions as statements")
  5915. end
  5916. local native = varNative1(var)
  5917. if native["syntax-stmt"] then
  5918. errorPositions_21_1(log, child, "This definition is already a statement")
  5919. end
  5920. native["syntax-stmt"] = true
  5921. elseif temp1 == "syntax-precedence" then
  5922. if var["kind"] ~= "native" then
  5923. errorPositions_21_1(log, child, "Can only set syntax of native definitions")
  5924. end
  5925. local native, precedence = varNative1(var), nth1(node, i + 1)
  5926. if native["syntax-precedence"] then
  5927. errorPositions_21_1(log, child, "Multiple precedences set")
  5928. end
  5929. local temp2 = type1(precedence)
  5930. if temp2 == "number" then
  5931. native["syntax-precedence"] = (precedence["value"])
  5932. elseif temp2 == "list" then
  5933. local res = {tag="list", n=0}
  5934. local forLimit = n1(precedence)
  5935. local i1 = 1
  5936. while i1 <= forLimit do
  5937. local prec = precedence[i1]
  5938. expectType_21_1(log, prec, precedence, "number", "precedence")
  5939. push_21_1(res, prec["value"])
  5940. i1 = i1 + 1
  5941. end
  5942. native["syntax-precedence"] = res
  5943. else
  5944. errorPositions_21_1(log, child, formatOutput_21_1(nil, "Expected precedence, got " .. display1((function()
  5945. if temp2 == "nil" then
  5946. return "nothing"
  5947. else
  5948. return temp2
  5949. end
  5950. end)())))
  5951. end
  5952. i = i + 1
  5953. elseif temp1 == "syntax-fold" then
  5954. if var["kind"] ~= "native" then
  5955. errorPositions_21_1(log, child, "Can only set syntax of native definitions")
  5956. end
  5957. local native = varNative1(var)
  5958. expectType_21_1(log, nth1(node, i + 1), node, "string", "fold direction")
  5959. if native["syntax-fold"] then
  5960. errorPositions_21_1(log, child, "Multiple fold directions set")
  5961. end
  5962. local temp2 = nth1(node, i + 1)["value"]
  5963. if temp2 == "left" then
  5964. native["syntax-fold"] = "left"
  5965. elseif temp2 == "right" then
  5966. native["syntax-fold"] = "right"
  5967. else
  5968. errorPositions_21_1(log, nth1(node, i + 1), formatOutput_21_1(nil, "Unknown fold direction " .. quoted1(temp2)))
  5969. end
  5970. i = i + 1
  5971. else
  5972. errorPositions_21_1(log, child, "Unexpected modifier '" .. pretty1(child) .. "'")
  5973. end
  5974. else
  5975. errorPositions_21_1(log, child, "Unexpected modifier of type " .. temp .. ", have you got too many values?")
  5976. end
  5977. i = i + 1
  5978. end
  5979. if var["kind"] == "native" then
  5980. local native = varNative1(var)
  5981. if native["syntax"] and native["bind-to"] then
  5982. errorPositions_21_1(log, node, "Cannot specify :syntax and :bind-to in native definition")
  5983. end
  5984. if native["syntax-fold"] and not native["syntax"] then
  5985. errorPositions_21_1(log, node, "Cannot specify a fold direction when no syntax given")
  5986. end
  5987. if native["syntax-stmt"] and not native["syntax"] then
  5988. errorPositions_21_1(log, node, "Cannot have a statement when no syntax given")
  5989. end
  5990. if native["syntax-precedence"] and not native["syntax"] then
  5991. errorPositions_21_1(log, node, "Cannot specify a precedence when no syntax given")
  5992. end
  5993. if native["syntax"] then
  5994. local syntaxArity, signature = native["syntax-arity"], native["signature"]
  5995. local signatureArity
  5996. if type1(signature) == "list" then
  5997. signatureArity = n1(signature)
  5998. else
  5999. signatureArity = nil
  6000. end
  6001. local precedence = native["syntax-precedence"]
  6002. local precArity
  6003. if type1(precedence) == "list" then
  6004. precArity = n1(precedence)
  6005. else
  6006. precArity = nil
  6007. end
  6008. if signatureArity and signatureArity ~= syntaxArity then
  6009. errorPositions_21_1(log, node, formatOutput_21_1(nil, "Definition has arity " .. display1(syntaxArity) .. ", but signature has " .. display1(signatureArity) .. " arguments"))
  6010. end
  6011. if precArity and precArity ~= syntaxArity then
  6012. errorPositions_21_1(log, node, formatOutput_21_1(nil, "Definition has arity " .. display1(syntaxArity) .. ", but precedence has " .. display1(precArity) .. " values"))
  6013. end
  6014. if native["syntax-fold"] and syntaxArity ~= 2 then
  6015. errorPositions_21_1(log, node, formatOutput_21_1(nil, "Cannot specify a fold direction with arity " .. display1(syntaxArity) .. " (must be 2)"))
  6016. end
  6017. end
  6018. end
  6019. return nil
  6020. end
  6021. resolveExecuteResult1 = function(source, node, scope, state)
  6022. local temp = type_23_1(node)
  6023. if temp == "string" then
  6024. node = {tag="string", value=node}
  6025. elseif temp == "number" then
  6026. node = {tag="number", value=node}
  6027. elseif temp == "boolean" then
  6028. node = {tag="symbol", contents=tostring1(node), var=builtins1[(tostring1(node))]}
  6029. elseif temp == "table" then
  6030. local tag = type1(node)
  6031. if tag == "symbol" or tag == "string" or tag == "number" or tag == "key" or tag == "list" then
  6032. local copy = {}
  6033. local temp1 = node
  6034. local temp2, v = next1(temp1)
  6035. while temp2 ~= nil do
  6036. copy[temp2] = v
  6037. temp2, v = next1(temp1, temp2)
  6038. end
  6039. node = copy
  6040. else
  6041. doNodeError_21_1(state["compiler"]["log"], formatOutput_21_1(nil, "Invalid node of type " .. display1(type1(node)) .. " from " .. display1(formatNodeSourceName1(source))), source, nil, sourceRange1(source), "")
  6042. end
  6043. else
  6044. doNodeError_21_1(state["compiler"]["log"], formatOutput_21_1(nil, "Invalid node of type " .. display1(type1(node)) .. " from " .. display1(formatNodeSourceName1(source))), source, nil, sourceRange1(source), "")
  6045. end
  6046. if not node["source"] then
  6047. node["source"] = source
  6048. end
  6049. local temp = type1(node)
  6050. if temp == "list" then
  6051. local forLimit = n1(node)
  6052. local i = 1
  6053. while i <= forLimit do
  6054. node[i] = resolveExecuteResult1(source, nth1(node, i), scope, state)
  6055. i = i + 1
  6056. end
  6057. elseif temp == "symbol" then
  6058. if string_3f_1(node["var"]) then
  6059. local var = state["compiler"]["variables"][node["var"]]
  6060. if not var then
  6061. errorPositions_21_1(state["compiler"]["log"], node, "Invalid variable key " .. quoted1(node["var"]) .. " for " .. pretty1(node))
  6062. end
  6063. node["var"] = var
  6064. end
  6065. end
  6066. return node
  6067. end
  6068. resolveQuote1 = function(node, scope, state, level)
  6069. if level == 0 then
  6070. return resolveNode1(node, scope, state)
  6071. else
  6072. local temp = type1(node)
  6073. if temp == "string" then
  6074. return node
  6075. elseif temp == "number" then
  6076. return node
  6077. elseif temp == "key" then
  6078. return node
  6079. elseif temp == "symbol" then
  6080. if not node["var"] then
  6081. node["var"] = lookupAlways_21_1(scope, node["contents"], node)
  6082. if not (node["var"]["scope"]["kind"] == "top-level" or node["var"]["scope"]["kind"] == "builtin") then
  6083. errorPositions_21_1(state["compiler"]["log"], node, "Cannot use non-top level definition '" .. node["var"]["name"] .. "' in syntax-quote")
  6084. end
  6085. end
  6086. return node
  6087. elseif temp == "list" then
  6088. local first = car1(node)
  6089. if first then
  6090. node[1] = resolveQuote1(first, scope, state, level)
  6091. if type1(first) == "symbol" then
  6092. if first["var"] == builtins1["unquote"] then
  6093. level = level - 1
  6094. elseif first["var"] == builtins1["unquote-splice"] then
  6095. level = level - 1
  6096. elseif first["var"] == builtins1["syntax-quote"] then
  6097. level = level + 1
  6098. end
  6099. end
  6100. end
  6101. local forLimit = n1(node)
  6102. local i = 2
  6103. while i <= forLimit do
  6104. node[i] = resolveQuote1(nth1(node, i), scope, state, level)
  6105. i = i + 1
  6106. end
  6107. return node
  6108. else
  6109. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  6110. end
  6111. end
  6112. end
  6113. resolveNode1 = function(node, scope, state, root, many)
  6114. while true do
  6115. local node1 = node
  6116. local temp = type1(node1)
  6117. if temp == "number" then
  6118. return node1
  6119. elseif temp == "string" then
  6120. return node1
  6121. elseif temp == "key" then
  6122. return node1
  6123. elseif temp == "symbol" then
  6124. if not node1["var"] then
  6125. node1["var"] = lookupAlways_21_1(scope, node1["contents"], node1)
  6126. end
  6127. if node1["var"]["kind"] == "builtin" then
  6128. errorPositions_21_1(state["compiler"]["log"], node1, "Cannot have a raw builtin.")
  6129. end
  6130. require_21_1(state, node1["var"], node1)
  6131. return node1
  6132. elseif temp == "list" then
  6133. local first = car1(node1)
  6134. local temp1 = type1(first)
  6135. if temp1 == "symbol" then
  6136. if not first["var"] then
  6137. first["var"] = lookupAlways_21_1(scope, first["contents"], first)
  6138. end
  6139. local func = first["var"]
  6140. local funcState, temp2 = require_21_1(state, func, first), func["kind"]
  6141. if temp2 == "builtin" then
  6142. if func == builtins1["lambda"] then
  6143. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "list", "argument list")
  6144. local childScope, args, hasVariadic = child1(scope), nth1(node1, 2), false
  6145. local forLimit = n1(args)
  6146. local i = 1
  6147. while i <= forLimit do
  6148. expectType_21_1(state["compiler"]["log"], nth1(args, i), args, "symbol", "argument")
  6149. local arg = nth1(args, i)
  6150. local name = arg["contents"]
  6151. local isVar = sub1(name, 1, 1) == "&"
  6152. if isVar then
  6153. if hasVariadic then
  6154. errorPositions_21_1(state["compiler"]["log"], args, "Cannot have multiple variadic arguments")
  6155. elseif n1(name) == 1 then
  6156. errorPositions_21_1(state["compiler"]["log"], arg, format1("Expected a symbol for variadic argument.%s", (function()
  6157. if i < n1(args) then
  6158. local nextArg = nth1(args, i + 1)
  6159. if type1(nextArg) == "symbol" and sub1(nextArg["contents"], 1, 1) ~= "&" then
  6160. return format1("\nDid you mean '&%s'?", nextArg["contents"])
  6161. else
  6162. return ""
  6163. end
  6164. else
  6165. return ""
  6166. end
  6167. end)()))
  6168. else
  6169. name = sub1(name, 2)
  6170. hasVariadic = true
  6171. end
  6172. end
  6173. local var = addVerbose_21_1(childScope, name, "arg", arg, state["compiler"]["log"])
  6174. var["display-name"] = (arg["display-name"])
  6175. var["is-variadic"] = isVar
  6176. arg["var"] = var
  6177. i = i + 1
  6178. end
  6179. return resolveBlock1(node1, 3, childScope, state)
  6180. elseif func == builtins1["cond"] then
  6181. local forLimit = n1(node1)
  6182. local i = 2
  6183. while i <= forLimit do
  6184. local case = nth1(node1, i)
  6185. expectType_21_1(state["compiler"]["log"], case, node1, "list", "case expression")
  6186. expect_21_1(state["compiler"]["log"], car1(case), case, "condition")
  6187. case[1] = resolveNode1(car1(case), scope, state)
  6188. resolveBlock1(case, 2, scope, state)
  6189. i = i + 1
  6190. end
  6191. return node1
  6192. elseif func == builtins1["set!"] then
  6193. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "symbol")
  6194. expect_21_1(state["compiler"]["log"], nth1(node1, 3), node1, "value")
  6195. maxLength_21_1(state["compiler"]["log"], node1, 3, "set!")
  6196. local var = lookupAlways_21_1(scope, nth1(node1, 2)["contents"], nth1(node1, 2))
  6197. require_21_1(state, var, nth1(node1, 2))
  6198. node1[2]["var"] = var
  6199. if var["const"] then
  6200. errorPositions_21_1(state["compiler"]["log"], node1, format1("Cannot rebind immutable definition '%s'", nth1(node1, 2)["contents"]), format1("Top level definitions are immutable by default. If you want\nto redefine '%s', add the `:mutable` modifier to its definition.", nth1(node1, 2)["contents"]))
  6201. end
  6202. node1[3] = resolveNode1(nth1(node1, 3), scope, state)
  6203. return node1
  6204. elseif func == builtins1["quote"] then
  6205. expect_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "value")
  6206. maxLength_21_1(state["compiler"]["log"], node1, 2, "quote")
  6207. return node1
  6208. elseif func == builtins1["syntax-quote"] then
  6209. expect_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "value")
  6210. maxLength_21_1(state["compiler"]["log"], node1, 2, "syntax-quote")
  6211. node1[2] = resolveQuote1(nth1(node1, 2), scope, state, 1)
  6212. return node1
  6213. elseif func == builtins1["unquote"] then
  6214. expect_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "value")
  6215. local result, states = {tag="list", n=0}, {tag="list", n=0}
  6216. local forLimit = n1(node1)
  6217. local i = 2
  6218. while i <= forLimit do
  6219. local childState = create3(scope, state["compiler"])
  6220. local built = resolveNode1(nth1(node1, i), scope, childState)
  6221. built_21_1(childState, {tag="list", n=3, source=built["source"], [1]={tag="symbol", contents="lambda", var=builtins1["lambda"]}, [2]={tag="list", n=0}, [3]=built})
  6222. local func1 = get_21_1(childState)
  6223. state["compiler"]["active-scope"] = scope
  6224. state["compiler"]["active-node"] = built
  6225. local temp3 = state["compiler"]["exec"](func1)
  6226. if type1(temp3) == "list" and (n1(temp3) >= 2 and (n1(temp3) <= 2 and (nth1(temp3, 1) == false and true))) then
  6227. local msg = nth1(temp3, 2)
  6228. errorPositions_21_1(state["compiler"]["log"], node1, remapTraceback1(state["compiler"]["compile-state"]["mappings"], msg))
  6229. elseif type1(temp3) == "list" and (n1(temp3) >= 1 and (nth1(temp3, 1) == true and true)) then
  6230. local replacement = slice1(temp3, 2)
  6231. if i == n1(node1) then
  6232. local forLimit1 = n1(replacement)
  6233. local i1 = 1
  6234. while i1 <= forLimit1 do
  6235. local child = replacement[i1]
  6236. push_21_1(result, child)
  6237. push_21_1(states, childState)
  6238. i1 = i1 + 1
  6239. end
  6240. elseif n1(replacement) == 1 then
  6241. push_21_1(result, car1(replacement))
  6242. push_21_1(states, childState)
  6243. else
  6244. errorPositions_21_1(state["compiler"]["log"], nth1(node1, i), "Expected one value, got " .. n1(replacement))
  6245. end
  6246. else
  6247. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp3) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true . ?replacement)`")
  6248. end
  6249. i = i + 1
  6250. end
  6251. if n1(result) == 0 or n1(result) == 1 and car1(result) == nil then
  6252. result = list1({tag="symbol", contents="nil", var=builtins1["nil"]})
  6253. end
  6254. local source, forLimit = {tag="node-source", owner=nil, parent=node1["source"], range=sourceRange1(node1["source"])}, n1(result)
  6255. local i = 1
  6256. while i <= forLimit do
  6257. result[i] = resolveExecuteResult1(source, nth1(result, i), scope, state)
  6258. i = i + 1
  6259. end
  6260. if n1(result) == 1 then
  6261. node = car1(result)
  6262. elseif many then
  6263. result["tag"] = "many"
  6264. return result
  6265. else
  6266. return errorPositions_21_1(state["compiler"]["log"], node1, "Multiple values returned in a non block context")
  6267. end
  6268. elseif func == builtins1["unquote-splice"] then
  6269. maxLength_21_1(state["compiler"]["log"], node1, 2, "unquote-splice")
  6270. local childState = create3(scope, state["compiler"])
  6271. local built = resolveNode1(nth1(node1, 2), scope, childState)
  6272. built_21_1(childState, {tag="list", n=3, source=built["source"], [1]={tag="symbol", contents="lambda", var=builtins1["lambda"]}, [2]={tag="list", n=0}, [3]=built})
  6273. local func1 = get_21_1(childState)
  6274. state["compiler"]["active-scope"] = scope
  6275. state["compiler"]["active-node"] = built
  6276. local temp3 = state["compiler"]["exec"](func1)
  6277. if type1(temp3) == "list" and (n1(temp3) >= 2 and (n1(temp3) <= 2 and (nth1(temp3, 1) == false and true))) then
  6278. local msg = nth1(temp3, 2)
  6279. return errorPositions_21_1(state["compiler"]["log"], node1, remapTraceback1(state["compiler"]["compile-state"]["mappings"], msg))
  6280. elseif type1(temp3) == "list" and (n1(temp3) >= 1 and (nth1(temp3, 1) == true and true)) then
  6281. local result = car1((slice1(temp3, 2)))
  6282. if type1(result) ~= "list" then
  6283. errorPositions_21_1(state["compiler"]["log"], node1, "Expected list from unquote-splice, got '" .. type1(result) .. "'")
  6284. end
  6285. if n1(result) == 0 then
  6286. result = list1({tag="symbol", contents="nil", var=builtins1["nil"]})
  6287. end
  6288. local source, forLimit = {tag="node-source", owner=nil, parent=node1["source"], range=sourceRange1(node1["source"])}, n1(result)
  6289. local i = 1
  6290. while i <= forLimit do
  6291. result[i] = resolveExecuteResult1(source, nth1(result, i), scope, state)
  6292. i = i + 1
  6293. end
  6294. if n1(result) == 1 then
  6295. node = car1(result)
  6296. elseif many then
  6297. result["tag"] = "many"
  6298. return result
  6299. else
  6300. return errorPositions_21_1(state["compiler"]["log"], node1, "Multiple values returned in a non-block context")
  6301. end
  6302. else
  6303. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp3) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true . ?replacement)`")
  6304. end
  6305. elseif func == builtins1["define"] then
  6306. if not root then
  6307. errorPositions_21_1(state["compiler"]["log"], first, "define can only be used on the top level")
  6308. end
  6309. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "symbol", "name")
  6310. expect_21_1(state["compiler"]["log"], nth1(node1, 3), node1, "value")
  6311. local var = addVerbose_21_1(scope, nth1(node1, 2)["contents"], "defined", node1, state["compiler"]["log"])
  6312. var["display-name"] = (nth1(node1, 2)["display-name"])
  6313. define_21_1(state, var)
  6314. node1["def-var"] = var
  6315. handleMetadata1(state["compiler"]["log"], node1, var, 3, n1(node1) - 1)
  6316. node1[n1(node1)] = resolveNode1(nth1(node1, n1(node1)), scope, state)
  6317. return node1
  6318. elseif func == builtins1["define-macro"] then
  6319. if not root then
  6320. errorPositions_21_1(state["compiler"]["log"], first, "define-macro can only be used on the top level")
  6321. end
  6322. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "symbol", "name")
  6323. expect_21_1(state["compiler"]["log"], nth1(node1, 3), node1, "value")
  6324. local var = addVerbose_21_1(scope, nth1(node1, 2)["contents"], "macro", node1, state["compiler"]["log"])
  6325. var["display-name"] = (nth1(node1, 2)["display-name"])
  6326. define_21_1(state, var)
  6327. node1["def-var"] = var
  6328. handleMetadata1(state["compiler"]["log"], node1, var, 3, n1(node1) - 1)
  6329. node1[n1(node1)] = resolveNode1(nth1(node1, n1(node1)), scope, state)
  6330. return node1
  6331. elseif func == builtins1["define-native"] then
  6332. if not root then
  6333. errorPositions_21_1(state["compiler"]["log"], first, "define-native can only be used on the top level")
  6334. end
  6335. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "symbol", "name")
  6336. local var = addVerbose_21_1(scope, nth1(node1, 2)["contents"], "native", node1, state["compiler"]["log"])
  6337. local native
  6338. local cache, name = state["compiler"]["libs"], var["unique-name"]
  6339. native = cache["metas"][name]
  6340. if native then
  6341. setVarNative_21_1(var, native)
  6342. end
  6343. var["display-name"] = (nth1(node1, 2)["display-name"])
  6344. define_21_1(state, var)
  6345. node1["def-var"] = var
  6346. handleMetadata1(state["compiler"]["log"], node1, var, 3, n1(node1))
  6347. return node1
  6348. elseif func == builtins1["import"] then
  6349. expectType_21_1(state["compiler"]["log"], nth1(node1, 2), node1, "symbol", "module name")
  6350. local as, symbols, exportIdx, qualifier = nil, nil, nil, nth1(node1, 3)
  6351. local temp3 = type1(qualifier)
  6352. if temp3 == "symbol" then
  6353. exportIdx = 4
  6354. as = qualifier["contents"]
  6355. symbols = nil
  6356. elseif temp3 == "list" then
  6357. exportIdx = 4
  6358. as = nil
  6359. if n1(qualifier) == 0 then
  6360. symbols = nil
  6361. else
  6362. symbols = {}
  6363. local forLimit = n1(qualifier)
  6364. local i = 1
  6365. while i <= forLimit do
  6366. local entry = qualifier[i]
  6367. expectType_21_1(state["compiler"]["log"], entry, qualifier, "symbol")
  6368. symbols[entry["contents"]] = entry
  6369. i = i + 1
  6370. end
  6371. end
  6372. elseif temp3 == "nil" then
  6373. exportIdx = 3
  6374. as = nth1(node1, 2)["contents"]
  6375. symbols = nil
  6376. elseif temp3 == "key" then
  6377. exportIdx = 3
  6378. as = nth1(node1, 2)["contents"]
  6379. symbols = nil
  6380. else
  6381. expectType_21_1(state["compiler"]["log"], nth1(node1, 3), node1, "symbol", "alias name of import list")
  6382. end
  6383. maxLength_21_1(state["compiler"]["log"], node1, exportIdx, "import")
  6384. yield1({tag="import", module=nth1(node1, 2)["contents"], as=as, symbols=symbols, export=(function()
  6385. local export = nth1(node1, exportIdx)
  6386. if export then
  6387. expectType_21_1(state["compiler"]["log"], export, node1, "key", "import modifier")
  6388. if export["value"] == "export" then
  6389. return true
  6390. else
  6391. return errorPositions_21_1(state["compiler"]["log"], export, "unknown import modifier")
  6392. end
  6393. else
  6394. return export
  6395. end
  6396. end)(), scope=scope})
  6397. return node1
  6398. elseif func == builtins1["struct-literal"] then
  6399. if n1(node1) % 2 ~= 1 then
  6400. errorPositions_21_1(state["compiler"]["log"], node1, "Expected an even number of arguments, got " .. n1(node1) - 1)
  6401. end
  6402. return resolveList1(node1, 2, scope, state)
  6403. else
  6404. return errorPositions_21_1(state["compiler"]["log"], node1, "[Internal]" .. ("Unknown builtin " .. (function()
  6405. if func then
  6406. return func["name"]
  6407. else
  6408. return "?"
  6409. end
  6410. end)()))
  6411. end
  6412. elseif temp2 == "macro" then
  6413. if not funcState then
  6414. errorPositions_21_1(state["compiler"]["log"], first, "[Internal]Macro is not defined correctly")
  6415. end
  6416. local builder = get_21_1(funcState)
  6417. if type1(builder) ~= "function" then
  6418. errorPositions_21_1(state["compiler"]["log"], first, "Macro is of type " .. type1(builder))
  6419. end
  6420. state["compiler"]["active-scope"] = scope
  6421. state["compiler"]["active-node"] = node1
  6422. local temp3
  6423. local _efunction = function()
  6424. return apply1(builder, slicingView1(node1, 1))
  6425. end
  6426. temp3 = state["compiler"]["exec"](_efunction)
  6427. if type1(temp3) == "list" and (n1(temp3) >= 2 and (n1(temp3) <= 2 and (nth1(temp3, 1) == false and true))) then
  6428. local msg = nth1(temp3, 2)
  6429. return errorPositions_21_1(state["compiler"]["log"], first, remapTraceback1(state["compiler"]["compile-state"]["mappings"], msg))
  6430. elseif type1(temp3) == "list" and (n1(temp3) >= 1 and (nth1(temp3, 1) == true and true)) then
  6431. local replacement = slice1(temp3, 2)
  6432. local source, forLimit = {tag="node-source", owner=func, parent=first["source"], range=sourceRange1(node1["source"])}, n1(replacement)
  6433. local i = 1
  6434. while i <= forLimit do
  6435. replacement[i] = resolveExecuteResult1(source, nth1(replacement, i), scope, state)
  6436. i = i + 1
  6437. end
  6438. if n1(replacement) == 0 then
  6439. return errorPositions_21_1(state["compiler"]["log"], node1, "Expected some value from " .. name1(funcState) .. ", got nothing")
  6440. elseif n1(replacement) == 1 then
  6441. node = car1(replacement)
  6442. elseif many then
  6443. replacement["tag"] = "many"
  6444. return replacement
  6445. else
  6446. return errorPositions_21_1(state["compiler"]["log"], node1, "Multiple values returned in a non-block context.")
  6447. end
  6448. else
  6449. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp3) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true . ?replacement)`")
  6450. end
  6451. else
  6452. return resolveList1(node1, 1, scope, state)
  6453. end
  6454. elseif temp1 == "list" then
  6455. return resolveList1(node1, 1, scope, state)
  6456. else
  6457. return errorPositions_21_1(state["compiler"]["log"], first or node1, "Cannot invoke a non-function type '" .. temp1 .. "'")
  6458. end
  6459. else
  6460. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"number\"`\n Tried: `\"string\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  6461. end
  6462. end
  6463. end
  6464. resolveList1 = function(nodes, start, scope, state)
  6465. local forLimit = n1(nodes)
  6466. local i = start
  6467. while i <= forLimit do
  6468. nodes[i] = resolveNode1(nth1(nodes, i), scope, state)
  6469. i = i + 1
  6470. end
  6471. return nodes
  6472. end
  6473. resolveBlock1 = function(nodes, start, scope, state)
  6474. local len, i = n1(nodes), start
  6475. while i <= len do
  6476. local node = resolveNode1(nth1(nodes, i), scope, state, false, true)
  6477. if node["tag"] == "many" then
  6478. nodes[i] = nth1(node, 1)
  6479. local forLimit = n1(node)
  6480. local j = 2
  6481. while j <= forLimit do
  6482. insertNth_21_1(nodes, i + (j - 1), nth1(node, j))
  6483. j = j + 1
  6484. end
  6485. len = len + (n1(node) - 1)
  6486. else
  6487. nodes[i] = node
  6488. i = i + 1
  6489. end
  6490. end
  6491. return nodes
  6492. end
  6493. resolve1 = function(node, scope, state)
  6494. node = resolveNode1(node, scope, state, true, true)
  6495. while node["tag"] == "many" and n1(node) == 1 do
  6496. node = resolveNode1(car1(node), scope, state, true, true)
  6497. end
  6498. return node
  6499. end
  6500. distance1 = function(a, b)
  6501. if a == b then
  6502. return 0
  6503. elseif n1(a) == 0 then
  6504. return n1(b)
  6505. elseif n1(b) == 0 then
  6506. return n1(a)
  6507. else
  6508. local v0, v1 = {tag="list", n=0}, {tag="list", n=0}
  6509. local forLimit = n1(b) + 1
  6510. local i = 1
  6511. while i <= forLimit do
  6512. push_21_1(v0, i - 1)
  6513. push_21_1(v1, 0)
  6514. i = i + 1
  6515. end
  6516. local forLimit = n1(a)
  6517. local i = 1
  6518. while i <= forLimit do
  6519. v1[1] = i
  6520. local forLimit1 = n1(b)
  6521. local j = 1
  6522. while j <= forLimit1 do
  6523. local subCost, delCost, addCost, aChar, bChar = 1, 1, 1, sub1(a, i, i), sub1(b, j, j)
  6524. if aChar == bChar then
  6525. subCost = 0
  6526. end
  6527. if aChar == "-" or aChar == "/" then
  6528. delCost = 0.5
  6529. end
  6530. if bChar == "-" or bChar == "/" then
  6531. addCost = 0.5
  6532. end
  6533. if n1(a) <= 5 or n1(b) <= 5 then
  6534. subCost = subCost * 2
  6535. delCost = delCost + 0.5
  6536. end
  6537. v1[j + 1] = min1(nth1(v1, j) + delCost, nth1(v0, j + 1) + addCost, nth1(v0, j) + subCost)
  6538. j = j + 1
  6539. end
  6540. local forLimit1 = n1(v0)
  6541. local j = 1
  6542. while j <= forLimit1 do
  6543. v0[j] = nth1(v1, j)
  6544. j = j + 1
  6545. end
  6546. i = i + 1
  6547. end
  6548. return nth1(v1, n1(b) + 1)
  6549. end
  6550. end
  6551. compile1 = function(compiler, nodes, scope, name, loader)
  6552. local queue, states, loader1, logger, timer = {tag="list", n=0}, {tag="list", n=0}, loader or compiler["loader"], compiler["log"], compiler["timer"]
  6553. if name then
  6554. name = "[resolve] " .. name
  6555. end
  6556. local hook, hookMask, hookCount
  6557. if gethook1 then
  6558. hook, hookMask, hookCount = gethook1()
  6559. else
  6560. hook, hookMask, hookCount = nil
  6561. end
  6562. local forLimit = n1(nodes)
  6563. local i = 1
  6564. while i <= forLimit do
  6565. local node, state, co = nth1(nodes, i), create3(scope, compiler), create2(resolve1)
  6566. push_21_1(states, state)
  6567. if hook then
  6568. sethook1(co, hook, hookMask, hookCount)
  6569. end
  6570. push_21_1(queue, {tag="init", node=node, _co=co, _state=state, _node=node, _idx=i})
  6571. i = i + 1
  6572. end
  6573. local skipped = 0
  6574. local resume = function(action, ...)
  6575. local args = _pack(...) args.tag = "list"
  6576. skipped = 0
  6577. compiler["active-scope"] = action["_active-scope"]
  6578. compiler["active-node"] = action["_active-node"]
  6579. local temp = list1(resume1(action["_co"], splice1(args)))
  6580. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and true)) then
  6581. local status, result = nth1(temp, 1), nth1(temp, 2)
  6582. if not status then
  6583. error1(result, 0)
  6584. elseif status1(action["_co"]) == "dead" then
  6585. if result["tag"] == "many" then
  6586. local baseIdx = action["_idx"]
  6587. self1(logger, "put-debug!", " Got multiple nodes as a result. Adding to queue")
  6588. local forLimit = n1(queue)
  6589. local i = 1
  6590. while i <= forLimit do
  6591. local elem = queue[i]
  6592. if elem["_idx"] > action["_idx"] then
  6593. elem["_idx"] = elem["_idx"] + (n1(result) - 1)
  6594. end
  6595. i = i + 1
  6596. end
  6597. local forLimit = n1(result)
  6598. local i = 1
  6599. while i <= forLimit do
  6600. local state = create3(scope, compiler)
  6601. if i == 1 then
  6602. states[baseIdx] = state
  6603. else
  6604. insertNth_21_1(states, baseIdx + (i - 1), state)
  6605. end
  6606. local co = create2(resolve1)
  6607. if hook then
  6608. sethook1(co, hook, hookMask, hookCount)
  6609. end
  6610. push_21_1(queue, {tag="init", node=nth1(result, i), _co=co, _state=state, _node=nth1(result, i), _idx=baseIdx + (i - 1)})
  6611. i = i + 1
  6612. end
  6613. else
  6614. built_21_1(action["_state"], result)
  6615. end
  6616. else
  6617. result["_co"] = action["_co"]
  6618. result["_state"] = action["_state"]
  6619. result["_node"] = action["_node"]
  6620. result["_idx"] = action["_idx"]
  6621. result["_active-scope"] = compiler["active-scope"]
  6622. result["_active-node"] = compiler["active-node"]
  6623. push_21_1(queue, result)
  6624. end
  6625. else
  6626. error1("Pattern matching failure! Can not match the pattern `(?status ?result)` against `" .. pretty1(temp) .. "`.")
  6627. end
  6628. compiler["active-scope"] = nil
  6629. compiler["active-node"] = nil
  6630. return nil
  6631. end
  6632. if name then
  6633. startTimer_21_1(timer, name, 2)
  6634. end
  6635. while n1(queue) > 0 and skipped <= n1(queue) do
  6636. local head = removeNth_21_1(queue, 1)
  6637. self1(logger, "put-debug!", (formatOutput_21_1(nil, "" .. display1(type1(head)) .. " for " .. display1(head["_state"]["stage"]) .. " at " .. display1(formatNode1(head["_node"])) .. " (" .. display1((function()
  6638. if head["_state"]["var"] then
  6639. return head["_state"]["var"]["name"]
  6640. else
  6641. return "?"
  6642. end
  6643. end)()) .. ")")))
  6644. local temp = type1(head)
  6645. if temp == "init" then
  6646. resume(head, head["node"], scope, head["_state"])
  6647. elseif temp == "define" then
  6648. local var
  6649. local name2 = head["name"]
  6650. var = scope["variables"][name2]
  6651. if var then
  6652. resume(head, var)
  6653. else
  6654. self1(logger, "put-debug!", (" Awaiting definiion of " .. head["name"]))
  6655. skipped = skipped + 1
  6656. push_21_1(queue, head)
  6657. end
  6658. elseif temp == "build" then
  6659. if head["state"]["stage"] ~= "parsed" then
  6660. resume(head)
  6661. else
  6662. self1(logger, "put-debug!", (" Awaiting building of node " .. (function()
  6663. if head["state"]["var"] then
  6664. return head["state"]["var"]["name"]
  6665. else
  6666. return "?"
  6667. end
  6668. end)()))
  6669. skipped = skipped + 1
  6670. push_21_1(queue, head)
  6671. end
  6672. elseif temp == "execute" then
  6673. executeStates1(compiler["compile-state"], head["states"], compiler["global"])
  6674. resume(head)
  6675. elseif temp == "import" then
  6676. if name then
  6677. pauseTimer_21_1(timer, name)
  6678. end
  6679. local result = loader1(head["module"])
  6680. local module = car1(result)
  6681. if name then
  6682. startTimer_21_1(timer, name)
  6683. end
  6684. if not module then
  6685. doNodeError_21_1(logger, nth1(result, 2), head["_node"]["source"], nil, sourceRange1(head["_node"]["source"]), "")
  6686. end
  6687. local export, scope1, node, temp1 = head["export"], head["scope"], head["_node"], module["scope"]["exported"]
  6688. local temp2, var = next1(temp1)
  6689. while temp2 ~= nil do
  6690. if head["as"] then
  6691. importVerbose_21_1(scope1, head["as"] .. "/" .. temp2, var, node, export, logger)
  6692. elseif head["symbols"] then
  6693. if head["symbols"][temp2] then
  6694. importVerbose_21_1(scope1, temp2, var, node, export, logger)
  6695. end
  6696. else
  6697. importVerbose_21_1(scope1, temp2, var, node, export, logger)
  6698. end
  6699. temp2, var = next1(temp1, temp2)
  6700. end
  6701. if head["symbols"] then
  6702. local failed = false
  6703. local temp1 = head["symbols"]
  6704. local temp2, nameNode = next1(temp1)
  6705. while temp2 ~= nil do
  6706. if not module["scope"]["exported"][temp2] then
  6707. failed = true
  6708. putNodeError_21_1(logger, "Cannot find " .. temp2, nameNode["source"], nil, sourceRange1(head["_node"]["source"]), "Importing here", sourceRange1(nameNode["source"]), "Required here")
  6709. end
  6710. temp2, nameNode = next1(temp1, temp2)
  6711. end
  6712. if failed then
  6713. compilerError_21_1("Resolution failed")
  6714. end
  6715. end
  6716. resume(head)
  6717. else
  6718. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"init\"`\n Tried: `\"define\"`\n Tried: `\"build\"`\n Tried: `\"execute\"`\n Tried: `\"import\"`")
  6719. end
  6720. end
  6721. if n1(queue) > 0 then
  6722. local forLimit = n1(queue)
  6723. local i = 1
  6724. while i <= forLimit do
  6725. local entry = queue[i]
  6726. local temp = type1(entry)
  6727. if temp == "define" then
  6728. local info, suggestions = nil, ""
  6729. local scope1 = entry["scope"]
  6730. if scope1 then
  6731. local vars, varDis, varSet, distances = {tag="list", n=0}, {tag="list", n=0}, {}, {}
  6732. while scope1 do
  6733. local temp1 = scope1["variables"]
  6734. local temp2, _5f_ = next1(temp1)
  6735. while temp2 ~= nil do
  6736. if not varSet[temp2] then
  6737. varSet[temp2] = "true"
  6738. push_21_1(vars, temp2)
  6739. local parlen = n1(entry["name"])
  6740. local lendiff = abs1(n1(temp2) - parlen)
  6741. if parlen <= 5 or lendiff <= parlen * 0.3 then
  6742. local dis = distance1(temp2, entry["name"]) / parlen
  6743. if parlen <= 5 then
  6744. dis = dis / 2
  6745. end
  6746. push_21_1(varDis, temp2)
  6747. distances[temp2] = dis
  6748. end
  6749. end
  6750. temp2, _5f_ = next1(temp1, temp2)
  6751. end
  6752. scope1 = scope1["parent"]
  6753. end
  6754. sort1(vars, nil)
  6755. sort1(varDis, function(a, b)
  6756. return distances[a] < distances[b]
  6757. end)
  6758. local elems
  6759. local temp1
  6760. local xs = first1(partition1(function(x)
  6761. return distances[x] <= 0.5
  6762. end, varDis))
  6763. temp1 = slice1(xs, 1, min1(5, n1(xs)))
  6764. elems = map2(function(temp2)
  6765. return coloured1("1;32", temp2)
  6766. end, temp1)
  6767. local temp1 = n1(elems)
  6768. if temp1 == 0 then
  6769. elseif temp1 == 1 then
  6770. suggestions = "\nDid you mean '" .. car1(elems) .. "'?"
  6771. else
  6772. suggestions = "\nDid you mean any of these?" .. "\n •" .. concat2(elems, "\n •")
  6773. end
  6774. info = "Variables in scope are " .. concat2(vars, ", ")
  6775. end
  6776. putNodeError_21_1(logger, "Cannot find variable '" .. entry["name"] .. "'" .. suggestions, (entry["node"] or entry["_node"])["source"], info, sourceRange1((entry["node"] or entry["_node"])["source"]), "")
  6777. elseif temp == "build" then
  6778. local var, node = entry["state"]["var"], entry["state"]["node"]
  6779. self1(logger, "put-error!", ("Could not build " .. (function()
  6780. if var then
  6781. return var["name"]
  6782. elseif node then
  6783. return formatNode1(node)
  6784. else
  6785. return "unknown node"
  6786. end
  6787. end)()))
  6788. else
  6789. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"define\"`\n Tried: `\"build\"`")
  6790. end
  6791. i = i + 1
  6792. end
  6793. compilerError_21_1("Resolution failed")
  6794. end
  6795. if name then
  6796. stopTimer_21_1(timer, name)
  6797. end
  6798. return splice1(list1(map2(rsNode1, states), states))
  6799. end
  6800. pathEscape1 = {["?"]="(.*)", ["."]="%.", ["%"]="%%", ["^"]="%^", ["$"]="%$", ["+"]="%+", ["-"]="%-", ["*"]="%*", ["["]="%[", ["]"]="%]", ["("]="%)", [")"]="%)"}
  6801. lispExtensions1 = {tag="list", n=3, ".lisp", ".cl", ".urn"}
  6802. tryHandle1 = function(name)
  6803. local i = 1
  6804. while true do
  6805. if (i > n1(lispExtensions1)) then
  6806. return nil
  6807. else
  6808. local handle = open1(name .. nth1(lispExtensions1, i), "r")
  6809. if handle then
  6810. return splice1(list1(handle, (name .. nth1(lispExtensions1, i))))
  6811. else
  6812. i = i + 1
  6813. end
  6814. end
  6815. end
  6816. end
  6817. simplifyPath1 = function(path, paths)
  6818. local current = path
  6819. local forLimit = n1(paths)
  6820. local i = 1
  6821. while i <= forLimit do
  6822. local sub = match1(path, "^" .. gsub1(paths[i], ".", pathEscape1) .. "$")
  6823. if sub and n1(sub) < n1(current) then
  6824. current = sub
  6825. end
  6826. i = i + 1
  6827. end
  6828. return current
  6829. end
  6830. stripExtension1 = function(path)
  6831. local i = 1
  6832. while true do
  6833. if i > n1(lispExtensions1) then
  6834. return path
  6835. else
  6836. local suffix = nth1(lispExtensions1, i)
  6837. if endsWith_3f_1(path, suffix) then
  6838. return sub1(path, 1, -1 - n1(suffix))
  6839. else
  6840. i = i + 1
  6841. end
  6842. end
  6843. end
  6844. end
  6845. readMeta1 = function(state, name, entry)
  6846. local native = {tag="native", pure=false, signature=nil, ["bind-to"]=nil, syntax=nil, ["syntax-arity"]=nil, ["syntax-fold"]=nil, ["syntax-stmt"]=false, ["syntax-precedence"]=nil}
  6847. local temp = type1(entry["count"])
  6848. if temp == "nil" then
  6849. elseif temp == "number" then
  6850. native["syntax-arity"] = (entry["count"])
  6851. else
  6852. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Expected number for " .. display1(name) .. "'s count, got " .. display1(temp))))
  6853. end
  6854. local temp = type1(entry["prec"])
  6855. if temp == "nil" then
  6856. elseif temp == "number" then
  6857. native["syntax-precedence"] = (entry["prec"])
  6858. else
  6859. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Expected number for " .. display1(name) .. "'s prec, got " .. display1(temp))))
  6860. end
  6861. local temp = type1(entry["precs"])
  6862. if temp == "nil" then
  6863. elseif temp == "list" then
  6864. native["syntax-precedence"] = (entry["precs"])
  6865. else
  6866. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Expected number for " .. display1(name) .. "'s precs, got " .. display1(temp))))
  6867. end
  6868. if entry["pure"] then
  6869. native["pure"] = true
  6870. end
  6871. local temp = type1(entry)
  6872. if temp == "expr" then
  6873. local buffer, max = parseTemplate1(entry["contents"])
  6874. native["syntax"] = buffer
  6875. if not entry["count"] then
  6876. native["syntax-arity"] = max
  6877. end
  6878. elseif temp == "stmt" then
  6879. local buffer, max = parseTemplate1(entry["contents"])
  6880. native["syntax"] = buffer
  6881. if not entry["count"] then
  6882. native["syntax-arity"] = max
  6883. end
  6884. native["syntax-stmt"] = true
  6885. elseif temp == "var" then
  6886. native["bind-to"] = (entry["contents"])
  6887. else
  6888. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Unknown meta type " .. display1(temp) .. " for " .. display1(name))))
  6889. end
  6890. local fold = entry["fold"]
  6891. if fold then
  6892. if type1(entry) ~= "expr" then
  6893. error1("Cannot have fold for non-expression " .. name, 0)
  6894. end
  6895. if entry["count"] ~= 2 then
  6896. error1("Cannot have fold for length " .. entry["count"] .. " for " .. name, 0)
  6897. end
  6898. if fold == "l" then
  6899. native["syntax-fold"] = "left"
  6900. elseif fold == "r" then
  6901. native["syntax-fold"] = "right"
  6902. else
  6903. error1("Unknown fold " .. fold .. " for " .. name, 0)
  6904. end
  6905. end
  6906. entry["name"] = name
  6907. local libValue, metaValue = state["libs"]["values"][name], entry["value"]
  6908. if libValue ~= nil and metaValue ~= nil then
  6909. error1("Duplicate value for " .. name .. ": in native and meta file", 0)
  6910. elseif libValue ~= nil then
  6911. entry["has-value"] = true
  6912. entry["value"] = libValue
  6913. elseif metaValue ~= nil then
  6914. entry["has-value"] = true
  6915. state["libs"]["values"][name] = metaValue
  6916. end
  6917. state["libs"]["metas"][name] = native
  6918. return nil
  6919. end
  6920. readLibrary1 = function(state, name, path, lispHandle)
  6921. self1(state["log"], "put-verbose!", ("Loading " .. path .. " into " .. name))
  6922. local uniqueName = name .. "-" .. n1(state["libs"]["loaded"])
  6923. local lib, contents = libraryOf1(name, uniqueName, path, state["root-scope"]), self1(lispHandle, "read", "*a")
  6924. self1(lispHandle, "close")
  6925. local handle = open1(path .. ".lib.lua", "r")
  6926. if handle then
  6927. local contents1 = self1(handle, "read", "*a")
  6928. self1(handle, "close")
  6929. lib["lua-contents"] = contents1
  6930. local fun, err = load1(contents1, "@" .. name)
  6931. if fun then
  6932. local temp = list1(xpcall1(fun, tracebackPlain1))
  6933. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  6934. local msg = nth1(temp, 2)
  6935. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Cannot load " .. display1(path) .. ".lib.lua (" .. tostring1(msg) .. ")")))
  6936. elseif type1(temp) == "list" and (n1(temp) >= 2 and (nth1(temp, 1) == true and (type_23_1((nth1(temp, 2))) == "table" and true))) then
  6937. local res = nth1(temp, 2)
  6938. local temp1, v = next1(res)
  6939. while temp1 ~= nil do
  6940. if string_3f_1(temp1) then
  6941. local cache, name2 = state["libs"], uniqueName .. "/" .. temp1
  6942. cache["values"][name2] = v
  6943. else
  6944. self1(state["log"], "put-warning!", (formatOutput_21_1(nil, "Non-string key '" .. tostring1(temp1) .. "' when loading " .. display1(path) .. ".lib.lua")))
  6945. end
  6946. temp1, v = next1(res, temp1)
  6947. end
  6948. else
  6949. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Received a non-table value from " .. display1(path) .. ".lib.lua")))
  6950. end
  6951. else
  6952. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Cannot load " .. display1(path) .. ".lib.lua (" .. display1(err) .. ")")))
  6953. end
  6954. end
  6955. local handle = open1(path .. ".meta.lua", "r")
  6956. if handle then
  6957. local contents1 = self1(handle, "read", "*a")
  6958. self1(handle, "close")
  6959. local fun, err = load1(contents1, "@" .. name)
  6960. if fun then
  6961. local temp = list1(xpcall1(fun, tracebackPlain1))
  6962. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  6963. local msg = nth1(temp, 2)
  6964. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Cannot load " .. display1(path) .. ".meta.lua (" .. tostring1(msg) .. ")")))
  6965. elseif type1(temp) == "list" and (n1(temp) >= 2 and (nth1(temp, 1) == true and (type_23_1((nth1(temp, 2))) == "table" and true))) then
  6966. local res = nth1(temp, 2)
  6967. local temp1, v = next1(res)
  6968. while temp1 ~= nil do
  6969. if string_3f_1(temp1) then
  6970. readMeta1(state, uniqueName .. "/" .. temp1, v)
  6971. else
  6972. self1(state["log"], "put-warning!", (formatOutput_21_1(nil, "Non-string key '" .. tostring1(temp1) .. "' when loading " .. display1(path) .. ".meta.lua")))
  6973. end
  6974. temp1, v = next1(res, temp1)
  6975. end
  6976. else
  6977. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Received a non-table value from " .. display1(path) .. ".meta.lua")))
  6978. end
  6979. else
  6980. self1(state["log"], "put-error!", (formatOutput_21_1(nil, "Cannot load " .. display1(path) .. ".meta.lua (" .. display1(err) .. ")")))
  6981. end
  6982. end
  6983. startTimer_21_1(state["timer"], "[parse] " .. path, 2)
  6984. local lexed, range = lex1(state["log"], contents, path .. ".lisp")
  6985. local parsed = parse1(state["log"], lexed)
  6986. stopTimer_21_1(state["timer"], "[parse] " .. path)
  6987. local prelude = state["prelude"]
  6988. if prelude then
  6989. lib["depends"][prelude] = true
  6990. end
  6991. local compiled = compile1(state, parsed, lib["scope"], path, function(name2)
  6992. local res = state["loader"](name2)
  6993. local module = car1(res)
  6994. if module then
  6995. lib["depends"][module] = true
  6996. end
  6997. return res
  6998. end)
  6999. push_21_1(state["libs"]["loaded"], lib)
  7000. if string_3f_1(car1(compiled)) then
  7001. lib["docs"] = (constVal1(car1(compiled)))
  7002. removeNth_21_1(compiled, 1)
  7003. end
  7004. lib["lisp-lines"] = (range["lines"])
  7005. lib["nodes"] = compiled
  7006. local forLimit = n1(compiled)
  7007. local i = 1
  7008. while i <= forLimit do
  7009. local node = compiled[i]
  7010. push_21_1(state["out"], node)
  7011. i = i + 1
  7012. end
  7013. self1(state["log"], "put-verbose!", ("Loaded " .. path .. " into " .. name))
  7014. return lib
  7015. end
  7016. namedLoader1 = function(state, name)
  7017. local cached = state["libs"]["names"][name]
  7018. if cached == nil then
  7019. state["libs"]["names"][name] = true
  7020. local searched, paths, _ = {tag="list", n=0}, state["paths"]
  7021. local i = 1
  7022. while true do
  7023. if i > n1(paths) then
  7024. return list1(nil, "Cannot find " .. quoted1(name) .. ".\nLooked in " .. concat2(searched, ", "))
  7025. else
  7026. local path = gsub1(nth1(paths, i), "%?", name)
  7027. local temp = pathLoader1(state, path)
  7028. if type1(temp) == "list" and (n1(temp) >= 1 and (n1(temp) <= 1 and true)) then
  7029. local lib = nth1(temp, 1)
  7030. state["libs"]["names"][name] = lib
  7031. return list1(lib)
  7032. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  7033. return list1(false, (nth1(temp, 2)))
  7034. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == nil and true))) then
  7035. push_21_1(searched, path)
  7036. i = i + 1
  7037. else
  7038. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(?lib)`\n Tried: `(false ?msg)`\n Tried: `(nil _)`")
  7039. end
  7040. end
  7041. end
  7042. elseif cached == true then
  7043. return list1(false, "Already loading " .. quoted1(name))
  7044. else
  7045. return list1(cached)
  7046. end
  7047. end
  7048. pathLoader1 = function(state, path)
  7049. local temp = state["libs"]["paths"][path]
  7050. if temp == nil then
  7051. local name, fullPath, handle = stripExtension1(path), path, nil
  7052. if name == path then
  7053. local handle_27_, path_27_ = tryHandle1(path)
  7054. if handle_27_ then
  7055. handle = handle_27_
  7056. fullPath = path_27_
  7057. end
  7058. else
  7059. handle = open1(path, "r")
  7060. end
  7061. local temp1
  7062. local cache, path1 = state["libs"], fullPath
  7063. temp1 = cache["paths"][path1]
  7064. if temp1 == nil then
  7065. if handle then
  7066. state["libs"]["paths"][path] = true
  7067. local cache, path1 = state["libs"], fullPath
  7068. cache["paths"][path1] = true
  7069. local lib = readLibrary1(state, simplifyPath1(name, state["paths"]), name, handle)
  7070. state["libs"]["paths"][path] = lib
  7071. local cache, path1 = state["libs"], fullPath
  7072. cache["paths"][path1] = lib
  7073. return list1(lib)
  7074. else
  7075. return list1(nil, "Cannot find " .. quoted1(path))
  7076. end
  7077. elseif temp1 == true then
  7078. if handle then
  7079. self1(handle, "close")
  7080. end
  7081. return list1(false, "Already loading " .. quoted1(fullPath))
  7082. else
  7083. if handle then
  7084. self1(handle, "close")
  7085. end
  7086. state["libs"]["paths"][path] = temp1
  7087. return list1(temp1)
  7088. end
  7089. elseif temp == true then
  7090. return list1(false, "Already loading " .. quoted1(path))
  7091. else
  7092. return list1(temp)
  7093. end
  7094. end
  7095. setupPrelude_21_1 = function(state, prelude)
  7096. if type1(prelude) ~= "library" then
  7097. error1(demandFailure1(nil, "(= (type prelude) \"library\")"))
  7098. end
  7099. state["prelude"] = prelude
  7100. local scope = child1(rootScope1)
  7101. state["root-scope"] = scope
  7102. local temp = prelude["scope"]["exported"]
  7103. local temp1, var = next1(temp)
  7104. while temp1 ~= nil do
  7105. import_21_1(scope, temp1, var)
  7106. temp1, var = next1(temp, temp1)
  7107. end
  7108. return nil
  7109. end
  7110. reload1 = function(compiler)
  7111. local cache, dirty, updatedLisp = compiler["libs"], {}, {}
  7112. local temp = cache["loaded"]
  7113. local forLimit = n1(temp)
  7114. local i = 1
  7115. while i <= forLimit do
  7116. local lib = temp[i]
  7117. local handle, path_27_ = tryHandle1(lib["path"])
  7118. if handle then
  7119. local newLines = gsub1(self1(handle, "read", "*a"), "\13\n?", "\n")
  7120. self1(handle, "close")
  7121. if neq_3f_1(newLines, concat2(lib["lisp-lines"], "\n")) then
  7122. updatedLisp[lib] = newLines
  7123. dirty[lib] = 1
  7124. end
  7125. else
  7126. error1(formatOutput_21_1(nil, "Cannot find " .. display1(lib["path"]) .. " (for module " .. display1(lib["name"]) .. ")"))
  7127. end
  7128. i = i + 1
  7129. end
  7130. while true do
  7131. local changed = false
  7132. local temp = cache["loaded"]
  7133. local forLimit = n1(temp)
  7134. local i = 1
  7135. while i <= forLimit do
  7136. local lib = temp[i]
  7137. local maxDepth, temp1 = dirty[lib] or 0, lib["depends"]
  7138. local temp2 = next1(temp1)
  7139. while temp2 ~= nil do
  7140. local depth = dirty[temp2]
  7141. if depth and depth >= maxDepth then
  7142. maxDepth = depth + 1
  7143. dirty[lib] = maxDepth
  7144. changed = true
  7145. end
  7146. temp2 = next1(temp1, temp2)
  7147. end
  7148. i = i + 1
  7149. end
  7150. if changed then
  7151. else
  7152. break
  7153. end
  7154. end
  7155. local reload
  7156. local xs, f = keys1(dirty), function(x, y)
  7157. return dirty[x] < dirty[y]
  7158. end
  7159. sort1(xs, f)
  7160. reload = xs
  7161. local forLimit = n1(reload)
  7162. local i = 1
  7163. while i <= forLimit do
  7164. local lib = reload[i]
  7165. local contents = updatedLisp[lib] or concat2(lib["lisp-lines"], "\n")
  7166. local lexed, range = lex1(compiler["log"], contents, lib["path"] .. ".lisp")
  7167. local parsed, oldScope = parse1(compiler["log"], lexed), lib["scope"]
  7168. local newScope, deps = scopeForLibrary1(oldScope["parent"], lib["name"], lib["unique-name"]), {}
  7169. self1(compiler["log"], "put-warning!", (formatOutput_21_1(nil, "" .. display1(lib["path"]) .. " or dependency has changed")))
  7170. if lib["depends"][compiler["prelude"]] then
  7171. deps[compiler["prelude"]] = true
  7172. end
  7173. local compiled = compile1(compiler, parsed, newScope, lib["path"], function(name)
  7174. local res = compiler["loader"](name)
  7175. local module = car1(res)
  7176. if module then
  7177. deps[module] = true
  7178. end
  7179. return res
  7180. end)
  7181. if string_3f_1(car1(compiled)) then
  7182. lib["docs"] = (constVal1(car1(compiled)))
  7183. removeNth_21_1(compiled, 1)
  7184. else
  7185. lib["docs"] = nil
  7186. end
  7187. lib["lisp-lines"] = (range["lines"])
  7188. lib["nodes"] = compiled
  7189. lib["scope"] = newScope
  7190. lib["depends"] = deps
  7191. if lib == compiler["prelude"] then
  7192. local rootScope = compiler["root-scope"]
  7193. local rootVars = rootScope["variables"]
  7194. local temp = next1(rootVars)
  7195. while temp ~= nil do
  7196. rootVars[temp] = nil
  7197. temp = next1(rootVars, temp)
  7198. end
  7199. local temp = newScope["exported"]
  7200. local temp1, var = next1(temp)
  7201. while temp1 ~= nil do
  7202. import_21_1(rootScope, temp1, var)
  7203. temp1, var = next1(temp, temp1)
  7204. end
  7205. end
  7206. local escaped, temp = compiler["compile-state"]["var-lookup"], oldScope["variables"]
  7207. local temp1, oldVar = next1(temp)
  7208. while temp1 ~= nil do
  7209. local esc = escaped[oldVar]
  7210. if esc then
  7211. local newVar = newScope["variables"][temp1]
  7212. if newVar then
  7213. escaped[newVar] = esc
  7214. end
  7215. end
  7216. temp1, oldVar = next1(temp, temp1)
  7217. end
  7218. local temp = oldScope["variables"]
  7219. local temp1, oldVar = next1(temp)
  7220. while temp1 ~= nil do
  7221. local newVar = newScope["variables"][temp1]
  7222. if newVar then
  7223. compiler[tostring1(oldVar)] = newVar
  7224. end
  7225. temp1, oldVar = next1(temp, temp1)
  7226. end
  7227. i = i + 1
  7228. end
  7229. return nil
  7230. end
  7231. formatRange2 = function(range)
  7232. return format1("%s:%s", range["name"], (function()
  7233. local pos = range["start"]
  7234. return pos["line"] .. ":" .. pos["column"]
  7235. end)())
  7236. end
  7237. sortVars_21_1 = function(list)
  7238. sort1(list, function(a, b)
  7239. return car1(a) < car1(b)
  7240. end)
  7241. return list
  7242. end
  7243. formatDefinition1 = function(var)
  7244. local temp = var["kind"]
  7245. if temp == "builtin" then
  7246. return "Builtin term"
  7247. elseif temp == "macro" then
  7248. return "Macro defined at " .. formatRange2(sourceRange1(var["node"]["source"]))
  7249. elseif temp == "native" then
  7250. return "Native defined at " .. formatRange2(sourceRange1(var["node"]["source"]))
  7251. elseif temp == "defined" then
  7252. return "Defined at " .. formatRange2(sourceRange1(var["node"]["source"]))
  7253. else
  7254. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"builtin\"`\n Tried: `\"macro\"`\n Tried: `\"native\"`\n Tried: `\"defined\"`")
  7255. end
  7256. end
  7257. formatSignature1 = function(name, var)
  7258. local sig = extractSignature1(var)
  7259. if sig == nil then
  7260. return name
  7261. else
  7262. return "(" .. concat2(cons1(name, sig), " ") .. ")"
  7263. end
  7264. end
  7265. formatLink1 = function(name, var, title)
  7266. local loc, sig = gsub1(stripExtension1((sourceRange1(var["node"]["source"])["name"])), "/", "."), extractSignature1(var)
  7267. local hash
  7268. if sig == nil then
  7269. hash = var["name"]
  7270. elseif empty_3f_1(sig) then
  7271. hash = var["name"]
  7272. else
  7273. hash = name .. " " .. concat2(sig, " ")
  7274. end
  7275. local titleq
  7276. if title then
  7277. titleq = " \"" .. title .. "\""
  7278. else
  7279. titleq = ""
  7280. end
  7281. return format1("[`%s`](%s.md#%s%s)", name, loc, gsub1(hash, "%A+", "-"), titleq)
  7282. end
  7283. writeDocstring1 = function(out, toks, scope)
  7284. local forLimit = n1(toks)
  7285. local i = 1
  7286. while i <= forLimit do
  7287. local tok = toks[i]
  7288. local ty = tok["kind"]
  7289. if ty == "text" then
  7290. append_21_1(out, tok["contents"])
  7291. elseif ty == "boldic" then
  7292. append_21_1(out, tok["contents"])
  7293. elseif ty == "bold" then
  7294. append_21_1(out, tok["contents"])
  7295. elseif ty == "italic" then
  7296. append_21_1(out, tok["contents"])
  7297. elseif ty == "arg" then
  7298. append_21_1(out, "`" .. tok["contents"] .. "`")
  7299. elseif ty == "mono" then
  7300. append_21_1(out, gsub1(tok["whole"], "^```(%S+)[^\n]*", "```%1"))
  7301. elseif ty == "link" then
  7302. local name = tok["contents"]
  7303. local ovar = lookup1(scope, name)
  7304. if ovar and ovar["node"] then
  7305. append_21_1(out, formatLink1(name, ovar))
  7306. else
  7307. append_21_1(out, format1("`%s`", name))
  7308. end
  7309. else
  7310. _error("unmatched item")
  7311. end
  7312. i = i + 1
  7313. end
  7314. return nil
  7315. end
  7316. exported1 = function(out, title, primary, vars, scope)
  7317. local documented, undocumented = {tag="list", n=0}, {tag="list", n=0}
  7318. iterPairs1(vars, function(name, var)
  7319. return push_21_1((function()
  7320. if var["doc"] then
  7321. return documented
  7322. else
  7323. return undocumented
  7324. end
  7325. end)(), list1(name, var))
  7326. end)
  7327. sortVars_21_1(documented)
  7328. sortVars_21_1(undocumented)
  7329. line_21_1(out, "---")
  7330. line_21_1(out, "title: " .. title)
  7331. line_21_1(out, "---")
  7332. line_21_1(out, "# " .. title)
  7333. if primary then
  7334. writeDocstring1(out, parseDocstring1(primary), scope)
  7335. line_21_1(out)
  7336. line_21_1(out, "", true)
  7337. end
  7338. local forLimit = n1(documented)
  7339. local i = 1
  7340. while i <= forLimit do
  7341. local entry = documented[i]
  7342. local name, var = car1(entry), nth1(entry, 2)
  7343. line_21_1(out, "## `" .. formatSignature1(name, var) .. "`")
  7344. line_21_1(out, "*" .. formatDefinition1(var) .. "*")
  7345. line_21_1(out, "", true)
  7346. if var["deprecated"] then
  7347. if string_3f_1(var["deprecated"]) then
  7348. append_21_1(out, format1(">**Warning:** %s is deprecated: ", name))
  7349. writeDocstring1(out, parseDocstring1(var["deprecated"]), var["scope"])
  7350. else
  7351. append_21_1(out, format1(">**Warning:** %s is deprecated.", name))
  7352. end
  7353. line_21_1(out)
  7354. line_21_1(out, "", true)
  7355. end
  7356. writeDocstring1(out, parseDocstring1(var["doc"]), var["scope"])
  7357. line_21_1(out)
  7358. line_21_1(out, "", true)
  7359. i = i + 1
  7360. end
  7361. if not empty_3f_1(undocumented) then
  7362. line_21_1(out, "## Undocumented symbols")
  7363. end
  7364. local forLimit = n1(undocumented)
  7365. local i = 1
  7366. while i <= forLimit do
  7367. local entry = undocumented[i]
  7368. local name, var = car1(entry), nth1(entry, 2)
  7369. line_21_1(out, " - `" .. formatSignature1(name, var) .. "` *" .. formatDefinition1(var) .. "*")
  7370. i = i + 1
  7371. end
  7372. return nil
  7373. end
  7374. index1 = function(out, libraries)
  7375. local variables, letters = {}, {}
  7376. local forLimit = n1(libraries)
  7377. local i = 1
  7378. while i <= forLimit do
  7379. local lib = libraries[i]
  7380. local temp = lib["scope"]["exported"]
  7381. local temp1, var = next1(temp)
  7382. while temp1 ~= nil do
  7383. local info = variables[var]
  7384. if not info then
  7385. info = {var=var, exported={tag="list", n=0}, defined=nil}
  7386. variables[var] = info
  7387. local letter = lower1(sub1(var["name"], 1, 1))
  7388. if not between_3f_1(letter, "a", "z") then
  7389. letter = "$"
  7390. end
  7391. local lookup = letters[letter]
  7392. if not lookup then
  7393. lookup = {tag="list", n=0}
  7394. letters[letter] = lookup
  7395. end
  7396. push_21_1(lookup, info)
  7397. end
  7398. if var["scope"] == lib["scope"] then
  7399. info["defined"] = lib
  7400. else
  7401. push_21_1(info["exported"], list1(temp1, lib))
  7402. end
  7403. temp1, var = next1(temp, temp1)
  7404. end
  7405. i = i + 1
  7406. end
  7407. local letterList = struct_2d3e_assoc1(letters)
  7408. sort1(letterList, function(a, b)
  7409. return car1(a) < car1(b)
  7410. end)
  7411. local forLimit = n1(letterList)
  7412. local i = 1
  7413. while i <= forLimit do
  7414. local xs, f = cadr1((letterList[i])), function(a, b)
  7415. return a["var"]["full-name"] < b["var"]["full-name"]
  7416. end
  7417. sort1(xs, f)
  7418. i = i + 1
  7419. end
  7420. line_21_1(out, "---")
  7421. line_21_1(out, "title: Symbol index")
  7422. line_21_1(out, "---")
  7423. line_21_1(out, "# Symbol index")
  7424. line_21_1(out, "", true)
  7425. line_21_1(out, "{:.sym-toc}")
  7426. local forLimit = n1(letterList)
  7427. local i = 1
  7428. while i <= forLimit do
  7429. local letter = letterList[i]
  7430. line_21_1(out, format1(" - [%s](#sym-%s)", car1(letter), (function()
  7431. if car1(letter) == "$" then
  7432. return "symbols"
  7433. else
  7434. return car1(letter)
  7435. end
  7436. end)()))
  7437. i = i + 1
  7438. end
  7439. line_21_1(out)
  7440. line_21_1(out, "", true)
  7441. line_21_1(out, "{:.sym-table}")
  7442. line_21_1(out, "| | Symbol | Defined in |")
  7443. line_21_1(out, "| - | ------ | ---------- |")
  7444. local forLimit = n1(letterList)
  7445. local i = 1
  7446. while i <= forLimit do
  7447. local letter = letterList[i]
  7448. line_21_1(out, format1("| <strong id=\"sym-%s\">%s</strong> | |", (function()
  7449. if car1(letter) == "$" then
  7450. return "symbols"
  7451. else
  7452. return car1(letter)
  7453. end
  7454. end)(), car1(letter)))
  7455. local temp = cadr1(letter)
  7456. local forLimit1 = n1(temp)
  7457. local i1 = 1
  7458. while i1 <= forLimit1 do
  7459. local info = temp[i1]
  7460. local var, defined = info["var"], info["defined"]
  7461. local range = sourceRange1(var["node"]["source"])
  7462. append_21_1(out, "| |")
  7463. append_21_1(out, formatLink1(var["name"], var, formatDefinition1(var)))
  7464. local doc = var["doc"]
  7465. if doc then
  7466. append_21_1(out, ": ")
  7467. writeDocstring1(out, extractSummary1(parseDocstring1(doc)))
  7468. end
  7469. append_21_1(out, "|")
  7470. local name
  7471. if defined then
  7472. name = defined["name"]
  7473. else
  7474. name = range["name"]
  7475. end
  7476. local path = gsub1(stripExtension1((function()
  7477. if defined then
  7478. return defined["path"]
  7479. else
  7480. return range["name"]
  7481. end
  7482. end)()), "/", ".")
  7483. if empty_3f_1(info["exported"]) then
  7484. append_21_1(out, format1("[%s](%s.md)", name, path))
  7485. else
  7486. append_21_1(out, format1("[%s](%s.md \"Also exported from %s\")", name, path, concat2(sort2(nub1(map2(function(x)
  7487. return cadr1(x)["name"]
  7488. end, info["exported"]))), ", ")))
  7489. end
  7490. line_21_1(out, "|")
  7491. i1 = i1 + 1
  7492. end
  7493. i = i + 1
  7494. end
  7495. return nil
  7496. end
  7497. docs1 = function(compiler, args)
  7498. if empty_3f_1(args["input"]) then
  7499. self1(compiler["log"], "put-error!", "No inputs to generate documentation for.")
  7500. exit_21_1(1)
  7501. end
  7502. local temp = args["input"]
  7503. local forLimit = n1(temp)
  7504. local i = 1
  7505. while i <= forLimit do
  7506. local path = temp[i]
  7507. local lib, writer = compiler["libs"]["paths"][path], {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  7508. exported1(writer, lib["name"], lib["docs"], lib["scope"]["exported"], lib["scope"])
  7509. local handle = open1(args["docs"] .. "/" .. gsub1(stripExtension1(path), "/", ".") .. ".md", "w")
  7510. self1(handle, "write", concat2(writer["out"]))
  7511. self1(handle, "close")
  7512. i = i + 1
  7513. end
  7514. local writer = {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  7515. index1(writer, map2(function(temp)
  7516. return compiler["libs"]["paths"][temp]
  7517. end, args["input"]))
  7518. local handle = open1(args["docs"] .. "/index.md", "w")
  7519. self1(handle, "write", concat2(writer["out"]))
  7520. return self1(handle, "close")
  7521. end
  7522. task1 = {name="docs", setup=function(spec)
  7523. return addArgument_21_1(spec, {tag="list", n=1, "--docs"}, "help", "Specify the folder to emit documentation to.", "cat", "out", "default", nil, "narg", 1)
  7524. end, pred=function(args)
  7525. return nil ~= args["docs"]
  7526. end, run=docs1}
  7527. local home = getenv1 and (getenv1("HOME") or (getenv1("USERPROFILE") or (getenv1("HOMEDRIVE") or getenv1("HOMEPATH"))))
  7528. if home then
  7529. historyPath1 = home .. "/.urn_history"
  7530. else
  7531. historyPath1 = ".urn_history"
  7532. end
  7533. readDumb1 = function(prompt)
  7534. write1(prompt)
  7535. flush1()
  7536. return read1("*l")
  7537. end
  7538. local read, providers = nil, list1(function()
  7539. local rlOk, readline = pcall1(require1, "urn.readline")
  7540. if rlOk then
  7541. return readline
  7542. else
  7543. return nil
  7544. end
  7545. end, function()
  7546. local ffiOk, ffi = pcall1(require1, "ffi")
  7547. if ffiOk then
  7548. local ok, readline = pcall1(ffi["load"], "readline")
  7549. if ok then
  7550. ffi["cdef"]("void* malloc(size_t bytes); // Required to allocate strings for completions\nvoid free(void *); // Required to free strings returned by readline\nchar *readline (const char *prompt); // Read a line with the given prompt\nconst char * rl_readline_name; // Set the program name\n\n// History manipulation\nvoid using_history();\nvoid add_history(const char *line);\nvoid read_history(const char *filename);\n\n// Hooks\ntypedef int rl_hook_func_t (void);\nrl_hook_func_t *rl_startup_hook;\n\n// Completion\ntypedef char *rl_compentry_func_t (const char *, int);\ntypedef char **rl_completion_func_t (const char *, int, int);\nchar **rl_completion_matches (const char *text, rl_compentry_func_t *entry_func);\nint rl_attempted_completion_over;\nchar * rl_line_buffer;\nconst char* rl_basic_word_break_characters;\nrl_completion_func_t * rl_attempted_completion_function;\n\nint rl_insert_text (const char *text);")
  7551. local currentInitial, previous, currentCompleter = "", "", nil
  7552. readline["rl_readline_name"] = "urn"
  7553. readline["rl_startup_hook"] = function()
  7554. if n1(currentInitial) > 0 then
  7555. readline["rl_insert_text"](currentInitial)
  7556. end
  7557. return 0
  7558. end
  7559. readline["using_history"]()
  7560. readline["read_history"](historyPath1)
  7561. readline["rl_basic_word_break_characters"] = "\n \9;()[]{},@`'"
  7562. readline["rl_attempted_completion_function"] = function(str, start, finish)
  7563. readline["rl_attempted_completion_over"] = 1
  7564. local results, resultsIdx = nil, 0
  7565. return readline["rl_completion_matches"](str, function(str1, idx)
  7566. if idx == 0 then
  7567. if currentCompleter then
  7568. results = currentCompleter(ffi["string"](readline["rl_line_buffer"], finish))
  7569. else
  7570. results = {tag="list", n=0}
  7571. end
  7572. end
  7573. resultsIdx = resultsIdx + 1
  7574. local resPartial = nth1(results, resultsIdx)
  7575. if resPartial then
  7576. local resStr = ffi["string"](str1) .. resPartial
  7577. local resBuf = ffi["C"]["malloc"](n1(resStr) + 1)
  7578. ffi["copy"](resBuf, resStr, n1(resStr) + 1)
  7579. return resBuf
  7580. else
  7581. return nil
  7582. end
  7583. end)
  7584. end
  7585. return function(prompt, initial, complete)
  7586. currentInitial = initial or ""
  7587. currentCompleter = complete
  7588. prompt = gsub1(prompt, "(\27%[%A*%a)", "\1%1\2")
  7589. local res = readline["readline"](prompt)
  7590. if res == nil then
  7591. return nil
  7592. else
  7593. local str = ffi["string"](res)
  7594. if find1(str, "%S") and previous ~= str then
  7595. previous = str
  7596. readline["add_history"](res)
  7597. local out = open1(historyPath1, "a")
  7598. if out then
  7599. self1(out, "write", str, "\n")
  7600. self1(out, "close")
  7601. end
  7602. end
  7603. ffi["C"]["free"](res)
  7604. return str
  7605. end
  7606. end
  7607. else
  7608. return nil
  7609. end
  7610. else
  7611. return nil
  7612. end
  7613. end, function()
  7614. local readlineOk, readline = pcall1(require1, "readline")
  7615. if readlineOk then
  7616. local previous = nil
  7617. readline["set_options"]({histfile=historyPath1, completion=false})
  7618. return function(prompt, initial, complete)
  7619. prompt = gsub1(prompt, "(\27%[%A*%a)", "\1%1\2")
  7620. local res = readline["readline"](prompt)
  7621. if res and (find1(res, "%S") and previous ~= res) then
  7622. previous = res
  7623. local out = open1(historyPath1, "a")
  7624. if out then
  7625. self1(out, "write", res, "\n")
  7626. self1(out, "close")
  7627. end
  7628. end
  7629. return res
  7630. end
  7631. else
  7632. return nil
  7633. end
  7634. end, function()
  7635. local linenoiseOk, linenoise = pcall1(require1, "linenoise")
  7636. if linenoiseOk then
  7637. local previous = nil
  7638. linenoise["historysetmaxlen"](1000)
  7639. linenoise["historyload"](historyPath1)
  7640. return function(prompt, initial, complete)
  7641. prompt = gsub1(prompt, "(\27%[%A*%a)", "")
  7642. if complete then
  7643. linenoise["setcompletion"](function(obj, line)
  7644. local temp = complete(line)
  7645. local forLimit = n1(temp)
  7646. local i = 1
  7647. while i <= forLimit do
  7648. local completion = temp[i]
  7649. linenoise["addcompletion"](obj, line .. completion .. " ")
  7650. i = i + 1
  7651. end
  7652. return nil
  7653. end)
  7654. else
  7655. linenoise["setcompletion"](nil)
  7656. end
  7657. local res = linenoise["linenoise"](prompt)
  7658. if res and (find1(res, "%S") and previous ~= res) then
  7659. previous = res
  7660. linenoise["historyadd"](res)
  7661. local out = open1(historyPath1, "a")
  7662. if out then
  7663. self1(out, "write", res, "\n")
  7664. self1(out, "close")
  7665. end
  7666. end
  7667. return res
  7668. end
  7669. else
  7670. return nil
  7671. end
  7672. end, function()
  7673. return readDumb1
  7674. end)
  7675. readLine_21_1 = function(prompt, initial, complete)
  7676. if not read then
  7677. local i = 1
  7678. while true do
  7679. local provider = nth1(providers, i)()
  7680. if provider then
  7681. read = provider
  7682. break
  7683. else
  7684. i = i + 1
  7685. end
  7686. end
  7687. end
  7688. return read(prompt, initial, complete)
  7689. end
  7690. requiresInput1 = function(str)
  7691. local temp = list1(pcall1(function()
  7692. return parse1(void1, lex1(void1, str, "<stdin>", true), true)
  7693. end))
  7694. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == true and true))) then
  7695. return false
  7696. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and type_23_1((nth1(temp, 2))) == "table"))) then
  7697. if nth1(temp, 2)["context"] then
  7698. return true
  7699. else
  7700. return false
  7701. end
  7702. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  7703. local x = nth1(temp, 2)
  7704. return nil
  7705. else
  7706. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(true _)`\n Tried: `(false (table? @ ?x))`\n Tried: `(false ?x)`")
  7707. end
  7708. end
  7709. getIndent1 = function(str)
  7710. local toks
  7711. local temp = list1(pcall1(lex1, void1, str, "<stdin>", true))
  7712. if type1(temp) == "list" and (n1(temp) >= 3 and (n1(temp) <= 3 and (nth1(temp, 1) == true and true))) then
  7713. toks = (nth1(temp, 2))
  7714. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and type_23_1((nth1(temp, 2))) == "table"))) then
  7715. toks = nth1(temp, 2)["tokens"] or {tag="list", n=0}
  7716. else
  7717. toks = error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(true ?x _)`\n Tried: `(false (table? @ ?x))`")
  7718. end
  7719. local stack = {tag="list", n=1, 1}
  7720. local forLimit = n1(toks)
  7721. local i = 1
  7722. while i <= forLimit do
  7723. local tok = toks[i]
  7724. local temp = type1(tok)
  7725. if temp == "open" then
  7726. push_21_1(stack, tok["source"]["start"]["column"] + 2)
  7727. elseif temp == "close" then
  7728. popLast_21_1(stack)
  7729. end
  7730. i = i + 1
  7731. end
  7732. return rep1(" ", last1(stack) - 1)
  7733. end
  7734. getComplete1 = function(str, scope)
  7735. local temp = list1(pcall1(lex1, void1, str, "<stdin>", true))
  7736. if type1(temp) == "list" and (n1(temp) >= 3 and (n1(temp) <= 3 and (nth1(temp, 1) == true and true))) then
  7737. local toks = nth1(temp, 2)
  7738. local last = nth1(toks, n1(toks) - 1)
  7739. local contents
  7740. if last == nil then
  7741. contents = ""
  7742. elseif last["source"]["finish"]["offset"] < n1(str) then
  7743. contents = ""
  7744. elseif type1(last) == "symbol" then
  7745. contents = symbol_2d3e_string1(last)
  7746. else
  7747. contents = nil
  7748. end
  7749. if contents then
  7750. local visited, vars = {}, {tag="list", n=0}
  7751. local scope1 = scope
  7752. while not ((scope1 == nil)) do
  7753. local temp1 = scope1["variables"]
  7754. local temp2, _5f_ = next1(temp1)
  7755. while temp2 ~= nil do
  7756. if sub1(temp2, 1, #contents) == contents and not visited[temp2] then
  7757. visited[temp2] = true
  7758. push_21_1(vars, sub1(temp2, n1(contents) + 1))
  7759. end
  7760. temp2, _5f_ = next1(temp1, temp2)
  7761. end
  7762. scope1 = scope1["parent"]
  7763. end
  7764. sort1(vars, nil)
  7765. return vars
  7766. else
  7767. return {tag="list", n=0}
  7768. end
  7769. else
  7770. return {tag="list", n=0}
  7771. end
  7772. end
  7773. if getenv1 then
  7774. local clrs = getenv1("URN_COLOURS")
  7775. if clrs then
  7776. replColourScheme1 = read2(clrs) or nil
  7777. else
  7778. replColourScheme1 = nil
  7779. end
  7780. else
  7781. replColourScheme1 = nil
  7782. end
  7783. colourFor1 = function(elem)
  7784. if assoc_3f_1(replColourScheme1, {tag="symbol", contents=elem}) then
  7785. return constVal1(assoc1(replColourScheme1, {tag="symbol", contents=elem}))
  7786. elseif elem == "text" then
  7787. return "0"
  7788. elseif elem == "arg" then
  7789. return "36"
  7790. elseif elem == "mono" then
  7791. return "1;37"
  7792. elseif elem == "bold" then
  7793. return "1"
  7794. elseif elem == "italic" then
  7795. return "3"
  7796. elseif elem == "link" then
  7797. return "1;34"
  7798. elseif elem == "comment" then
  7799. return "1;30"
  7800. elseif elem == "string" then
  7801. return "32"
  7802. elseif elem == "number" then
  7803. return "0"
  7804. elseif elem == "key" then
  7805. return "36"
  7806. elseif elem == "symbol" then
  7807. return "0"
  7808. elseif elem == "keyword" then
  7809. return "35"
  7810. elseif elem == "operator" then
  7811. return "0"
  7812. else
  7813. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(elem) .. ", but none matched.\n" .. " Tried: `\"text\"`\n Tried: `\"arg\"`\n Tried: `\"mono\"`\n Tried: `\"bold\"`\n Tried: `\"italic\"`\n Tried: `\"link\"`\n Tried: `\"comment\"`\n Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"keyword\"`\n Tried: `\"operator\"`")
  7814. end
  7815. end
  7816. tokenMapping1 = {string="string", interpolate="string", number="number", key="key", symbol="symbol", open="operator", close="operator", ["open-struct"]="operator", ["close-struct"]="operator", quote="operator", ["quasi-quote"]="operator", ["syntax-quote"]="operator", unquote="operator", ["unquote-splice"]="operator"}
  7817. keywords2 = createLookup1({tag="list", n=33, "define", "define-macro", "define-native", "lambda", "set!", "cond", "import", "struct-literal", "quote", "syntax-quote", "unquote", "unquote-splice", "defun", "defmacro", "car", "cdr", "list", "cons", "progn", "if", "when", "unless", "let", "let*", "with", "not", "gensym", "for", "while", "and", "or", "loop", "case"})
  7818. printDocs_21_1 = function(str)
  7819. local docs = parseDocstring1(str)
  7820. local forLimit = n1(docs)
  7821. local i = 1
  7822. while i <= forLimit do
  7823. local tok = docs[i]
  7824. local tag = tok["kind"]
  7825. if tag == "bolic" then
  7826. write1(coloured1(colourFor1("bold"), coloured1(colourFor1("italic"), tok["contents"])))
  7827. else
  7828. write1(coloured1(colourFor1(tag), tok["contents"]))
  7829. end
  7830. i = i + 1
  7831. end
  7832. return print1()
  7833. end
  7834. execCommand1 = function(compiler, scope, args)
  7835. local logger, command = compiler["log"], car1(args)
  7836. if command == "help" or command == "h" then
  7837. return print1("REPL commands:\n[:d]oc NAME Get documentation about a symbol\n:module NAME Display a loaded module's docs and definitions.\n[:r]eload Reload all modules which have changed.\n:scope Print out all variables in the scope\n[:s]earch QUERY Search the current scope for symbols and documentation containing a string.\n[:v]iew NAME Display the definition of a symbol.\n[:q]uit Exit the REPL cleanly.")
  7838. elseif command == "doc" or command == "d" then
  7839. local name = nth1(args, 2)
  7840. if name then
  7841. local var = lookup1(scope, name)
  7842. if var == nil then
  7843. return self1(logger, "put-error!", ("Cannot find '" .. name .. "'"))
  7844. else
  7845. local sig, name2 = extractSignature1(var), var["full-name"]
  7846. if sig then
  7847. name2 = "(" .. concat2(cons1(name2, sig), " ") .. ")"
  7848. end
  7849. print1(coloured1("36;1", name2))
  7850. local docs = var["doc"]
  7851. if docs then
  7852. return printDocs_21_1(docs)
  7853. else
  7854. return self1(logger, "put-error!", ("No documentation for '" .. name2 .. "'"))
  7855. end
  7856. end
  7857. else
  7858. return self1(logger, "put-error!", ":doc <variable>")
  7859. end
  7860. elseif command == "module" then
  7861. local name = nth1(args, 2)
  7862. if name then
  7863. local mod = compiler["libs"]["names"][name]
  7864. if mod == nil then
  7865. return self1(logger, "put-error!", ("Cannot find '" .. name .. "'"))
  7866. else
  7867. print1(coloured1("36;1", mod["name"]))
  7868. print1("Located at " .. mod["path"])
  7869. local docs = mod["docs"]
  7870. if docs then
  7871. print1()
  7872. printDocs_21_1(docs)
  7873. end
  7874. local vars
  7875. local xs = (keys1((mod["scope"]["exported"])))
  7876. sort1(xs, nil)
  7877. vars = xs
  7878. if not empty_3f_1(vars) then
  7879. print1()
  7880. print1(coloured1("32;1", "Exported symbols"))
  7881. print1(concat2(vars, " "))
  7882. end
  7883. local imports
  7884. local xs = (map2(libraryName1, (keys1((mod["depends"])))))
  7885. sort1(xs, nil)
  7886. imports = xs
  7887. if empty_3f_1(imports) then
  7888. return nil
  7889. else
  7890. print1()
  7891. print1(coloured1("32;1", "Imports"))
  7892. return print1(concat2(imports, " "))
  7893. end
  7894. end
  7895. else
  7896. return self1(logger, "put-error!", ":module <variable>")
  7897. end
  7898. elseif command == "search" or command == "s" then
  7899. if n1(args) > 1 then
  7900. local keywords, nameResults, docsResults, vars, varsSet, current = map2(lower1, slicingView1(args, 1)), {tag="list", n=0}, {tag="list", n=0}, {tag="list", n=0}, {}, scope
  7901. while current do
  7902. local temp = current["variables"]
  7903. local temp1, var = next1(temp)
  7904. while temp1 ~= nil do
  7905. if not varsSet[temp1] then
  7906. push_21_1(vars, temp1)
  7907. varsSet[temp1] = true
  7908. end
  7909. temp1, var = next1(temp, temp1)
  7910. end
  7911. current = current["parent"]
  7912. end
  7913. local forLimit = n1(vars)
  7914. local i = 1
  7915. while i <= forLimit do
  7916. local var = vars[i]
  7917. local forLimit1 = n1(keywords)
  7918. local i1 = 1
  7919. while i1 <= forLimit1 do
  7920. if find1(var, (keywords[i1])) then
  7921. push_21_1(nameResults, var)
  7922. end
  7923. i1 = i1 + 1
  7924. end
  7925. local docVar = lookup1(scope, var)
  7926. if docVar then
  7927. local tempDocs = docVar["doc"]
  7928. if tempDocs then
  7929. local docs = lower1(tempDocs)
  7930. if docs then
  7931. local keywordsFound = 0
  7932. if keywordsFound then
  7933. local forLimit1 = n1(keywords)
  7934. local i1 = 1
  7935. while i1 <= forLimit1 do
  7936. if find1(docs, (keywords[i1])) then
  7937. keywordsFound = keywordsFound + 1
  7938. end
  7939. i1 = i1 + 1
  7940. end
  7941. if eq_3f_1(keywordsFound, n1(keywords)) then
  7942. push_21_1(docsResults, var)
  7943. end
  7944. end
  7945. end
  7946. end
  7947. end
  7948. i = i + 1
  7949. end
  7950. if empty_3f_1(nameResults) and empty_3f_1(docsResults) then
  7951. return self1(logger, "put-error!", "No results")
  7952. else
  7953. if not empty_3f_1(nameResults) then
  7954. print1(coloured1("32;1", "Search by function name:"))
  7955. if n1(nameResults) > 20 then
  7956. print1(concat2(slice1(nameResults, 1, min1(20, n1(nameResults))), " ") .. " ...")
  7957. else
  7958. print1(concat2(nameResults, " "))
  7959. end
  7960. end
  7961. if not empty_3f_1(docsResults) then
  7962. print1(coloured1("32;1", "Search by function docs:"))
  7963. if n1(docsResults) > 20 then
  7964. return print1(concat2(slice1(docsResults, 1, min1(20, n1(docsResults))), " ") .. " ...")
  7965. else
  7966. return print1(concat2(docsResults, " "))
  7967. end
  7968. else
  7969. return nil
  7970. end
  7971. end
  7972. else
  7973. return self1(logger, "put-error!", ":search <keywords>")
  7974. end
  7975. elseif command == "scope" then
  7976. local vars, varsSet, current = {tag="list", n=0}, {}, scope
  7977. while current do
  7978. local temp = current["variables"]
  7979. local temp1, var = next1(temp)
  7980. while temp1 ~= nil do
  7981. if not varsSet[temp1] then
  7982. push_21_1(vars, temp1)
  7983. varsSet[temp1] = true
  7984. end
  7985. temp1, var = next1(temp, temp1)
  7986. end
  7987. current = current["parent"]
  7988. end
  7989. sort1(vars, nil)
  7990. return print1(concat2(vars, " "))
  7991. elseif command == "view" or command == "v" then
  7992. local name = nth1(args, 2)
  7993. if name then
  7994. local var = lookup1(scope, name)
  7995. if var ~= nil then
  7996. local node = var["node"]
  7997. local range = node and sourceFullRange1(node["source"])
  7998. if range ~= nil then
  7999. local lines, start, finish, buffer = range["lines"], range["start"], range["finish"], {tag="list", n=0}
  8000. local forStart, forLimit = start["line"], finish["line"]
  8001. local i = forStart
  8002. while i <= forLimit do
  8003. push_21_1(buffer, sub1(lines[i], (function()
  8004. if i == start["line"] then
  8005. return start["column"]
  8006. else
  8007. return 1
  8008. end
  8009. end)(), (function()
  8010. if i == finish["line"] then
  8011. return finish["column"]
  8012. else
  8013. return -1
  8014. end
  8015. end)()))
  8016. i = i + 1
  8017. end
  8018. local contents, previous = concat2(buffer, "\n"), 0
  8019. local temp = lex1(void1, contents, "stdin")
  8020. local forLimit = n1(temp)
  8021. local i = 1
  8022. while i <= forLimit do
  8023. local tok = temp[i]
  8024. local start1 = tok["source"]["start"]["offset"]
  8025. if start1 ~= previous then
  8026. write1(coloured1(colourFor1("comment"), sub1(contents, previous, start1 - 1)))
  8027. end
  8028. local tag = type1(tok)
  8029. if tag ~= "eof" then
  8030. if tag == "symbol" and keywords2[tok["contents"]] then
  8031. write1(coloured1(colourFor1("keyword"), tok["contents"]))
  8032. else
  8033. write1(coloured1(colourFor1(tokenMapping1[type1(tok)]), tok["contents"]))
  8034. end
  8035. end
  8036. previous = tok["source"]["finish"]["offset"] + 1
  8037. i = i + 1
  8038. end
  8039. return write1("\n")
  8040. else
  8041. return self1(logger, "put-error!", ("Cannot extract source code for " .. quoted1(name)))
  8042. end
  8043. else
  8044. return self1(logger, "put-error!", ("Cannot find " .. quoted1(name)))
  8045. end
  8046. else
  8047. return self1(logger, "put-error!", ":view <variable>")
  8048. end
  8049. elseif command == "reload" or command == "r" then
  8050. return reload1(compiler)
  8051. elseif command == "quit" or command == "q" then
  8052. print1("Goodbye.")
  8053. return exit1(0)
  8054. else
  8055. return self1(logger, "put-error!", ("Unknown command '" .. command .. "'"))
  8056. end
  8057. end
  8058. execString1 = function(compiler, scope, string)
  8059. local logger = compiler["log"]
  8060. local state = cadr1(list1(compile1(compiler, parse1(logger, (lex1(logger, string, "<stdin>"))), scope)))
  8061. if n1(state) > 0 then
  8062. local current = 0
  8063. local exec, compileState, global, logger1, run = create2(function()
  8064. local forLimit = n1(state)
  8065. local i = 1
  8066. while i <= forLimit do
  8067. current = state[i]
  8068. get_21_1(current)
  8069. i = i + 1
  8070. end
  8071. return nil
  8072. end), compiler["compile-state"], compiler["global"], compiler["log"], true
  8073. while run do
  8074. local res = list1(resume1(exec))
  8075. if not car1(res) then
  8076. self1(logger1, "put-error!", (cadr1(res)))
  8077. run = false
  8078. elseif status1(exec) == "dead" then
  8079. local lvl = get_21_1(last1(state))
  8080. local prettyFun = pretty1
  8081. local prettyVar = lookup1(scope, "pretty")
  8082. if prettyVar then
  8083. prettyFun = get_21_1(compiler["states"][prettyVar])
  8084. end
  8085. print1("out = " .. coloured1("36;1", prettyFun(lvl)))
  8086. global[pushEscapeVar_21_1(add_21_1(scope, "out", "defined", lvl), compileState)] = lvl
  8087. run = false
  8088. else
  8089. local states = cadr1(res)["states"]
  8090. local latest, co, task = car1(states), create2(executeStates1), nil
  8091. while run and status1(co) ~= "dead" do
  8092. compiler["active-node"] = latest["node"]
  8093. compiler["active-scope"] = latest["scope"]
  8094. local res1
  8095. if task then
  8096. res1 = list1(resume1(co))
  8097. else
  8098. res1 = list1(resume1(co, compileState, states, global))
  8099. end
  8100. compiler["active-node"] = nil
  8101. compiler["active-scope"] = nil
  8102. if type1(res1) == "list" and (n1(res1) >= 2 and (n1(res1) <= 2 and (nth1(res1, 1) == false and true))) then
  8103. error1(nth1(res1, 2), 0)
  8104. elseif type1(res1) == "list" and (n1(res1) >= 1 and (n1(res1) <= 1 and nth1(res1, 1) == true)) then
  8105. elseif type1(res1) == "list" and (n1(res1) >= 2 and (n1(res1) <= 2 and (nth1(res1, 1) == true and true))) then
  8106. local arg = nth1(res1, 2)
  8107. if status1(co) ~= "dead" then
  8108. task = arg
  8109. local temp = type1(task)
  8110. if temp == "execute" then
  8111. executeStates1(compileState, task["states"], global)
  8112. else
  8113. local _ = "Cannot handle " .. temp
  8114. end
  8115. end
  8116. else
  8117. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(res1) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true)`\n Tried: `(true ?arg)`")
  8118. end
  8119. end
  8120. end
  8121. end
  8122. return nil
  8123. else
  8124. return nil
  8125. end
  8126. end
  8127. repl1 = function(compiler, args)
  8128. local scope, logger, buffer, running = child1(compiler["root-scope"], "top-level"), compiler["log"], "", true
  8129. local read_21_
  8130. if args["read-dumb"] then
  8131. read_21_ = readDumb1
  8132. else
  8133. read_21_ = readLine_21_1
  8134. end
  8135. local temp = args["input"]
  8136. local forLimit = n1(temp)
  8137. local i = 1
  8138. while i <= forLimit do
  8139. local library = car1(pathLoader1(compiler, (temp[i])))
  8140. local temp1 = library["scope"]["exported"]
  8141. local temp2, var = next1(temp1)
  8142. while temp2 ~= nil do
  8143. if scope["variables"][temp2] then
  8144. import_21_1(scope, library["name"] .. "/" .. temp2, var)
  8145. else
  8146. import_21_1(scope, temp2, var)
  8147. end
  8148. temp2, var = next1(temp1, temp2)
  8149. end
  8150. i = i + 1
  8151. end
  8152. while running do
  8153. local line = read_21_(coloured1("32;1", (function()
  8154. if empty_3f_1(buffer) then
  8155. return "> "
  8156. else
  8157. return ". "
  8158. end
  8159. end)()), getIndent1(buffer), function(x)
  8160. return getComplete1(buffer .. x, scope)
  8161. end)
  8162. if not line and empty_3f_1(buffer) then
  8163. running = false
  8164. else
  8165. local data
  8166. if line then
  8167. data = buffer .. line .. "\n"
  8168. else
  8169. data = buffer
  8170. end
  8171. if sub1(data, 1, 1) == ":" then
  8172. buffer = ""
  8173. execCommand1(compiler, scope, map2(trim1, split1(sub1(data, 2), " ")))
  8174. elseif line and (n1(line) > 0 and requiresInput1(data)) then
  8175. buffer = data
  8176. else
  8177. buffer = ""
  8178. scope = child1(scope, "top-level")
  8179. local res = list1(pcall1(execString1, compiler, scope, data))
  8180. compiler["active-node"] = nil
  8181. compiler["active-scope"] = nil
  8182. if not (car1(res) or compilerError_3f_1(cadr1(res))) then
  8183. self1(logger, "put-error!", (cadr1(res)))
  8184. end
  8185. end
  8186. end
  8187. end
  8188. return nil
  8189. end
  8190. exec1 = function(compiler)
  8191. local data, scope, logger = read1("*a"), compiler["root-scope"], compiler["log"]
  8192. local res = list1(pcall1(execString1, compiler, scope, data))
  8193. if not (car1(res) or compilerError_3f_1(cadr1(res))) then
  8194. self1(logger, "put-error!", (cadr1(res)))
  8195. end
  8196. return exit1(0)
  8197. end
  8198. replTask1 = {name="repl", setup=function(spec)
  8199. addArgument_21_1(spec, {tag="list", n=1, "--repl"}, "help", "Start an interactive session.")
  8200. return addArgument_21_1(spec, {tag="list", n=1, "--read-dumb"}, "help", "Disable fancy readline input.")
  8201. end, pred=function(args)
  8202. return args["repl"]
  8203. end, run=repl1}
  8204. execTask1 = {name="exec", setup=function(spec)
  8205. return addArgument_21_1(spec, {tag="list", n=1, "--exec"}, "help", "Execute a program from stdin without compiling it. This acts as if it were input in one go via the REPL.")
  8206. end, pred=function(args)
  8207. return args["exec"]
  8208. end, run=exec1}
  8209. dotQuote1 = function(prefix, name)
  8210. if find1(name, "^[%w_][%d%w_]*$") then
  8211. if string_3f_1(prefix) then
  8212. return prefix .. "." .. name
  8213. else
  8214. return name
  8215. end
  8216. elseif string_3f_1(prefix) then
  8217. return prefix .. "[" .. quoted1(name) .. "]"
  8218. else
  8219. return "_ENV[" .. quoted1(name) .. "]"
  8220. end
  8221. end
  8222. genNative1 = function(compiler, args)
  8223. if n1(args["input"]) ~= 1 then
  8224. self1(compiler["log"], "put-error!", "Expected just one input")
  8225. exit_21_1(1)
  8226. end
  8227. local prefix = args["gen-native"]
  8228. local lib
  8229. local cache, path = compiler["libs"], last1(args["input"])
  8230. lib = cache["paths"][path]
  8231. local maxName, maxQuot, natives = 0, 0, {tag="list", n=0}
  8232. local temp = lib["nodes"]
  8233. local forLimit = n1(temp)
  8234. local i = 1
  8235. while i <= forLimit do
  8236. local node = temp[i]
  8237. if type1(node) == "list" and (type1((car1(node))) == "symbol" and car1(node)["contents"] == "define-native") then
  8238. local name = nth1(node, 2)["contents"]
  8239. push_21_1(natives, name)
  8240. maxName = max1(maxName, n1(quoted1(name)))
  8241. maxQuot = max1(maxQuot, n1(quoted1(dotQuote1(prefix, name))))
  8242. end
  8243. i = i + 1
  8244. end
  8245. sort1(natives, nil)
  8246. local handle, format = open1(lib["path"] .. ".meta.lua", "w"), " [%-" .. tostring1(maxName + 3) .. "s { tag = \"var\", contents = %-" .. tostring1(maxQuot + 1) .. "s },\n"
  8247. if not handle then
  8248. self1(compiler["log"], "put-error!", ("Cannot write to " .. lib["path"] .. ".meta.lua"))
  8249. exit_21_1(1)
  8250. end
  8251. self1(handle, "write", "return {\n")
  8252. local forLimit = n1(natives)
  8253. local i = 1
  8254. while i <= forLimit do
  8255. local native = natives[i]
  8256. self1(handle, "write", format1(format, quoted1(native) .. "] =", quoted1(dotQuote1(prefix, native)) .. ","))
  8257. i = i + 1
  8258. end
  8259. self1(handle, "write", "}\n")
  8260. return self1(handle, "close")
  8261. end
  8262. task2 = {name="gen-native", setup=function(spec)
  8263. return addArgument_21_1(spec, {tag="list", n=1, "--gen-native"}, "help", "Generate native bindings for a file", "var", "PREFIX", "narg", "?")
  8264. end, pred=function(args)
  8265. return args["gen-native"]
  8266. end, run=genNative1}
  8267. profileCalls1 = function(fn, mappings)
  8268. local stats, callStack = {}, {tag="list", n=0}
  8269. sethook1(function(action)
  8270. local info, start = getinfo1(2, "Sn"), clock1()
  8271. if action == "call" then
  8272. local previous = nth1(callStack, n1(callStack))
  8273. if previous then
  8274. previous["sum"] = previous["sum"] + (start - previous["inner-start"])
  8275. end
  8276. end
  8277. if action ~= "call" then
  8278. if not empty_3f_1(callStack) then
  8279. local current = popLast_21_1(callStack)
  8280. local hash = current["source"] .. current["linedefined"]
  8281. local entry = stats[hash]
  8282. if not entry then
  8283. entry = {source=current["source"], ["short-src"]=current["short_src"], line=current["linedefined"], name=current["name"], calls=0, ["total-time"]=0, ["inner-time"]=0}
  8284. stats[hash] = entry
  8285. end
  8286. entry["calls"] = 1 + entry["calls"]
  8287. entry["total-time"] = entry["total-time"] + (start - current["total-start"])
  8288. entry["inner-time"] = entry["inner-time"] + (current["sum"] + (start - current["inner-start"]))
  8289. end
  8290. end
  8291. if action ~= "return" then
  8292. info["total-start"] = start
  8293. info["inner-start"] = start
  8294. info["sum"] = 0
  8295. push_21_1(callStack, info)
  8296. end
  8297. if action == "return" then
  8298. local next = last1(callStack)
  8299. if next then
  8300. next["inner-start"] = start
  8301. return nil
  8302. else
  8303. return nil
  8304. end
  8305. else
  8306. return nil
  8307. end
  8308. end, "cr")
  8309. fn()
  8310. sethook1()
  8311. local out = values1(stats)
  8312. sort1(out, function(a, b)
  8313. return a["inner-time"] > b["inner-time"]
  8314. end)
  8315. print1("| Method | Location | Total | Inner | Calls |")
  8316. print1("| -------------------- | ------------------------------------------------------------ | -------- | -------- | ------- |")
  8317. local forLimit = n1(out)
  8318. local i = 1
  8319. while i <= forLimit do
  8320. local entry = out[i]
  8321. print1(format1("| %20s | %-60s | %8.5f | %8.5f | %7d | ", (function()
  8322. if entry["name"] then
  8323. return unmangleIdent1(entry["name"])
  8324. else
  8325. return "<unknown>"
  8326. end
  8327. end)(), remapMessage1(mappings, entry["short-src"] .. ":" .. entry["line"]), entry["total-time"], entry["inner-time"], entry["calls"]))
  8328. i = i + 1
  8329. end
  8330. return stats
  8331. end
  8332. buildStack1 = function(parent, stack, i, history, fold)
  8333. parent["n"] = parent["n"] + 1
  8334. if i >= 1 then
  8335. local elem = nth1(stack, i)
  8336. local hash = elem["source"] .. "|" .. elem["linedefined"]
  8337. local previous, child = fold and history[hash], parent[hash]
  8338. if previous then
  8339. parent["n"] = parent["n"] - 1
  8340. child = previous
  8341. end
  8342. if not child then
  8343. child = elem
  8344. elem["n"] = 0
  8345. parent[hash] = child
  8346. end
  8347. if not previous then
  8348. history[hash] = child
  8349. end
  8350. buildStack1(child, stack, i - 1, history, fold)
  8351. if previous then
  8352. return nil
  8353. else
  8354. history[hash] = nil
  8355. return nil
  8356. end
  8357. else
  8358. return nil
  8359. end
  8360. end
  8361. buildRevStack1 = function(parent, stack, i, history, fold)
  8362. parent["n"] = parent["n"] + 1
  8363. if i <= n1(stack) then
  8364. local elem = nth1(stack, i)
  8365. local hash = elem["source"] .. "|" .. elem["linedefined"]
  8366. local previous, child = fold and history[hash], parent[hash]
  8367. if previous then
  8368. parent["n"] = parent["n"] - 1
  8369. child = previous
  8370. end
  8371. if not child then
  8372. child = elem
  8373. elem["n"] = 0
  8374. parent[hash] = child
  8375. end
  8376. if not previous then
  8377. history[hash] = child
  8378. end
  8379. buildRevStack1(child, stack, i + 1, history, fold)
  8380. if previous then
  8381. return nil
  8382. else
  8383. history[hash] = nil
  8384. return nil
  8385. end
  8386. else
  8387. return nil
  8388. end
  8389. end
  8390. finishStack1 = function(element)
  8391. local children = {tag="list", n=0}
  8392. local temp, child = next1(element)
  8393. while temp ~= nil do
  8394. if type_23_1(child) == "table" then
  8395. push_21_1(children, child)
  8396. end
  8397. temp, child = next1(element, temp)
  8398. end
  8399. sort1(children, function(a, b)
  8400. return a["n"] > b["n"]
  8401. end)
  8402. element["children"] = children
  8403. local forLimit = n1(children)
  8404. local i = 1
  8405. while i <= forLimit do
  8406. finishStack1((children[i]))
  8407. i = i + 1
  8408. end
  8409. return nil
  8410. end
  8411. showStack_21_1 = function(out, mappings, total, stack, remaining)
  8412. line_21_1(out, format1("└ %s %s %d (%2.5f%%)", (function()
  8413. if stack["name"] then
  8414. return unmangleIdent1(stack["name"])
  8415. else
  8416. return "<unknown>"
  8417. end
  8418. end)(), (function()
  8419. if stack["short_src"] then
  8420. return remapMessage1(mappings, stack["short_src"] .. ":" .. stack["linedefined"])
  8421. else
  8422. return ""
  8423. end
  8424. end)(), stack["n"], (stack["n"] / total) * 100))
  8425. local temp
  8426. if remaining then
  8427. temp = remaining >= 1
  8428. else
  8429. temp = true
  8430. end
  8431. if temp then
  8432. out["indent"] = out["indent"] + 1
  8433. local temp = stack["children"]
  8434. local forLimit = n1(temp)
  8435. local i = 1
  8436. while i <= forLimit do
  8437. showStack_21_1(out, mappings, total, temp[i], remaining and remaining - 1)
  8438. i = i + 1
  8439. end
  8440. out["indent"] = out["indent"] - 1
  8441. return nil
  8442. else
  8443. return nil
  8444. end
  8445. end
  8446. showFlame_21_1 = function(mappings, stack, before, remaining)
  8447. local renamed = (function()
  8448. if stack["name"] then
  8449. return unmangleIdent1(stack["name"])
  8450. else
  8451. return "?"
  8452. end
  8453. end)() .. "`" .. (function()
  8454. if stack["short_src"] then
  8455. return remapMessage1(mappings, stack["short_src"] .. ":" .. stack["linedefined"])
  8456. else
  8457. return ""
  8458. end
  8459. end)()
  8460. print1(format1("%s%s %d", before, renamed, stack["n"]))
  8461. local temp
  8462. if remaining then
  8463. temp = remaining >= 1
  8464. else
  8465. temp = true
  8466. end
  8467. if temp then
  8468. local whole, temp = before .. renamed .. ";", stack["children"]
  8469. local forLimit = n1(temp)
  8470. local i = 1
  8471. while i <= forLimit do
  8472. showFlame_21_1(mappings, temp[i], whole, remaining and remaining - 1)
  8473. i = i + 1
  8474. end
  8475. return nil
  8476. else
  8477. return nil
  8478. end
  8479. end
  8480. profileStack1 = function(fn, mappings, args)
  8481. local stacks, top = {tag="list", n=0}, getinfo1(2, "S")
  8482. sethook1(function(action)
  8483. local pos, stack, info = 2, {tag="list", n=0}, getinfo1(2, "Sn")
  8484. while info do
  8485. if info["source"] == top["source"] and info["linedefined"] == top["linedefined"] then
  8486. info = nil
  8487. else
  8488. push_21_1(stack, info)
  8489. pos = pos + 1
  8490. info = getinfo1(pos, "Sn")
  8491. end
  8492. end
  8493. return push_21_1(stacks, stack)
  8494. end, "", 100000.0)
  8495. fn()
  8496. sethook1()
  8497. local folded = {n=0, name="<root>"}
  8498. local forLimit = n1(stacks)
  8499. local i = 1
  8500. while i <= forLimit do
  8501. local stack = stacks[i]
  8502. if args["stack-kind"] == "reverse" then
  8503. buildRevStack1(folded, stack, 1, {}, args["stack-fold"])
  8504. else
  8505. buildStack1(folded, stack, n1(stack), {}, args["stack-fold"])
  8506. end
  8507. i = i + 1
  8508. end
  8509. finishStack1(folded)
  8510. if args["stack-show"] == "flame" then
  8511. return showFlame_21_1(mappings, folded, "", args["stack-limit"] or 30)
  8512. else
  8513. local writer = {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  8514. showStack_21_1(writer, mappings, n1(stacks), folded, args["stack-limit"] or 10)
  8515. return print1(concat2(writer["out"]))
  8516. end
  8517. end
  8518. matcher2 = function(pattern)
  8519. return function(x)
  8520. local res = list1(match1(x, pattern))
  8521. if car1(res) == nil then
  8522. return nil
  8523. else
  8524. return res
  8525. end
  8526. end
  8527. end
  8528. addCount_21_1 = function(counts, name, line, count)
  8529. local fileCounts = counts[name]
  8530. if not fileCounts then
  8531. fileCounts = {max=0}
  8532. counts[name] = fileCounts
  8533. end
  8534. if line > fileCounts["max"] then
  8535. fileCounts["max"] = line
  8536. end
  8537. fileCounts[line] = (fileCounts[line] or 0) + count
  8538. return nil
  8539. end
  8540. readStats_21_1 = function(fileName, output)
  8541. if not output then
  8542. output = {}
  8543. end
  8544. local file = open1(fileName, "r")
  8545. if file then
  8546. while true do
  8547. local max = self1(file, "read", "*n")
  8548. if max then
  8549. if self1(file, "read", 1) == ":" then
  8550. local name = self1(file, "read", "*l")
  8551. if name then
  8552. local data = output[name]
  8553. if not data then
  8554. data = {max=max}
  8555. output[name] = data
  8556. elseif max > data["max"] then
  8557. data["max"] = max
  8558. end
  8559. local line = 1
  8560. while true do
  8561. if (line > max) then
  8562. break
  8563. else
  8564. local count = self1(file, "read", "*n")
  8565. if count then
  8566. if self1(file, "read", 1) == " " then
  8567. if count > 0 then
  8568. data[line] = (data[line] or 0) + count
  8569. end
  8570. line = line + 1
  8571. else
  8572. break
  8573. end
  8574. else
  8575. break
  8576. end
  8577. end
  8578. end
  8579. else
  8580. break
  8581. end
  8582. else
  8583. break
  8584. end
  8585. else
  8586. break
  8587. end
  8588. end
  8589. (getmetatable1(file) and getmetatable1(file)["--finalise"] or (file["close"] or function()
  8590. return nil
  8591. end))(file)
  8592. end
  8593. return output
  8594. end
  8595. writeStats_21_1 = function(compiler, fileName, output)
  8596. local handle, err = open1(fileName, "w")
  8597. if not handle then
  8598. self1(compiler["log"], "put-error!", (formatOutput_21_1(nil, "Cannot open stats file " .. err)))
  8599. exit_21_1(1)
  8600. end
  8601. local names = keys1(output)
  8602. sort1(names, nil)
  8603. local forLimit = n1(names)
  8604. local i = 1
  8605. while i <= forLimit do
  8606. local name = names[i]
  8607. local data = output[name]
  8608. self1(handle, "write", data["max"], ":", name, "\n")
  8609. local forLimit1 = data["max"]
  8610. local i1 = 1
  8611. while i1 <= forLimit1 do
  8612. self1(handle, "write", data[i1] or 0, " ")
  8613. i1 = i1 + 1
  8614. end
  8615. self1(handle, "write", "\n")
  8616. i = i + 1
  8617. end
  8618. return self1(handle, "close")
  8619. end
  8620. profileCoverageHook1 = function(visited)
  8621. return function(action, line)
  8622. local source = getinfo1(2, "S")["short_src"]
  8623. local visitedLines = visited[source]
  8624. if not visitedLines then
  8625. visitedLines = {}
  8626. visited[source] = visitedLines
  8627. end
  8628. local current = (visitedLines[line] or 0) + 1
  8629. visitedLines[line] = current
  8630. return nil
  8631. end
  8632. end
  8633. profileCoverage1 = function(fn, mappings, compiler)
  8634. local visited = compiler["coverage-visited"] or {}
  8635. sethook1(profileCoverageHook1(visited), "l")
  8636. fn()
  8637. sethook1()
  8638. visited[getinfo1(1, "S")["short_src"]] = nil
  8639. local result = readStats_21_1("luacov.stats.out")
  8640. local temp, visitedLines = next1(visited)
  8641. while temp ~= nil do
  8642. local thisMappings = mappings[temp]
  8643. if thisMappings then
  8644. local temp1, count = next1(visitedLines)
  8645. while temp1 ~= nil do
  8646. local mapped = thisMappings[temp1]
  8647. if mapped == nil then
  8648. else
  8649. local temp2
  8650. local temp3 = matcher2("^(.-):(%d+)%-(%d+)$")(mapped)
  8651. temp2 = type1(temp3) == "list" and (n1(temp3) >= 3 and (n1(temp3) <= 3 and true))
  8652. if temp2 then
  8653. local file, start, _eend = nth1(matcher2("^(.-):(%d+)%-(%d+)$")(mapped), 1), nth1(matcher2("^(.-):(%d+)%-(%d+)$")(mapped), 2), nth1(matcher2("^(.-):(%d+)%-(%d+)$")(mapped), 3)
  8654. local forStart, forLimit = tonumber1(start), tonumber1(_eend)
  8655. local line = forStart
  8656. while line <= forLimit do
  8657. addCount_21_1(result, file, tonumber1(line), count)
  8658. line = line + 1
  8659. end
  8660. else
  8661. local temp2
  8662. local temp3 = matcher2("^(.-):(%d+)$")(mapped)
  8663. temp2 = type1(temp3) == "list" and (n1(temp3) >= 2 and (n1(temp3) <= 2 and true))
  8664. if temp2 then
  8665. addCount_21_1(result, nth1(matcher2("^(.-):(%d+)$")(mapped), 1), tonumber1((nth1(matcher2("^(.-):(%d+)$")(mapped), 2))), count)
  8666. else
  8667. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(mapped) .. ", but none matched.\n" .. " Tried: `nil`\n Tried: `((matcher \"^(.-):(%d+)%-(%d+)$\") -> (?file ?start ?end))`\n Tried: `((matcher \"^(.-):(%d+)$\") -> (?file ?line))`")
  8668. end
  8669. end
  8670. end
  8671. temp1, count = next1(visitedLines, temp1)
  8672. end
  8673. else
  8674. local temp1, count = next1(visitedLines)
  8675. while temp1 ~= nil do
  8676. addCount_21_1(result, temp, temp1, count)
  8677. temp1, count = next1(visitedLines, temp1)
  8678. end
  8679. end
  8680. temp, visitedLines = next1(visited, temp)
  8681. end
  8682. return writeStats_21_1(compiler, "luacov.stats.out", result)
  8683. end
  8684. formatCoverage1 = function(hits, misses)
  8685. if hits == 0 and misses == 0 then
  8686. return "100%"
  8687. else
  8688. return format1("%2.f%%", 100 * (hits / (hits + misses)))
  8689. end
  8690. end
  8691. genCoverageReport1 = function(compiler, args)
  8692. if empty_3f_1(args["input"]) then
  8693. self1(compiler["log"], "put-error!", "No inputs to generate a report for.")
  8694. exit_21_1(1)
  8695. end
  8696. local stats, logger, max = readStats_21_1("luacov.stats.out"), compiler["log"], 0
  8697. local temp, counts = next1(stats)
  8698. while temp ~= nil do
  8699. local temp1, count = next1(counts)
  8700. while temp1 ~= nil do
  8701. if number_3f_1(temp1) and count > max then
  8702. max = count
  8703. end
  8704. temp1, count = next1(counts, temp1)
  8705. end
  8706. temp, counts = next1(stats, temp)
  8707. end
  8708. local maxSize = n1(format1("%d", max))
  8709. local fmtZero, fmtNone, fmtNum, handle, err = rep1("*", maxSize) .. "0", rep1(" ", maxSize + 1), "%" .. maxSize + 1 .. "d", open1(args["gen-coverage"] or "luacov.report.out", "w")
  8710. local summary, totalHits, totalMisses = {tag="list", n=0}, 0, 0
  8711. if not handle then
  8712. self1(logger, "put-error!", (formatOutput_21_1(nil, "Cannot open report file " .. err)))
  8713. exit_21_1(1)
  8714. end
  8715. local temp = args["input"]
  8716. local forLimit = n1(temp)
  8717. local i = 1
  8718. while i <= forLimit do
  8719. local path = temp[i]
  8720. self1(handle, "write", "==============================================================================", "\n")
  8721. self1(handle, "write", path, "\n")
  8722. self1(handle, "write", "==============================================================================", "\n")
  8723. local lib = compiler["libs"]["paths"][path]
  8724. local lines = lib["lisp-lines"]
  8725. local nLines, counts, active, hits, misses = n1(lines), stats[path], {}, 0, 0
  8726. visitBlock1(lib["nodes"], 1, function(node)
  8727. local temp1
  8728. if type1(node) ~= "list" then
  8729. temp1 = true
  8730. else
  8731. local head = car1(node)
  8732. local temp2 = type1(head)
  8733. if temp2 == "symbol" then
  8734. local var = head["var"]
  8735. temp1 = var ~= builtins1["lambda"] and (var ~= builtins1["cond"] and (var ~= builtins1["import"] and (var ~= builtins1["define"] and (var ~= builtins1["define-macro"] and var ~= builtins1["define-native"]))))
  8736. elseif temp2 == "list" then
  8737. temp1 = not builtin_3f_1(car1(head), "lambda")
  8738. else
  8739. temp1 = true
  8740. end
  8741. end
  8742. if temp1 then
  8743. local source = sourceRange1(node["source"])
  8744. if source["name"] == path then
  8745. local forStart, forLimit1 = source["start"]["line"], source["finish"]["line"]
  8746. local i1 = forStart
  8747. while i1 <= forLimit1 do
  8748. active[i1] = true
  8749. i1 = i1 + 1
  8750. end
  8751. return nil
  8752. else
  8753. return nil
  8754. end
  8755. else
  8756. return nil
  8757. end
  8758. end)
  8759. local i1 = 1
  8760. while i1 <= nLines do
  8761. local line, isActive, count = nth1(lines, i1), active[i1], counts and counts[i1] or 0
  8762. if not isActive and count > 0 then
  8763. self1(logger, "put-warning!", (formatOutput_21_1(nil, "" .. path .. ":" .. i1 .. " is not active but has count " .. count)))
  8764. end
  8765. if not isActive then
  8766. if line == "" then
  8767. self1(handle, "write", "\n")
  8768. else
  8769. self1(handle, "write", fmtNone, " ", line, "\n")
  8770. end
  8771. elseif count > 0 then
  8772. hits = hits + 1
  8773. self1(handle, "write", format1(fmtNum, count), " ", line, "\n")
  8774. else
  8775. misses = misses + 1
  8776. self1(handle, "write", fmtZero, " ", line, "\n")
  8777. end
  8778. i1 = i1 + 1
  8779. end
  8780. push_21_1(summary, list1(path, format1("%d", hits), format1("%d", misses), formatCoverage1(hits, misses)))
  8781. totalHits = totalHits + hits
  8782. totalMisses = totalMisses + misses
  8783. i = i + 1
  8784. end
  8785. self1(handle, "write", "==============================================================================", "\n")
  8786. self1(handle, "write", "Summary\n")
  8787. self1(handle, "write", "==============================================================================", "\n\n")
  8788. local headings = {tag="list", n=4, "File", "Hits", "Misses", "Coverage"}
  8789. local widths, total = map2(n1, headings), list1("Total", format1("%d", totalHits), format1("%d", totalMisses), formatCoverage1(totalHits, totalMisses))
  8790. local forLimit = n1(summary)
  8791. local i = 1
  8792. while i <= forLimit do
  8793. local row = summary[i]
  8794. local forLimit1 = n1(row)
  8795. local i1 = 1
  8796. while i1 <= forLimit1 do
  8797. local width = n1(row[i1])
  8798. if width > widths[i1] then
  8799. widths[i1] = width
  8800. end
  8801. i1 = i1 + 1
  8802. end
  8803. i = i + 1
  8804. end
  8805. local forLimit = n1(total)
  8806. local i = 1
  8807. while i <= forLimit do
  8808. if n1(total[i]) > widths[i] then
  8809. widths = i
  8810. end
  8811. i = i + 1
  8812. end
  8813. local format = "%-" .. concat2(widths, "s %-") .. "s\n"
  8814. local separator = rep1("-", n1(apply1(format1, format, headings))) .. "\n"
  8815. self1(handle, "write", apply1(format1, format, headings))
  8816. self1(handle, "write", separator)
  8817. local forLimit = n1(summary)
  8818. local i = 1
  8819. while i <= forLimit do
  8820. self1(handle, "write", apply1(format1, format, (summary[i])))
  8821. i = i + 1
  8822. end
  8823. self1(handle, "write", separator)
  8824. self1(handle, "write", apply1(format1, format, total))
  8825. return self1(handle, "close")
  8826. end
  8827. initLua1 = function(compiler, args)
  8828. if args["profile-compile"] then
  8829. if args["profile"] == "coverage" then
  8830. local visited = {}
  8831. local hook, exec = profileCoverageHook1(visited), compiler["exec"]
  8832. compiler["coverage-visited"] = visited
  8833. compiler["exec"] = function(func)
  8834. sethook1(hook, "l")
  8835. local result = exec(func)
  8836. sethook1()
  8837. return result
  8838. end
  8839. return nil
  8840. else
  8841. return nil
  8842. end
  8843. else
  8844. return nil
  8845. end
  8846. end
  8847. runLua1 = function(compiler, args)
  8848. if empty_3f_1(args["input"]) then
  8849. self1(compiler["log"], "put-error!", "No inputs to run.")
  8850. exit_21_1(1)
  8851. end
  8852. local out = file1(compiler, false)
  8853. local lines, logger = generateMappings1(out["lines"]), compiler["log"]
  8854. local name
  8855. if string_3f_1(args["emit-lua"]) then
  8856. name = args["emit-lua"]
  8857. else
  8858. name = args["output"] .. ".lua"
  8859. end
  8860. local temp = list1(load1(concat2(out["out"]), "=" .. name))
  8861. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == nil and true))) then
  8862. local msg = nth1(temp, 2)
  8863. self1(logger, "put-error!", "Cannot load compiled source.")
  8864. print1(msg)
  8865. print1(concat2(out["out"]))
  8866. return exit_21_1(1)
  8867. elseif type1(temp) == "list" and (n1(temp) >= 1 and (n1(temp) <= 1 and true)) then
  8868. local fun = nth1(temp, 1)
  8869. _5f_G1["arg"] = args["script-args"]
  8870. _5f_G1["arg"][0] = car1(args["input"])
  8871. local exec, temp1 = function()
  8872. local temp2 = list1(xpcall1(function()
  8873. return apply1(fun, args["script-args"])
  8874. end, traceback2))
  8875. if type1(temp2) == "list" and (n1(temp2) >= 1 and (nth1(temp2, 1) == true and true)) then
  8876. return nil
  8877. elseif type1(temp2) == "list" and (n1(temp2) >= 2 and (n1(temp2) <= 2 and (nth1(temp2, 1) == false and true))) then
  8878. local msg = nth1(temp2, 2)
  8879. self1(logger, "put-error!", "Execution failed.")
  8880. print1(remapTraceback1({[name]=lines}, msg))
  8881. return exit_21_1(1)
  8882. else
  8883. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp2) .. ", but none matched.\n" .. " Tried: `(true . _)`\n Tried: `(false ?msg)`")
  8884. end
  8885. end, args["profile"]
  8886. if temp1 == "none" then
  8887. return exec()
  8888. elseif temp1 == nil then
  8889. return exec()
  8890. elseif temp1 == "call" then
  8891. return profileCalls1(exec, {[name]=lines})
  8892. elseif temp1 == "stack" then
  8893. return profileStack1(exec, {[name]=lines}, args)
  8894. elseif temp1 == "coverage" then
  8895. return profileCoverage1(exec, merge1(compiler["compile-state"]["mappings"], {[name]=lines}), compiler)
  8896. else
  8897. self1(logger, "put-error!", ("Unknown profiler '" .. temp1 .. "'"))
  8898. return exit_21_1(1)
  8899. end
  8900. else
  8901. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(nil ?msg)`\n Tried: `(?fun)`")
  8902. end
  8903. end
  8904. task3 = {name="run", setup=function(spec)
  8905. addCategory_21_1(spec, "run", "Running files", "Provides a way to running the compiled script, along with various extensions such as profiling tools.")
  8906. addArgument_21_1(spec, {tag="list", n=2, "--run", "-r"}, "help", "Run the compiled code.", "cat", "run")
  8907. addArgument_21_1(spec, {tag="list", n=1, "--"}, "name", "script-args", "cat", "run", "help", "Arguments to pass to the compiled script.", "var", "ARG", "all", true, "default", {tag="list", n=0}, "action", addAction1, "narg", "*")
  8908. addArgument_21_1(spec, {tag="list", n=2, "--profile", "-p"}, "help", "Run the compiled code with the profiler.", "cat", "run", "var", "none|call|stack", "default", nil, "value", "stack", "narg", "?")
  8909. addArgument_21_1(spec, {tag="list", n=1, "--profile-compile"}, "help", "Run the profiler when evaluating code at compile time. Not all profilers support this.", "cat", "run")
  8910. addArgument_21_1(spec, {tag="list", n=1, "--stack-kind"}, "help", "The kind of stack to emit when using the stack profiler. A reverse stack shows callers of that method instead.", "cat", "run", "var", "forward|reverse", "default", "forward", "narg", 1)
  8911. addArgument_21_1(spec, {tag="list", n=1, "--stack-show"}, "help", "The method to use to display the profiling results.", "cat", "run", "var", "flame|term", "default", "term", "narg", 1)
  8912. addArgument_21_1(spec, {tag="list", n=1, "--stack-limit"}, "help", "The maximum number of call frames to emit.", "cat", "run", "var", "LIMIT", "default", nil, "action", setNumAction1, "narg", 1)
  8913. return addArgument_21_1(spec, {tag="list", n=1, "--stack-fold"}, "help", "Whether to fold recursive functions into themselves. This hopefully makes deep graphs easier to understand, but may result in less accurate graphs.", "cat", "run", "value", true, "default", false)
  8914. end, pred=function(args)
  8915. return args["run"] or args["profile"]
  8916. end, init=initLua1, run=runLua1}
  8917. coverageReport1 = {name="coverage-report", setup=function(spec)
  8918. return addArgument_21_1(spec, {tag="list", n=1, "--gen-coverage"}, "help", "Specify the folder to emit documentation to.", "cat", "run", "default", nil, "value", "luacov.report.out", "narg", "?")
  8919. end, pred=function(args)
  8920. return nil ~= args["gen-coverage"]
  8921. end, run=genCoverageReport1}
  8922. getVar1 = function(state, var)
  8923. local vars = state["usage-vars"]
  8924. local entry = vars[var]
  8925. if not entry then
  8926. entry = {var=var, usages={tag="list", n=0}, soft={tag="list", n=0}, defs={tag="list", n=0}, active=false}
  8927. vars[var] = entry
  8928. end
  8929. return entry
  8930. end
  8931. addUsage_21_1 = function(state, var, node)
  8932. local varMeta = getVar1(state, var)
  8933. push_21_1(varMeta["usages"], node)
  8934. varMeta["active"] = true
  8935. return nil
  8936. end
  8937. removeUsage_21_1 = function(state, var, node)
  8938. local varMeta = getVar1(state, var)
  8939. local users = varMeta["usages"]
  8940. local forStart = n1(users)
  8941. local i = forStart
  8942. while i >= 1 do
  8943. if nth1(users, i) == node then
  8944. removeNth_21_1(users, i)
  8945. if empty_3f_1(users) then
  8946. varMeta["active"] = false
  8947. end
  8948. end
  8949. i = i + -1
  8950. end
  8951. return nil
  8952. end
  8953. addDefinition_21_1 = function(state, var, node, kind, value)
  8954. return push_21_1(getVar1(state, var)["defs"], {tag=kind, node=node, value=value})
  8955. end
  8956. replaceDefinition_21_1 = function(state, var, oldValue, newKind, newValue)
  8957. local varMeta = state["usage-vars"][var]
  8958. if varMeta then
  8959. local temp = varMeta["defs"]
  8960. local forLimit = n1(temp)
  8961. local i = 1
  8962. while i <= forLimit do
  8963. local def = temp[i]
  8964. if def["value"] == oldValue then
  8965. def["tag"] = newKind
  8966. def["value"] = newValue
  8967. end
  8968. i = i + 1
  8969. end
  8970. return nil
  8971. else
  8972. return nil
  8973. end
  8974. end
  8975. populateDefinitions1 = function(state, nodes, visit_3f_)
  8976. if not visit_3f_ then
  8977. visit_3f_ = function()
  8978. return true
  8979. end
  8980. end
  8981. local queue, lazyDefs, addCheckedUsage_21_, addLazyDef_21_, visitQuote, visitNode = {tag="list", n=0}, {}
  8982. addCheckedUsage_21_ = function(var, user)
  8983. if not getVar1(state, var)["active"] then
  8984. local defs = lazyDefs[var]
  8985. if defs then
  8986. local forLimit = n1(defs)
  8987. local i = 1
  8988. while i <= forLimit do
  8989. push_21_1(queue, (defs[i]))
  8990. i = i + 1
  8991. end
  8992. end
  8993. end
  8994. return addUsage_21_1(state, var, user)
  8995. end
  8996. addLazyDef_21_ = function(var, node)
  8997. if getVar1(state, var)["active"] then
  8998. return true
  8999. else
  9000. local defs = lazyDefs[var]
  9001. if not defs then
  9002. defs = {tag="list", n=0}
  9003. lazyDefs[var] = defs
  9004. end
  9005. push_21_1(defs, node)
  9006. return false
  9007. end
  9008. end
  9009. visitQuote = function(node, level)
  9010. while true do
  9011. if level == 0 then
  9012. return visitNode(node)
  9013. else
  9014. local temp = type1(node)
  9015. if temp == "string" then
  9016. return nil
  9017. elseif temp == "number" then
  9018. return nil
  9019. elseif temp == "key" then
  9020. return nil
  9021. elseif temp == "symbol" then
  9022. local var = node["var"]
  9023. if var then
  9024. return push_21_1(getVar1(state, var)["soft"], node)
  9025. else
  9026. return nil
  9027. end
  9028. elseif temp == "list" then
  9029. local first = nth1(node, 1)
  9030. if type1(first) ~= "symbol" then
  9031. local forLimit = n1(node)
  9032. local i = 1
  9033. while i <= forLimit do
  9034. local sub = node[i]
  9035. visitQuote(sub, level)
  9036. i = i + 1
  9037. end
  9038. return nil
  9039. elseif first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  9040. node, level = nth1(node, 2), level - 1
  9041. elseif first["contents"] == "syntax-quote" then
  9042. node, level = nth1(node, 2), level + 1
  9043. else
  9044. local forLimit = n1(node)
  9045. local i = 1
  9046. while i <= forLimit do
  9047. local sub = node[i]
  9048. visitQuote(sub, level)
  9049. i = i + 1
  9050. end
  9051. return nil
  9052. end
  9053. else
  9054. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  9055. end
  9056. end
  9057. end
  9058. end
  9059. visitNode = function(node)
  9060. while true do
  9061. local temp = type1(node)
  9062. if temp == "string" then
  9063. return nil
  9064. elseif temp == "number" then
  9065. return nil
  9066. elseif temp == "key" then
  9067. return nil
  9068. elseif temp == "symbol" then
  9069. return addCheckedUsage_21_(node["var"], node)
  9070. elseif temp == "list" then
  9071. local head = car1(node)
  9072. local temp1 = type1(head)
  9073. if temp1 == "symbol" then
  9074. local func = head["var"]
  9075. if func["kind"] ~= "builtin" then
  9076. local forLimit = n1(node)
  9077. local i = 1
  9078. while i <= forLimit do
  9079. visitNode(nth1(node, i))
  9080. i = i + 1
  9081. end
  9082. return nil
  9083. elseif func == builtins1["lambda"] then
  9084. local temp2 = nth1(node, 2)
  9085. local forLimit = n1(temp2)
  9086. local i = 1
  9087. while i <= forLimit do
  9088. local arg = temp2[i]
  9089. addDefinition_21_1(state, arg["var"], arg, "var", arg["var"])
  9090. i = i + 1
  9091. end
  9092. local forLimit = n1(node)
  9093. local i = 3
  9094. while i <= forLimit do
  9095. visitNode(nth1(node, i))
  9096. i = i + 1
  9097. end
  9098. return nil
  9099. elseif func == builtins1["define-native"] then
  9100. return addDefinition_21_1(state, node["def-var"], node, "var", node["def-var"])
  9101. elseif func == builtins1["set!"] then
  9102. local var, val = nth1(node, 2)["var"], nth1(node, 3)
  9103. addDefinition_21_1(state, var, node, "val", val)
  9104. if visit_3f_(val, var, node) or addLazyDef_21_(var, val) then
  9105. node = val
  9106. else
  9107. return nil
  9108. end
  9109. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  9110. local var, val = node["def-var"], last1(node)
  9111. addDefinition_21_1(state, var, node, "val", val)
  9112. if visit_3f_(val, var, node) or addLazyDef_21_(var, val) then
  9113. node = val
  9114. else
  9115. return nil
  9116. end
  9117. elseif func == builtins1["cond"] then
  9118. local forLimit = n1(node)
  9119. local i = 2
  9120. while i <= forLimit do
  9121. local temp2 = nth1(node, i)
  9122. local forLimit1 = n1(temp2)
  9123. local i1 = 1
  9124. while i1 <= forLimit1 do
  9125. local child = temp2[i1]
  9126. visitNode(child)
  9127. i1 = i1 + 1
  9128. end
  9129. i = i + 1
  9130. end
  9131. return nil
  9132. elseif func == builtins1["quote"] then
  9133. return nil
  9134. elseif func == builtins1["syntax-quote"] then
  9135. return visitQuote(nth1(node, 2), 1)
  9136. elseif func == builtins1["import"] then
  9137. return nil
  9138. elseif func == builtins1["struct-literal"] then
  9139. local forLimit = n1(node)
  9140. local i = 2
  9141. while i <= forLimit do
  9142. visitNode(nth1(node, i))
  9143. i = i + 1
  9144. end
  9145. return nil
  9146. else
  9147. return error1("Unhandled variable " .. func["name"], 0)
  9148. end
  9149. elseif temp1 == "list" then
  9150. if builtin_3f_1(car1(head), "lambda") then
  9151. local temp2 = zipArgs1(cadar1(node), 1, node, 2)
  9152. local forLimit = n1(temp2)
  9153. local i = 1
  9154. while i <= forLimit do
  9155. local zipped = temp2[i]
  9156. local args, vals = car1(zipped), cadr1(zipped)
  9157. if n1(args) == 1 and (n1(vals) <= 1 and not car1(args)["var"]["is-variadic"]) then
  9158. local var, val = car1(args)["var"], car1(vals) or makeNil1()
  9159. addDefinition_21_1(state, var, car1(args), "val", val)
  9160. if visit_3f_(val, var, node) or addLazyDef_21_(var, val) then
  9161. visitNode(val)
  9162. end
  9163. else
  9164. local forLimit1 = n1(args)
  9165. local i1 = 1
  9166. while i1 <= forLimit1 do
  9167. local arg = args[i1]
  9168. addDefinition_21_1(state, arg["var"], arg, "var", arg["var"])
  9169. i1 = i1 + 1
  9170. end
  9171. local forLimit1 = n1(vals)
  9172. local i1 = 1
  9173. while i1 <= forLimit1 do
  9174. local val = vals[i1]
  9175. visitNode(val)
  9176. i1 = i1 + 1
  9177. end
  9178. end
  9179. i = i + 1
  9180. end
  9181. local forLimit = n1(head)
  9182. local i = 3
  9183. while i <= forLimit do
  9184. visitNode(nth1(head, i))
  9185. i = i + 1
  9186. end
  9187. return nil
  9188. else
  9189. local forLimit = n1(node)
  9190. local i = 1
  9191. while i <= forLimit do
  9192. visitNode(nth1(node, i))
  9193. i = i + 1
  9194. end
  9195. return nil
  9196. end
  9197. else
  9198. local forLimit = n1(node)
  9199. local i = 1
  9200. while i <= forLimit do
  9201. visitNode(nth1(node, i))
  9202. i = i + 1
  9203. end
  9204. return nil
  9205. end
  9206. else
  9207. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  9208. end
  9209. end
  9210. end
  9211. local forLimit = n1(nodes)
  9212. local i = 1
  9213. while i <= forLimit do
  9214. push_21_1(queue, (nodes[i]))
  9215. i = i + 1
  9216. end
  9217. while n1(queue) > 0 do
  9218. visitNode(popLast_21_1(queue))
  9219. end
  9220. return nil
  9221. end
  9222. visitLazyDefinition_3f_1 = function(val, _5f_, node)
  9223. return node["def-var"] == nil and not (type1(val) == "list" and builtin_3f_1(car1(val), "lambda"))
  9224. end
  9225. visitEagerExported_3f_1 = function(val, _5f_, node)
  9226. local def = node["def-var"]
  9227. local temp
  9228. if def then
  9229. local temp1 = def["kind"] == "macro"
  9230. if temp1 then
  9231. temp = temp1
  9232. else
  9233. local scope, name = def["scope"], def["name"]
  9234. temp = scope["exported"][name]
  9235. end
  9236. else
  9237. temp = def
  9238. end
  9239. return temp or (type1(val) ~= "list" or not builtin_3f_1(car1(val), "lambda"))
  9240. end
  9241. tagUsage1 = {name="tag-usage", help="Gathers usage and definition data for all expressions in NODES, storing it in LOOKUP.", cat={tag="list", n=2, "tag", "usage"}, run=function(temp, state, nodes, lookup, visit_3f_)
  9242. local visit_3f_1
  9243. if visit_3f_ == nil then
  9244. visit_3f_1 = visitLazyDefinition_3f_1
  9245. else
  9246. visit_3f_1 = visit_3f_
  9247. end
  9248. lookup["usage-vars"] = {}
  9249. return populateDefinitions1(lookup, nodes, visit_3f_1)
  9250. end}
  9251. transform1 = function(nodes, transformers, lookup)
  9252. local pre, post, preBlock, postBlock, preBind, postBind, transformQuote, transformNode = transformers["pre"], transformers["post"], transformers["pre-block"], transformers["post-block"], transformers["pre-bind"], transformers["post-bind"]
  9253. transformQuote = function(node, level)
  9254. if level == 0 then
  9255. return transformNode(node)
  9256. else
  9257. local tag = type1(node)
  9258. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  9259. elseif tag == "list" then
  9260. local first = nth1(node, 1)
  9261. if first and type1(first) == "symbol" then
  9262. if first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  9263. node[2] = transformQuote(nth1(node, 2), level - 1)
  9264. elseif first["contents"] == "syntax-quote" then
  9265. node[2] = transformQuote(nth1(node, 2), level + 1)
  9266. else
  9267. local forLimit = n1(node)
  9268. local i = 1
  9269. while i <= forLimit do
  9270. node[i] = transformQuote(nth1(node, i), level)
  9271. i = i + 1
  9272. end
  9273. end
  9274. else
  9275. local forLimit = n1(node)
  9276. local i = 1
  9277. while i <= forLimit do
  9278. node[i] = transformQuote(nth1(node, i), level)
  9279. i = i + 1
  9280. end
  9281. end
  9282. else
  9283. error1("Unknown tag " .. tag)
  9284. end
  9285. return node
  9286. end
  9287. end
  9288. transformNode = function(node)
  9289. local forLimit = n1(pre)
  9290. local i = 1
  9291. while i <= forLimit do
  9292. node = pre[i](node)
  9293. i = i + 1
  9294. end
  9295. local temp = type1(node)
  9296. if temp == "string" then
  9297. elseif temp == "number" then
  9298. elseif temp == "key" then
  9299. elseif temp == "symbol" then
  9300. elseif temp == "list" then
  9301. local head = car1(node)
  9302. local temp1 = type1(head)
  9303. if temp1 == "symbol" then
  9304. local func = head["var"]
  9305. if func["kind"] ~= "builtin" then
  9306. local forLimit = n1(node)
  9307. local i = 1
  9308. while i <= forLimit do
  9309. node[i] = transformNode(nth1(node, i))
  9310. i = i + 1
  9311. end
  9312. elseif func == builtins1["lambda"] then
  9313. local forLimit = n1(preBlock)
  9314. local i = 1
  9315. while i <= forLimit do
  9316. preBlock[i](node, 3)
  9317. i = i + 1
  9318. end
  9319. local forLimit = n1(node)
  9320. local i = 3
  9321. while i <= forLimit do
  9322. node[i] = transformNode(nth1(node, i))
  9323. i = i + 1
  9324. end
  9325. local forLimit = n1(postBlock)
  9326. local i = 1
  9327. while i <= forLimit do
  9328. postBlock[i](node, 3)
  9329. i = i + 1
  9330. end
  9331. elseif func == builtins1["cond"] then
  9332. local forLimit = n1(node)
  9333. local i = 2
  9334. while i <= forLimit do
  9335. local branch = nth1(node, i)
  9336. branch[1] = transformNode(nth1(branch, 1))
  9337. local forLimit1 = n1(preBlock)
  9338. local i1 = 1
  9339. while i1 <= forLimit1 do
  9340. preBlock[i1](branch, 2)
  9341. i1 = i1 + 1
  9342. end
  9343. local forLimit1 = n1(branch)
  9344. local i1 = 2
  9345. while i1 <= forLimit1 do
  9346. branch[i1] = transformNode(nth1(branch, i1))
  9347. i1 = i1 + 1
  9348. end
  9349. local forLimit1 = n1(postBlock)
  9350. local i1 = 1
  9351. while i1 <= forLimit1 do
  9352. postBlock[i1](branch, 2)
  9353. i1 = i1 + 1
  9354. end
  9355. i = i + 1
  9356. end
  9357. elseif func == builtins1["set!"] then
  9358. local old = nth1(node, 3)
  9359. local new = transformNode(old)
  9360. if old ~= new then
  9361. replaceDefinition_21_1(lookup, nth1(node, 2)["var"], old, "val", new)
  9362. node[3] = new
  9363. end
  9364. elseif func == builtins1["quote"] then
  9365. elseif func == builtins1["syntax-quote"] then
  9366. node[2] = transformQuote(nth1(node, 2), 1)
  9367. elseif func == builtins1["unquote"] or func == builtins1["unquote-splice"] then
  9368. error1("unquote/unquote-splice should never appear head", 0)
  9369. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  9370. local len = n1(node)
  9371. local old = nth1(node, len)
  9372. local new = transformNode(old)
  9373. if old ~= new then
  9374. replaceDefinition_21_1(lookup, node["def-var"], old, "val", new)
  9375. node[len] = new
  9376. end
  9377. elseif func == builtins1["define-native"] then
  9378. elseif func == builtins1["import"] then
  9379. elseif func == builtins1["struct-literal"] then
  9380. local forLimit = n1(node)
  9381. local i = 1
  9382. while i <= forLimit do
  9383. node[i] = transformNode(nth1(node, i))
  9384. i = i + 1
  9385. end
  9386. else
  9387. error1("Unknown variable " .. func["name"], 0)
  9388. end
  9389. elseif temp1 == "list" then
  9390. if builtin_3f_1(car1(head), "lambda") then
  9391. local forLimit = n1(preBind)
  9392. local i = 1
  9393. while i <= forLimit do
  9394. preBind[i](node)
  9395. i = i + 1
  9396. end
  9397. local valI, temp2 = 2, zipArgs1(nth1(head, 2), 1, node, 2)
  9398. local forLimit = n1(temp2)
  9399. local i = 1
  9400. while i <= forLimit do
  9401. local zipped = temp2[i]
  9402. local args, vals = car1(zipped), cadr1(zipped)
  9403. if n1(args) == 1 and (n1(vals) == 1 and not car1(args)["var"]["is-variadic"]) then
  9404. local old = car1(vals)
  9405. local new = transformNode(old)
  9406. if old ~= new then
  9407. replaceDefinition_21_1(lookup, car1(args)["var"], old, "val", new)
  9408. node[valI] = new
  9409. end
  9410. valI = valI + 1
  9411. else
  9412. local forLimit1 = n1(vals)
  9413. local i1 = 1
  9414. while i1 <= forLimit1 do
  9415. local val = vals[i1]
  9416. node[valI] = transformNode(val)
  9417. valI = valI + 1
  9418. i1 = i1 + 1
  9419. end
  9420. end
  9421. i = i + 1
  9422. end
  9423. local forLimit = n1(preBlock)
  9424. local i = 1
  9425. while i <= forLimit do
  9426. preBlock[i](head, 3)
  9427. i = i + 1
  9428. end
  9429. local forLimit = n1(head)
  9430. local i = 3
  9431. while i <= forLimit do
  9432. head[i] = transformNode(nth1(head, i))
  9433. i = i + 1
  9434. end
  9435. local forLimit = n1(postBlock)
  9436. local i = 1
  9437. while i <= forLimit do
  9438. postBlock[i](head, 2)
  9439. i = i + 1
  9440. end
  9441. local forLimit = n1(postBind)
  9442. local i = 1
  9443. while i <= forLimit do
  9444. postBind[i](node)
  9445. i = i + 1
  9446. end
  9447. else
  9448. local forLimit = n1(node)
  9449. local i = 1
  9450. while i <= forLimit do
  9451. node[i] = transformNode(nth1(node, i))
  9452. i = i + 1
  9453. end
  9454. end
  9455. else
  9456. local forLimit = n1(node)
  9457. local i = 1
  9458. while i <= forLimit do
  9459. node[i] = transformNode(nth1(node, i))
  9460. i = i + 1
  9461. end
  9462. end
  9463. else
  9464. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  9465. end
  9466. local forLimit = n1(post)
  9467. local i = 1
  9468. while i <= forLimit do
  9469. node = post[i](node)
  9470. i = i + 1
  9471. end
  9472. return node
  9473. end
  9474. local forLimit = n1(preBlock)
  9475. local i = 1
  9476. while i <= forLimit do
  9477. preBlock[i](nodes, 1)
  9478. i = i + 1
  9479. end
  9480. local forLimit = n1(nodes)
  9481. local i = 1
  9482. while i <= forLimit do
  9483. nodes[i] = transformNode(nth1(nodes, i))
  9484. i = i + 1
  9485. end
  9486. local forLimit = n1(postBlock)
  9487. local i = 1
  9488. while i <= forLimit do
  9489. postBlock[i](nodes, 1)
  9490. i = i + 1
  9491. end
  9492. return nil
  9493. end
  9494. emptyTransformers1 = function()
  9495. return {pre={tag="list", n=0}, ["pre-block"]={tag="list", n=0}, ["pre-bind"]={tag="list", n=0}, post={tag="list", n=0}, ["post-block"]={tag="list", n=0}, ["post-bind"]={tag="list", n=0}}
  9496. end
  9497. transformer1 = {name="transformer", help="Run the given TRANSFORMERS on the provides NODES with the given\nLOOKUP information.", cat={tag="list", n=2, "opt", "usage"}, run=function(temp, state, nodes, lookup, transformers)
  9498. local trackers, transLookup = {tag="list", n=0}, emptyTransformers1()
  9499. local forLimit = n1(transformers)
  9500. local i = 1
  9501. while i <= forLimit do
  9502. local trans, tracker = transformers[i], {changed=0}
  9503. local run = trans["run"]
  9504. push_21_1(trackers, tracker)
  9505. local temp1 = trans["cat"]
  9506. local forLimit1 = n1(temp1)
  9507. local i1 = 1
  9508. while i1 <= forLimit1 do
  9509. local cat = temp1[i1]
  9510. local group = match1(cat, "^transform%-(.*)")
  9511. if group then
  9512. if not transLookup[group] then
  9513. error1("Unknown category " .. cat .. " for " .. trans["name"])
  9514. end
  9515. if endsWith_3f_1(group, "-block") then
  9516. push_21_1(transLookup[group], function(node, start)
  9517. return run(tracker, state, node, start, lookup)
  9518. end)
  9519. else
  9520. push_21_1(transLookup[group], function(node)
  9521. return run(tracker, state, node, lookup)
  9522. end)
  9523. end
  9524. end
  9525. i1 = i1 + 1
  9526. end
  9527. i = i + 1
  9528. end
  9529. transform1(nodes, transLookup, lookup)
  9530. local forLimit = n1(trackers)
  9531. local i = 1
  9532. while i <= forLimit do
  9533. temp["changed"] = temp["changed"] + nth1(trackers, i)["changed"]
  9534. if state["track"] then
  9535. self1(state["logger"], "put-verbose!", (sprintf1("%s made %d changes", "[" .. concat2(nth1(transformers, i)["cat"], " ") .. "] " .. nth1(transformers, i)["name"], nth1(trackers, i)["changed"])))
  9536. end
  9537. i = i + 1
  9538. end
  9539. return nil
  9540. end}
  9541. traverseQuote1 = function(node, visitor, level)
  9542. if level == 0 then
  9543. return traverseNode1(node, visitor)
  9544. else
  9545. local tag = type1(node)
  9546. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  9547. return node
  9548. elseif tag == "list" then
  9549. local first = nth1(node, 1)
  9550. if type1(first) == "symbol" then
  9551. if first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  9552. node[2] = traverseQuote1(nth1(node, 2), visitor, level - 1)
  9553. return node
  9554. elseif first["contents"] == "syntax-quote" then
  9555. node[2] = traverseQuote1(nth1(node, 2), visitor, level + 1)
  9556. return node
  9557. else
  9558. local forLimit = n1(node)
  9559. local i = 1
  9560. while i <= forLimit do
  9561. node[i] = traverseQuote1(nth1(node, i), visitor, level)
  9562. i = i + 1
  9563. end
  9564. return node
  9565. end
  9566. else
  9567. local forLimit = n1(node)
  9568. local i = 1
  9569. while i <= forLimit do
  9570. node[i] = traverseQuote1(nth1(node, i), visitor, level)
  9571. i = i + 1
  9572. end
  9573. return node
  9574. end
  9575. elseif error1 then
  9576. return "Unknown tag " .. tag
  9577. else
  9578. _error("unmatched item")
  9579. end
  9580. end
  9581. end
  9582. traverseNode1 = function(node, visitor)
  9583. local tag = type1(node)
  9584. if tag == "string" or tag == "number" or tag == "key" or tag == "symbol" then
  9585. return visitor(node, visitor)
  9586. elseif tag == "list" then
  9587. local first = car1(node)
  9588. first = visitor(first, visitor)
  9589. node[1] = first
  9590. if type1(first) == "symbol" then
  9591. local func = first["var"]
  9592. local funct = func["kind"]
  9593. if funct == "defined" or funct == "arg" or funct == "native" or funct == "macro" then
  9594. traverseList1(node, 1, visitor)
  9595. return visitor(node, visitor)
  9596. elseif func == builtins1["lambda"] then
  9597. traverseBlock1(node, 3, visitor)
  9598. return visitor(node, visitor)
  9599. elseif func == builtins1["cond"] then
  9600. local forLimit = n1(node)
  9601. local i = 2
  9602. while i <= forLimit do
  9603. local case = nth1(node, i)
  9604. case[1] = traverseNode1(nth1(case, 1), visitor)
  9605. traverseBlock1(case, 2, visitor)
  9606. i = i + 1
  9607. end
  9608. return visitor(node, visitor)
  9609. elseif func == builtins1["set!"] then
  9610. node[3] = traverseNode1(nth1(node, 3), visitor)
  9611. return visitor(node, visitor)
  9612. elseif func == builtins1["quote"] then
  9613. return visitor(node, visitor)
  9614. elseif func == builtins1["syntax-quote"] then
  9615. node[2] = traverseQuote1(nth1(node, 2), visitor, 1)
  9616. return visitor(node, visitor)
  9617. elseif func == builtins1["unquote"] or func == builtins1["unquote-splice"] then
  9618. return error1("unquote/unquote-splice should never appear head", 0)
  9619. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  9620. node[n1(node)] = traverseNode1(nth1(node, n1(node)), visitor)
  9621. return visitor(node, visitor)
  9622. elseif func == builtins1["define-native"] then
  9623. return visitor(node, visitor)
  9624. elseif func == builtins1["import"] then
  9625. return visitor(node, visitor)
  9626. elseif func == builtins1["struct-literal"] then
  9627. traverseList1(node, 2, visitor)
  9628. return visitor(node, visitor)
  9629. else
  9630. return error1("Unknown kind " .. funct .. " for variable " .. func["name"], 0)
  9631. end
  9632. else
  9633. traverseList1(node, 1, visitor)
  9634. return visitor(node, visitor)
  9635. end
  9636. else
  9637. return error1("Unknown tag " .. tag)
  9638. end
  9639. end
  9640. traverseBlock1 = function(node, start, visitor)
  9641. local forLimit = n1(node)
  9642. local i = start
  9643. while i <= forLimit do
  9644. node[i] = (traverseNode1(nth1(node, i + 0), visitor))
  9645. i = i + 1
  9646. end
  9647. return node
  9648. end
  9649. traverseList1 = function(node, start, visitor)
  9650. local forLimit = n1(node)
  9651. local i = start
  9652. while i <= forLimit do
  9653. node[i] = traverseNode1(nth1(node, i), visitor)
  9654. i = i + 1
  9655. end
  9656. return node
  9657. end
  9658. metavar_3f_1 = function(x)
  9659. return x["var"] == nil and sub1(symbol_2d3e_string1(x), 1, 1) == "?"
  9660. end
  9661. genvar_3f_1 = function(x)
  9662. return x["var"] == nil and sub1(symbol_2d3e_string1(x), 1, 1) == "%"
  9663. end
  9664. builtinPtrn_21_1 = function(ptrn)
  9665. local temp = type1(ptrn)
  9666. if temp == "string" then
  9667. return ptrn
  9668. elseif temp == "number" then
  9669. return ptrn
  9670. elseif temp == "key" then
  9671. return ptrn
  9672. elseif temp == "symbol" then
  9673. ptrn["var"] = builtins1[(ptrn["contents"])]
  9674. return ptrn
  9675. elseif temp == "list" then
  9676. local forLimit = n1(ptrn)
  9677. local i = 1
  9678. while i <= forLimit do
  9679. ptrn[i] = builtinPtrn_21_1(nth1(ptrn, i))
  9680. i = i + 1
  9681. end
  9682. return ptrn
  9683. else
  9684. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  9685. end
  9686. end
  9687. fusionPatterns1 = list1({from=builtinPtrn_21_1({tag="list", n=3, {tag="symbol", contents="cond"}, {tag="list", n=2, {tag="list", n=3, {tag="symbol", contents="cond"}, {tag="list", n=2, {tag="symbol", contents="?x"}, {tag="symbol", contents="false"}}, {tag="list", n=2, {tag="symbol", contents="true"}, {tag="symbol", contents="true"}}}, {tag="symbol", contents="false"}}, {tag="list", n=2, {tag="symbol", contents="true"}, {tag="symbol", contents="true"}}}), to=builtinPtrn_21_1({tag="list", n=3, {tag="symbol", contents="cond"}, {tag="list", n=2, {tag="symbol", contents="?x"}, {tag="symbol", contents="true"}}, {tag="list", n=2, {tag="symbol", contents="true"}, {tag="symbol", contents="false"}}})})
  9688. peq_3f_1 = function(x, y, out)
  9689. if x == y then
  9690. return true
  9691. else
  9692. local tyX, tyY = type1(x), type1(y)
  9693. if tyX == "symbol" and metavar_3f_1(x) then
  9694. out[symbol_2d3e_string1(x)] = y
  9695. return true
  9696. elseif tyX ~= tyY then
  9697. return false
  9698. elseif tyX == "symbol" then
  9699. return x["var"] == y["var"]
  9700. elseif tyX == "string" then
  9701. return constVal1(x) == constVal1(y)
  9702. elseif tyX == "number" then
  9703. return constVal1(x) == constVal1(y)
  9704. elseif tyX == "key" then
  9705. return constVal1(x) == constVal1(y)
  9706. elseif tyX == "list" then
  9707. if n1(x) == n1(y) then
  9708. local ok = true
  9709. local forLimit = n1(x)
  9710. local i = 1
  9711. while i <= forLimit do
  9712. if ok and not peq_3f_1(nth1(x, i), nth1(y, i), out) then
  9713. ok = false
  9714. end
  9715. i = i + 1
  9716. end
  9717. return ok
  9718. else
  9719. return false
  9720. end
  9721. else
  9722. _error("unmatched item")
  9723. end
  9724. end
  9725. end
  9726. substitute1 = function(x, subs, syms)
  9727. local temp = type1(x)
  9728. if temp == "string" then
  9729. return x
  9730. elseif temp == "number" then
  9731. return x
  9732. elseif temp == "key" then
  9733. return x
  9734. elseif temp == "symbol" then
  9735. if metavar_3f_1(x) then
  9736. local res = subs[symbol_2d3e_string1(x)]
  9737. if res == nil then
  9738. error1("Unknown capture " .. pretty1(x), 0)
  9739. end
  9740. return res
  9741. elseif genvar_3f_1(x) then
  9742. local name = symbol_2d3e_string1(x)
  9743. local sym = syms[name]
  9744. if not sym then
  9745. sym = {tag="symbol", contents=name, var={tag="var", kind="arg", name=name}}
  9746. syms[name] = sym
  9747. end
  9748. return sym
  9749. else
  9750. local var = x["var"]
  9751. return {tag="symbol", contents=var["name"], var=var}
  9752. end
  9753. elseif temp == "list" then
  9754. return map2(function(temp1)
  9755. return substitute1(temp1, subs, syms)
  9756. end, x)
  9757. else
  9758. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  9759. end
  9760. end
  9761. fusion1 = {name="fusion", help="Merges various loops together as specified by a pattern.", cat={tag="list", n=4, "opt", "transform", "transform-pre", "transform-post"}, level=2, run=function(temp, state, node)
  9762. if type1(node) == "list" then
  9763. local forLimit = n1(fusionPatterns1)
  9764. local i = 1
  9765. while i <= forLimit do
  9766. local ptrn, subs = fusionPatterns1[i], {}
  9767. if peq_3f_1(ptrn["from"], node, subs) then
  9768. temp["changed"] = temp["changed"] + 1
  9769. node = substitute1(ptrn["to"], subs, {})
  9770. end
  9771. i = i + 1
  9772. end
  9773. end
  9774. return node
  9775. end}
  9776. addRule_21_1 = function(rule)
  9777. if type1(rule) ~= "table" then
  9778. error1(demandFailure1(nil, "(= (type rule) \"table\")"))
  9779. end
  9780. push_21_1(fusionPatterns1, rule)
  9781. return nil
  9782. end
  9783. stripImport1 = {name="strip-import", help="Strip all import expressions in NODES", cat={tag="list", n=2, "opt", "transform-pre-block"}, run=function(temp, state, nodes, start)
  9784. local forStart = n1(nodes)
  9785. local i = forStart
  9786. while i >= start do
  9787. local node = nth1(nodes, i)
  9788. if type1(node) == "list" and builtin_3f_1(car1(node), "import") then
  9789. if i == n1(nodes) then
  9790. nodes[i] = makeNil1()
  9791. else
  9792. removeNth_21_1(nodes, i)
  9793. end
  9794. temp["changed"] = temp["changed"] + 1
  9795. end
  9796. i = i + -1
  9797. end
  9798. return nil
  9799. end}
  9800. stripPure1 = {name="strip-pure", help="Strip all pure expressions in NODES (apart from the last one).", cat={tag="list", n=2, "opt", "transform-pre-block"}, run=function(temp, state, nodes, start)
  9801. local forStart = n1(nodes) - 1
  9802. local i = forStart
  9803. while i >= start do
  9804. if not sideEffect_3f_1((nth1(nodes, i))) then
  9805. removeNth_21_1(nodes, i)
  9806. temp["changed"] = temp["changed"] + 1
  9807. end
  9808. i = i + -1
  9809. end
  9810. return nil
  9811. end}
  9812. constantFold1 = {name="constant-fold", help="A primitive constant folder\n\nThis simply finds function calls with constant functions and looks up the function.\nIf the function is native and pure then we'll execute it and replace the node with the\nresult. There are a couple of caveats:\n\n - If the function call errors then we will flag a warning and continue.\n - If this returns a decimal (or infinity or NaN) then we'll continue: we cannot correctly\n accurately handle this.\n - If this doesn't return exactly one value then we will stop. This might be a future enhancement.", cat={tag="list", n=2, "opt", "transform-post"}, run=function(temp, state, node)
  9813. if type1(node) == "list" and fastAll1(constant_3f_1, node, 2) then
  9814. local head = car1(node)
  9815. local meta = type1(head) == "symbol" and (not head["folded"] and (head["var"]["kind"] == "native" and varNative1(head["var"])))
  9816. if meta and (meta["pure"] and function_3f_1(getNative1(head["var"]))) then
  9817. local res = list1(pcall1(meta["value"], splice1(map2(urn_2d3e_val1, slicingView1(node, 1)))))
  9818. if car1(res) then
  9819. local val = nth1(res, 2)
  9820. if n1(res) ~= 2 or number_3f_1(val) and (cadr1(list1(modf1(val))) ~= 0 or abs1(val) == huge1) then
  9821. head["folded"] = true
  9822. return node
  9823. else
  9824. temp["changed"] = temp["changed"] + 1
  9825. return val_2d3e_urn1(val)
  9826. end
  9827. else
  9828. head["folded"] = true
  9829. putNodeWarning_21_1(state["logger"], "Cannot execute constant expression", node["source"], nil, sourceRange1(node["source"]), "Executed " .. pretty1(node) .. ", failed with: " .. nth1(res, 2))
  9830. return node
  9831. end
  9832. else
  9833. return node
  9834. end
  9835. else
  9836. return node
  9837. end
  9838. end}
  9839. condFold1 = {name="cond-fold", help="Simplify all `cond` nodes, removing `false` branches and killing\nall branches after a `true` one.", cat={tag="list", n=2, "opt", "transform-post"}, run=function(temp, state, node)
  9840. if type1(node) == "list" and builtin_3f_1(car1(node), "cond") then
  9841. local final, i = false, 2
  9842. while i <= n1(node) do
  9843. local elem = nth1(node, i)
  9844. if final then
  9845. temp["changed"] = temp["changed"] + 1
  9846. removeNth_21_1(node, i)
  9847. else
  9848. local temp1 = urn_2d3e_bool1(car1(elem))
  9849. if temp1 == false then
  9850. temp["changed"] = temp["changed"] + 1
  9851. removeNth_21_1(node, i)
  9852. elseif temp1 == true then
  9853. if not builtin_3f_1(car1(elem), "true") then
  9854. temp["changed"] = temp["changed"] + 1
  9855. elem[1] = (function()
  9856. local var = builtins1["true"]
  9857. return {tag="symbol", contents=var["name"], var=var}
  9858. end)()
  9859. end
  9860. final = true
  9861. i = i + 1
  9862. elseif temp1 == nil then
  9863. i = i + 1
  9864. else
  9865. error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp1) .. ", but none matched.\n" .. " Tried: `false`\n Tried: `true`\n Tried: `nil`")
  9866. end
  9867. end
  9868. end
  9869. if n1(node) == 2 and builtin_3f_1(car1(nth1(node, 2)), "true") then
  9870. temp["changed"] = temp["changed"] + 1
  9871. local body = slicingView1(nth1(node, 2), 1)
  9872. if n1(body) == 1 then
  9873. return car1(body)
  9874. else
  9875. return makeProgn1(slicingView1(nth1(node, 2), 1))
  9876. end
  9877. else
  9878. local temp1
  9879. if n1(node) > 1 then
  9880. local branch = last1(node)
  9881. temp1 = n1(branch) == 2 and (builtin_3f_1(car1(branch), "true") and (type1((cadr1(branch))) == "list" and builtin_3f_1(caadr1(branch), "cond")))
  9882. else
  9883. temp1 = false
  9884. end
  9885. if temp1 then
  9886. local childCond = nth1(popLast_21_1(node), 2)
  9887. local forLimit = n1(childCond)
  9888. local i1 = 2
  9889. while i1 <= forLimit do
  9890. push_21_1(node, nth1(childCond, i1))
  9891. i1 = i1 + 1
  9892. end
  9893. temp["changed"] = temp["changed"] + 1
  9894. return node
  9895. else
  9896. return node
  9897. end
  9898. end
  9899. else
  9900. return node
  9901. end
  9902. end}
  9903. lambdaFold1 = {name="lambda-fold", help="Simplify all directly called lambdas without arguments, inlining them\nwere appropriate.", cat={tag="list", n=3, "opt", "deforest", "transform-post-bind"}, run=function(temp, state, node)
  9904. if simpleBinding_3f_1(node) then
  9905. local vars, nodeLam = {}, car1(node)
  9906. local nodeArgs = nth1(nodeLam, 2)
  9907. local argN, valN, i = n1(nodeArgs), n1(node) - 1, 1
  9908. if valN <= argN then
  9909. local forLimit = n1(nodeArgs)
  9910. local i1 = 1
  9911. while i1 <= forLimit do
  9912. vars[nodeArgs[i1]["var"]] = true
  9913. i1 = i1 + 1
  9914. end
  9915. while i <= valN and not builtin_3f_1(nth1(node, i + 1), "nil") do
  9916. i = i + 1
  9917. end
  9918. if i <= argN then
  9919. while not ((i > argN)) do
  9920. local head = nth1(nodeLam, 3)
  9921. if type1(head) == "list" and (builtin_3f_1(car1(head), "set!") and (nth1(head, 2)["var"] == nth1(nodeArgs, i)["var"] and not nodeContainsVars_3f_1(nth1(head, 3), vars))) then
  9922. while valN < i do
  9923. push_21_1(node, makeNil1())
  9924. valN = valN + 1
  9925. end
  9926. removeNth_21_1(nodeLam, 3)
  9927. node[i + 1] = nth1(head, 3)
  9928. temp["changed"] = temp["changed"] + 1
  9929. end
  9930. i = i + 1
  9931. end
  9932. end
  9933. end
  9934. end
  9935. if simpleBinding_3f_1(node) then
  9936. local vars, nodeLam = {}, car1(node)
  9937. local nodeArgs = nth1(nodeLam, 2)
  9938. local forLimit = n1(nodeArgs)
  9939. local i = 1
  9940. while i <= forLimit do
  9941. vars[nodeArgs[i]["var"]] = true
  9942. i = i + 1
  9943. end
  9944. local child = nth1(nodeLam, 3)
  9945. while true do
  9946. if (not simpleBinding_3f_1(child) or n1(nodeArgs) ~= n1(node) - 1 or n1(nodeLam) > 3) then
  9947. return nil
  9948. else
  9949. local args = nth1(car1(child), 2)
  9950. while true do
  9951. local val = nth1(child, 2)
  9952. if empty_3f_1(args) then
  9953. break
  9954. elseif not val then
  9955. local forLimit = n1(args)
  9956. local i = 1
  9957. while i <= forLimit do
  9958. temp["changed"] = temp["changed"] + 1
  9959. local arg = removeNth_21_1(args, 1)
  9960. push_21_1(nodeArgs, arg)
  9961. vars[arg["var"]] = true
  9962. i = i + 1
  9963. end
  9964. break
  9965. elseif nodeContainsVars_3f_1(val, vars) then
  9966. break
  9967. else
  9968. temp["changed"] = temp["changed"] + 1
  9969. push_21_1(node, removeNth_21_1(child, 2))
  9970. local arg = removeNth_21_1(args, 1)
  9971. push_21_1(nodeArgs, arg)
  9972. vars[arg["var"]] = true
  9973. end
  9974. end
  9975. if empty_3f_1(args) and n1(child) == 1 then
  9976. removeNth_21_1(nodeLam, 3)
  9977. local lam = car1(child)
  9978. local forLimit = n1(lam)
  9979. local i = 3
  9980. while i <= forLimit do
  9981. insertNth_21_1(nodeLam, i, nth1(lam, i))
  9982. i = i + 1
  9983. end
  9984. child = nth1(nodeLam, 3)
  9985. else
  9986. return nil
  9987. end
  9988. end
  9989. end
  9990. else
  9991. return nil
  9992. end
  9993. end}
  9994. wrapValueFlatten1 = {name="wrap-value-flatten", help="Flatten \"value wrappers\": lambdas with a single argument which\nprevent returning multiple values.", cat={tag="list", n=2, "opt", "transform-post"}, run=function(temp, state, node)
  9995. local temp1
  9996. if type1(node) == "list" then
  9997. local head = car1(node)
  9998. temp1 = type1(head) ~= "symbol" or head["var"]["kind"] ~= "builtin"
  9999. else
  10000. temp1 = false
  10001. end
  10002. if temp1 then
  10003. local forLimit = max1(1, n1(node) - 1)
  10004. local i = 1
  10005. while i <= forLimit do
  10006. local arg = nth1(node, i)
  10007. local temp1
  10008. if type1(arg) == "list" then
  10009. if n1(arg) == 2 then
  10010. local head = car1(arg)
  10011. temp1 = type1(head) == "list" and (n1(head) == 3 and (builtin_3f_1(car1(head), "lambda") and (n1(nth1(head, 2)) == 1 and (not car1(nth1(head, 2))["var"]["is-variadic"] and (type1((nth1(head, 3))) == "symbol" and nth1(head, 3)["var"] == car1(nth1(head, 2))["var"])))))
  10012. else
  10013. temp1 = false
  10014. end
  10015. else
  10016. temp1 = false
  10017. end
  10018. if temp1 then
  10019. temp["changed"] = temp["changed"] + 1
  10020. node[i] = cadr1(arg)
  10021. end
  10022. i = i + 1
  10023. end
  10024. end
  10025. return node
  10026. end}
  10027. prognFoldExpr1 = {name="progn-fold-expr", help="Reduce [[progn]]-like nodes with a single body element into a single\nexpression.", cat={tag="list", n=3, "opt", "deforest", "transform-post"}, run=function(temp, state, node)
  10028. if type1(node) == "list" and (n1(node) == 1 and (type1((car1(node))) == "list" and (builtin_3f_1(caar1(node), "lambda") and (n1(car1(node)) == 3 and empty_3f_1(nth1(car1(node), 2)))))) then
  10029. temp["changed"] = temp["changed"] + 1
  10030. return nth1(car1(node), 3)
  10031. else
  10032. return node
  10033. end
  10034. end}
  10035. prognFoldBlock1 = {name="progn-fold-block", help="Reduce [[progn]]-like nodes with a single body element into a single\nexpression.", cat={tag="list", n=3, "opt", "deforest", "transform-post-block"}, run=function(temp, state, nodes, start)
  10036. local i, len = start, n1(nodes)
  10037. while i <= len do
  10038. local node = nth1(nodes, i)
  10039. if type1(node) == "list" and (n1(node) == 1 and (type1((car1(node))) == "list" and (builtin_3f_1(car1(car1(node)), "lambda") and empty_3f_1(nth1(car1(node), 2))))) then
  10040. local body = car1(node)
  10041. temp["changed"] = temp["changed"] + 1
  10042. if n1(body) == 2 then
  10043. removeNth_21_1(nodes, i)
  10044. else
  10045. nodes[i] = nth1(body, 3)
  10046. local forLimit = n1(body)
  10047. local j = 4
  10048. while j <= forLimit do
  10049. insertNth_21_1(nodes, i + (j - 3), nth1(body, j))
  10050. j = j + 1
  10051. end
  10052. end
  10053. len = len + (n1(node) - 1)
  10054. else
  10055. i = i + 1
  10056. end
  10057. end
  10058. return nil
  10059. end}
  10060. stripDefsFast1 = function(nodes)
  10061. local defs = {}
  10062. local forLimit = n1(nodes)
  10063. local i = 1
  10064. while i <= forLimit do
  10065. local node = nodes[i]
  10066. if type1(node) == "list" then
  10067. local var = node["def-var"]
  10068. if var then
  10069. defs[var] = node
  10070. end
  10071. end
  10072. i = i + 1
  10073. end
  10074. local visited, queue = {}, {tag="list", n=0}
  10075. local visitor = function(node, visitor1)
  10076. local temp = type1(node)
  10077. if temp == "symbol" then
  10078. local var = node["var"]
  10079. local def = defs[var]
  10080. if def and not visited[var] then
  10081. visited[var] = true
  10082. return push_21_1(queue, def)
  10083. else
  10084. return nil
  10085. end
  10086. elseif temp == "list" then
  10087. if builtin_3f_1(car1(node), "set!") then
  10088. return visitor1(cadr1(node))
  10089. else
  10090. return nil
  10091. end
  10092. else
  10093. return nil
  10094. end
  10095. end
  10096. local forLimit = n1(nodes)
  10097. local i = 1
  10098. while i <= forLimit do
  10099. local node = nodes[i]
  10100. if not node["def-var"] then
  10101. visitNode1(node, visitor)
  10102. end
  10103. i = i + 1
  10104. end
  10105. while n1(queue) > 0 do
  10106. visitNode1(popLast_21_1(queue), visitor)
  10107. end
  10108. local forStart = n1(nodes)
  10109. local i = forStart
  10110. while i >= 1 do
  10111. local var = nth1(nodes, i)["def-var"]
  10112. if var and not visited[var] then
  10113. if i == n1(nodes) then
  10114. nodes[i] = makeNil1()
  10115. else
  10116. removeNth_21_1(nodes, i)
  10117. end
  10118. end
  10119. i = i + -1
  10120. end
  10121. return nil
  10122. end
  10123. getConstantVal1 = function(lookup, sym)
  10124. local var, def = sym["var"], getVar1(lookup, sym["var"])
  10125. if var == builtins1["true"] then
  10126. return sym
  10127. elseif var == builtins1["false"] then
  10128. return sym
  10129. elseif var == builtins1["nil"] then
  10130. return sym
  10131. elseif n1(def["defs"]) == 1 then
  10132. local ent = car1(def["defs"])
  10133. local val, ty = ent["value"], type1(ent)
  10134. if string_3f_1(val) or number_3f_1(val) or type1(val) == "key" then
  10135. return val
  10136. elseif type1(val) == "symbol" and ty == "val" then
  10137. return getConstantVal1(lookup, val) or sym
  10138. else
  10139. return sym
  10140. end
  10141. else
  10142. return nil
  10143. end
  10144. end
  10145. removeReferences1 = function(vars, nodes, start)
  10146. if (not next1(vars)) then
  10147. return nil
  10148. else
  10149. return traverseList1(nodes, start, function(node)
  10150. local temp = type1(node)
  10151. if temp == "symbol" then
  10152. if vars[node["var"]] then
  10153. return makeNil1()
  10154. else
  10155. return node
  10156. end
  10157. elseif temp == "list" then
  10158. if builtin_3f_1(car1(node), "set!") and vars[nth1(node, 2)["var"]] then
  10159. local val = nth1(node, 3)
  10160. if sideEffect_3f_1(val) then
  10161. return makeProgn1(list1(val, makeNil1()))
  10162. else
  10163. return makeNil1()
  10164. end
  10165. else
  10166. return node
  10167. end
  10168. else
  10169. return node
  10170. end
  10171. end)
  10172. end
  10173. end
  10174. stripDefs1 = {name="strip-defs", help="Strip all unused top level definitions.", cat={tag="list", n=2, "opt", "usage"}, run=function(temp, state, nodes, lookup)
  10175. local removed = {}
  10176. local forStart = n1(nodes)
  10177. local i = forStart
  10178. while i >= 1 do
  10179. local node = nth1(nodes, i)
  10180. if node["def-var"] and not getVar1(lookup, node["def-var"])["active"] then
  10181. if i == n1(nodes) then
  10182. nodes[i] = makeNil1()
  10183. else
  10184. removeNth_21_1(nodes, i)
  10185. end
  10186. removed[node["def-var"]] = true
  10187. temp["changed"] = temp["changed"] + 1
  10188. end
  10189. i = i + -1
  10190. end
  10191. return removeReferences1(removed, nodes, 1)
  10192. end}
  10193. stripArgs1 = {name="strip-args", help="Strip all unused, pure arguments in directly called lambdas.", cat={tag="list", n=3, "opt", "usage", "transform-post-bind"}, run=function(temp, state, node, lookup)
  10194. local lam = car1(node)
  10195. local lamArgs, argOffset, valOffset, removed = nth1(lam, 2), 1, 2, {}
  10196. local temp1 = zipArgs1(lamArgs, 1, node, 2)
  10197. local forLimit = n1(temp1)
  10198. local i = 1
  10199. while i <= forLimit do
  10200. local zipped = temp1[i]
  10201. local args = car1(zipped)
  10202. local arg, vals = car1(args), cadr1(zipped)
  10203. if n1(args) > 1 or arg and n1(getVar1(lookup, arg["var"])["usages"]) > 0 or any1(sideEffect_3f_1, vals) then
  10204. argOffset = argOffset + n1(args)
  10205. valOffset = argOffset + n1(vals)
  10206. else
  10207. temp["changed"] = temp["changed"] + 1
  10208. if arg then
  10209. removed[arg["var"]] = true
  10210. removeNth_21_1(lamArgs, argOffset)
  10211. end
  10212. local forLimit1 = n1(vals)
  10213. local i1 = 1
  10214. while i1 <= forLimit1 do
  10215. local val = vals[i1]
  10216. removeNth_21_1(node, valOffset)
  10217. i1 = i1 + 1
  10218. end
  10219. end
  10220. i = i + 1
  10221. end
  10222. return removeReferences1(removed, lam, 3)
  10223. end}
  10224. variableFold1 = {name="variable-fold", help="Folds constant variable accesses", cat={tag="list", n=3, "opt", "usage", "transform-pre"}, run=function(temp, state, node, lookup)
  10225. if type1(node) == "symbol" then
  10226. local replace = getConstantVal1(lookup, node)
  10227. if replace and replace ~= node then
  10228. removeUsage_21_1(lookup, node["var"], node)
  10229. if type1(replace) == "symbol" then
  10230. replace = copyOf1(replace)
  10231. addUsage_21_1(lookup, replace["var"], replace)
  10232. end
  10233. temp["changed"] = temp["changed"] + 1
  10234. return replace
  10235. else
  10236. return node
  10237. end
  10238. else
  10239. return node
  10240. end
  10241. end}
  10242. expressionFold1 = {name="expression-fold", help="Folds basic variable accesses where execution order will not change.\n\nFor instance, converts ((lambda (x) (+ x 1)) (Y)) to (+ Y 1) in the\ncase where Y is an arbitrary expression.\n\nThere are a couple of complexities in the implementation\nhere. Firstly, we want to ensure that the arguments are executed in\nthe correct order and only once.\n\nIn order to achieve this, we find the lambda forms and visit the body,\nstopping if we visit arguments in the wrong order or non-constant\nterms such as mutable variables or other function calls. For\nsimplicity's sake, we fail if we hit other lambdas or conds as that\nmakes analysing control flow significantly more complex.\n\nAnother source of added complexity is the case where where Y could\nreturn multiple values: namely in the last argument to function\ncalls. Here it is an invalid optimisation to just place Y, as that\ncould result in additional values being passed to the function.\n\nIn order to avoid this, Y will get converted to the\nform ((lambda (<tmp>) <tmp>) Y). This is understood by the codegen\nand so is not as inefficient as it looks. However, we do have to take\nadditional steps to avoid trying to fold the above again and again.\n\nWe use post-bind rather than pre-bind as that enables us to benefit\nfrom any optimisations inside the node. We're not going to be moving\nany simple, constant-foldable expressions around. After all, that's\ncovered by [[variable-fold]].", cat={tag="list", n=3, "opt", "usage", "transform-post-bind"}, run=function(temp, state, root, lookup)
  10243. local lam, args, len, validate = car1(root)
  10244. args = nth1(lam, 2)
  10245. len = n1(args)
  10246. validate = function(i)
  10247. while true do
  10248. if i > len then
  10249. return true
  10250. else
  10251. local var = nth1(args, i)["var"]
  10252. local entry = getVar1(lookup, var)
  10253. if var["is-variadic"] then
  10254. return false
  10255. elseif n1(entry["defs"]) ~= 1 then
  10256. return false
  10257. elseif type1(car1(entry["defs"])) == "var" then
  10258. return false
  10259. elseif n1(entry["usages"]) ~= 1 then
  10260. return false
  10261. else
  10262. i = i + 1
  10263. end
  10264. end
  10265. end
  10266. end
  10267. if len > 0 and ((n1(root) ~= 2 or len ~= 1 or n1(lam) ~= 3 or singleReturn_3f_1(nth1(root, 2)) or type1((nth1(lam, 3))) ~= "symbol" or nth1(lam, 3)["var"] ~= car1(args)["var"]) and validate(1)) then
  10268. local currentIdx, argMap, wrapMap, ok, finished = 1, {}, {}, true, false
  10269. local forLimit = n1(args)
  10270. local i = 1
  10271. while i <= forLimit do
  10272. argMap[nth1(args, i)["var"]] = i
  10273. i = i + 1
  10274. end
  10275. visitBlock1(lam, 3, function(node, visitor)
  10276. if ok and not finished then
  10277. local temp1 = type1(node)
  10278. if temp1 == "string" then
  10279. return nil
  10280. elseif temp1 == "number" then
  10281. return nil
  10282. elseif temp1 == "key" then
  10283. return nil
  10284. elseif temp1 == "symbol" then
  10285. local idx = argMap[node["var"]]
  10286. if idx == nil then
  10287. if n1(getVar1(lookup, node["var"])["defs"]) > 1 then
  10288. ok = false
  10289. return false
  10290. else
  10291. return nil
  10292. end
  10293. elseif idx == currentIdx then
  10294. currentIdx = currentIdx + 1
  10295. if currentIdx > len then
  10296. finished = true
  10297. return nil
  10298. else
  10299. return nil
  10300. end
  10301. else
  10302. ok = false
  10303. return false
  10304. end
  10305. elseif temp1 == "list" then
  10306. local head = car1(node)
  10307. local temp2 = type1(head)
  10308. if temp2 == "symbol" then
  10309. local var = head["var"]
  10310. if var["kind"] ~= "builtin" then
  10311. visitBlock1(node, 1, visitor)
  10312. if n1(node) > 1 then
  10313. local last = nth1(node, n1(node))
  10314. if type1(last) == "symbol" then
  10315. local idx = argMap[last["var"]]
  10316. if idx then
  10317. if type1((root[idx + 1])) == "list" then
  10318. wrapMap[idx] = true
  10319. end
  10320. end
  10321. end
  10322. end
  10323. elseif var == builtins1["set!"] then
  10324. visitNode1(nth1(node, 3), visitor)
  10325. elseif var == builtins1["define"] then
  10326. visitNode1(last1(node), visitor)
  10327. elseif var == builtins1["define-macro"] then
  10328. visitNode1(last1(node), visitor)
  10329. elseif var == builtins1["define-native"] then
  10330. elseif var == builtins1["cond"] then
  10331. visitNode1(car1(nth1(node, 2)), visitor)
  10332. elseif var == builtins1["lambda"] then
  10333. elseif var == builtins1["quote"] then
  10334. elseif var == builtins1["import"] then
  10335. elseif var == builtins1["syntax-quote"] then
  10336. visitQuote1(nth1(node, 2), visitor, 1)
  10337. elseif var == builtins1["struct-literal"] then
  10338. visitBlock1(node, 2, visitor)
  10339. else
  10340. _error("unmatched item")
  10341. end
  10342. if finished then
  10343. elseif var == builtins1["set!"] then
  10344. ok = false
  10345. elseif var == builtins1["cond"] then
  10346. ok = false
  10347. elseif var == builtins1["lambda"] then
  10348. ok = false
  10349. else
  10350. ok = false
  10351. end
  10352. return false
  10353. elseif temp2 == "list" then
  10354. if builtin_3f_1(car1(head), "lambda") then
  10355. visitBlock1(node, 2, visitor)
  10356. visitBlock1(head, 3, visitor)
  10357. return false
  10358. else
  10359. ok = false
  10360. return false
  10361. end
  10362. else
  10363. ok = false
  10364. return false
  10365. end
  10366. else
  10367. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp1) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  10368. end
  10369. else
  10370. return false
  10371. end
  10372. end)
  10373. if ok and finished then
  10374. temp["changed"] = temp["changed"] + 1
  10375. traverseList1(root, 1, function(child)
  10376. if type1(child) == "symbol" then
  10377. local var = child["var"]
  10378. local i = argMap[var]
  10379. if i then
  10380. if wrapMap[i] then
  10381. return {tag="list", n=2, {tag="list", n=3, (function()
  10382. local var2 = builtins1["lambda"]
  10383. return {tag="symbol", contents=var2["name"], var=var2}
  10384. end)(), {tag="list", n=1, {tag="symbol", contents=var["name"], var=var}}, {tag="symbol", contents=var["name"], var=var}}, nth1(root, i + 1)}
  10385. else
  10386. return nth1(root, i + 1) or makeNil1()
  10387. end
  10388. else
  10389. return child
  10390. end
  10391. else
  10392. return child
  10393. end
  10394. end)
  10395. local forStart = n1(root)
  10396. local i = forStart
  10397. while i >= 2 do
  10398. removeNth_21_1(root, i)
  10399. i = i + -1
  10400. end
  10401. local forStart = n1(args)
  10402. local i = forStart
  10403. while i >= 1 do
  10404. removeNth_21_1(args, i)
  10405. i = i + -1
  10406. end
  10407. return nil
  10408. else
  10409. return nil
  10410. end
  10411. else
  10412. return nil
  10413. end
  10414. end}
  10415. condEliminate1 = {name="cond-eliminate", help="Replace variables with known truthy/falsey values with `true` or\n`false` when used in branches.", cat={tag="list", n=2, "opt", "usage"}, run=function(temp, state, nodes, varLookup)
  10416. local lookup = {}
  10417. return visitBlock1(nodes, 1, function(node, visitor, isCond)
  10418. local temp1 = type1(node)
  10419. if temp1 == "symbol" then
  10420. if isCond then
  10421. local temp2 = lookup[node["var"]]
  10422. if temp2 == false then
  10423. if node["var"] ~= builtins1["false"] then
  10424. local var = builtins1["false"]
  10425. return {tag="symbol", contents=var["name"], var=var}
  10426. else
  10427. return nil
  10428. end
  10429. elseif temp2 == true then
  10430. if node["var"] ~= builtins1["true"] then
  10431. local var = builtins1["true"]
  10432. return {tag="symbol", contents=var["name"], var=var}
  10433. else
  10434. return nil
  10435. end
  10436. else
  10437. return nil
  10438. end
  10439. else
  10440. return nil
  10441. end
  10442. elseif temp1 == "list" then
  10443. local head = car1(node)
  10444. local temp2 = type1(head)
  10445. if temp2 == "symbol" then
  10446. if builtin_3f_1(head, "cond") then
  10447. local vars = {tag="list", n=0}
  10448. local forLimit = n1(node)
  10449. local i = 2
  10450. while i <= forLimit do
  10451. local entry = nth1(node, i)
  10452. local test, len = car1(entry), n1(entry)
  10453. local var = type1(test) == "symbol" and test["var"]
  10454. if var then
  10455. if lookup[var] ~= nil then
  10456. var = nil
  10457. elseif n1(getVar1(varLookup, var)["defs"]) > 1 then
  10458. var = nil
  10459. end
  10460. end
  10461. local temp3 = visitor(test, visitor, true)
  10462. if temp3 == nil then
  10463. visitNode1(test, visitor)
  10464. elseif temp3 == false then
  10465. else
  10466. temp["changed"] = temp["changed"] + 1
  10467. entry[1] = temp3
  10468. end
  10469. if var then
  10470. push_21_1(vars, var)
  10471. lookup[var] = true
  10472. end
  10473. local forLimit1 = len - 1
  10474. local i1 = 2
  10475. while i1 <= forLimit1 do
  10476. visitNode1(nth1(entry, i1), visitor)
  10477. i1 = i1 + 1
  10478. end
  10479. if len > 1 then
  10480. local last = nth1(entry, len)
  10481. local temp3 = visitor(last, visitor, isCond)
  10482. if temp3 == nil then
  10483. visitNode1(last, visitor)
  10484. elseif temp3 == false then
  10485. else
  10486. temp["changed"] = temp["changed"] + 1
  10487. entry[len] = temp3
  10488. end
  10489. end
  10490. if var then
  10491. lookup[var] = false
  10492. end
  10493. i = i + 1
  10494. end
  10495. local forLimit = n1(vars)
  10496. local i = 1
  10497. while i <= forLimit do
  10498. lookup[vars[i]] = nil
  10499. i = i + 1
  10500. end
  10501. return false
  10502. else
  10503. return nil
  10504. end
  10505. elseif temp2 == "list" then
  10506. if isCond and builtin_3f_1(car1(head), "lambda") then
  10507. local forLimit = n1(node)
  10508. local i = 2
  10509. while i <= forLimit do
  10510. visitNode1(nth1(node, i), visitor)
  10511. i = i + 1
  10512. end
  10513. local len = n1(head)
  10514. local forLimit = len - 1
  10515. local i = 3
  10516. while i <= forLimit do
  10517. visitNode1(nth1(head, i), visitor)
  10518. i = i + 1
  10519. end
  10520. if len > 2 then
  10521. local last = nth1(head, len)
  10522. local temp3 = visitor(last, visitor, isCond)
  10523. if temp3 == nil then
  10524. visitNode1(last, visitor)
  10525. elseif temp3 == false then
  10526. else
  10527. temp["changed"] = temp["changed"] + 1
  10528. node[head] = temp3
  10529. end
  10530. end
  10531. return false
  10532. else
  10533. return nil
  10534. end
  10535. else
  10536. return nil
  10537. end
  10538. else
  10539. return nil
  10540. end
  10541. end)
  10542. end}
  10543. deferrable_3f_1 = function(lookup, node)
  10544. local deferrable = true
  10545. visitNode1(node, function(node1)
  10546. local temp = type1(node1)
  10547. if temp == "string" then
  10548. return nil
  10549. elseif temp == "number" then
  10550. return nil
  10551. elseif temp == "key" then
  10552. return nil
  10553. elseif temp == "symbol" then
  10554. if n1(getVar1(lookup, node1["var"])["defs"]) > 1 then
  10555. deferrable = false
  10556. end
  10557. return deferrable
  10558. elseif temp == "list" then
  10559. if type1(car1(node1)) == "symbol" then
  10560. local var = car1(node1)["var"]
  10561. if var == builtins1["lambda"] then
  10562. return false
  10563. elseif var == builtins1["quote"] then
  10564. return deferrable
  10565. elseif var == builtins1["quasi-quote"] then
  10566. return deferrable
  10567. elseif var == builtins1["struct-literal"] then
  10568. return deferrable
  10569. elseif var == builtins1["cond"] then
  10570. return nil
  10571. else
  10572. deferrable = false
  10573. return false
  10574. end
  10575. else
  10576. deferrable = false
  10577. return false
  10578. end
  10579. else
  10580. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  10581. end
  10582. end)
  10583. return deferrable
  10584. end
  10585. lowerValue1 = {name="lower-value", help="Pushes various values into child nodes, bringing them closer to the\nplace they are used", cat={tag="list", n=3, "opt", "usage", "transform-post-bind"}, run=function(temp, state, node, lookup)
  10586. local lam = car1(node)
  10587. local lamArgs, argOffset, valOffset = nth1(lam, 2), 1, 2
  10588. local temp1 = zipArgs1(lamArgs, 1, node, 2)
  10589. local forLimit = n1(temp1)
  10590. local i = 1
  10591. while i <= forLimit do
  10592. local zipped = temp1[i]
  10593. local args, vals, handled = car1(zipped), cadr1(zipped), false
  10594. if n1(args) == 1 and (not car1(args)["var"]["is-variadic"] and (n1(vals) == 1 and car1(vals) ~= nil)) then
  10595. local var, val = car1(args)["var"], car1(vals)
  10596. if not handled and (type1(val) == "list" and (builtin_3f_1(car1(val), "lambda") and n1(getVar1(lookup, var)["usages"]) == 1)) then
  10597. local users, found = 0, nil
  10598. visitBlock1(lam, 3, function(child)
  10599. if type1(child) == "list" and (type1((car1(child))) == "symbol" and car1(child)["var"] == var) then
  10600. found = child
  10601. elseif type1(child) == "symbol" and child["var"] == var then
  10602. users = users + 1
  10603. end
  10604. local _ = users <= 1
  10605. return nil
  10606. end)
  10607. if found and users == 1 then
  10608. temp["changed"] = temp["changed"] + 1
  10609. handled = true
  10610. found[1] = val
  10611. removeNth_21_1(lamArgs, argOffset)
  10612. removeNth_21_1(node, valOffset)
  10613. end
  10614. end
  10615. if not handled and (not atom_3f_1(val) and deferrable_3f_1(lookup, val)) then
  10616. local cur, start, best = lam, 3, nil
  10617. while true do
  10618. local found
  10619. local i1, found1 = start, nil
  10620. while true do
  10621. if i1 > n1(cur) then
  10622. found = found1
  10623. break
  10624. else
  10625. local curi = nth1(cur, i1)
  10626. if not nodeContainsVar_3f_1(curi, var) then
  10627. i1 = i1 + 1
  10628. elseif found1 then
  10629. found = nil
  10630. break
  10631. else
  10632. i1, found1 = i1 + 1, curi
  10633. end
  10634. end
  10635. end
  10636. local condFound
  10637. local temp2 = type1(found) == "list"
  10638. if temp2 then
  10639. local temp3 = builtin_3f_1(car1(found), "cond")
  10640. if temp3 then
  10641. local i1, block = 2, nil
  10642. while true do
  10643. if i1 > n1(found) then
  10644. condFound = block
  10645. break
  10646. else
  10647. local branch = nth1(found, i1)
  10648. if nodeContainsVar_3f_1(car1(branch), var) then
  10649. condFound = nil
  10650. break
  10651. elseif not fastAny1(function(temp4)
  10652. return nodeContainsVar_3f_1(temp4, var)
  10653. end, branch, 2) then
  10654. i1 = i1 + 1
  10655. elseif block then
  10656. condFound = nil
  10657. break
  10658. else
  10659. i1, block = i1 + 1, branch
  10660. end
  10661. end
  10662. end
  10663. else
  10664. condFound = temp3
  10665. end
  10666. else
  10667. condFound = temp2
  10668. end
  10669. if condFound then
  10670. cur, start, best = condFound, 2, condFound
  10671. elseif type1(found) == "list" and (type1((car1(found))) == "list" and (builtin_3f_1(caar1(found), "lambda") and fastAll1(function(x)
  10672. return not nodeContainsVar_3f_1(x, var)
  10673. end, car1(found), 3))) then
  10674. cur, start = car1(found), 3
  10675. elseif best then
  10676. temp["changed"] = temp["changed"] + 1
  10677. handled = true
  10678. local newBody = {tag="list", n=2, (function()
  10679. local var2 = builtins1["lambda"]
  10680. return {tag="symbol", contents=var2["name"], var=var2}
  10681. end)(), {tag="list", n=1, car1(args)}}
  10682. local forLimit1 = n1(best)
  10683. local i1 = 2
  10684. while i1 <= forLimit1 do
  10685. push_21_1(newBody, removeNth_21_1(best, 2))
  10686. i1 = i1 + 1
  10687. end
  10688. push_21_1(best, list1(newBody, val))
  10689. removeNth_21_1(lamArgs, argOffset)
  10690. removeNth_21_1(node, valOffset)
  10691. break
  10692. else
  10693. break
  10694. end
  10695. end
  10696. end
  10697. end
  10698. if not handled then
  10699. argOffset = argOffset + n1(args)
  10700. valOffset = argOffset + n1(vals)
  10701. end
  10702. i = i + 1
  10703. end
  10704. return nil
  10705. end}
  10706. getScope1 = function(scope, lookup)
  10707. local newScope = lookup["scopes"][scope]
  10708. if newScope then
  10709. return newScope
  10710. else
  10711. local newScope1 = child1()
  10712. lookup["scopes"][scope] = newScope1
  10713. return newScope1
  10714. end
  10715. end
  10716. getVar2 = function(var, lookup)
  10717. return lookup["vars"][var] or var
  10718. end
  10719. copyNode1 = function(node, lookup)
  10720. local temp = type1(node)
  10721. if temp == "string" then
  10722. return copyOf1(node)
  10723. elseif temp == "key" then
  10724. return copyOf1(node)
  10725. elseif temp == "number" then
  10726. return copyOf1(node)
  10727. elseif temp == "symbol" then
  10728. local copy, oldVar = copyOf1(node), node["var"]
  10729. local newVar = getVar2(oldVar, lookup)
  10730. if oldVar ~= newVar and oldVar["node"] == node then
  10731. newVar["node"] = copy
  10732. end
  10733. copy["var"] = newVar
  10734. return copy
  10735. elseif temp == "list" then
  10736. if builtin_3f_1(car1(node), "lambda") then
  10737. local args = cadr1(node)
  10738. if not empty_3f_1(args) then
  10739. local newScope, forLimit = child1(getScope1(car1(args)["var"]["scope"], lookup)), n1(args)
  10740. local i = 1
  10741. while i <= forLimit do
  10742. local var = args[i]["var"]
  10743. local newVar = add_21_1(newScope, var["name"], var["kind"], nil)
  10744. newVar["is-variadic"] = (var["is-variadic"])
  10745. lookup["vars"][var] = newVar
  10746. i = i + 1
  10747. end
  10748. end
  10749. end
  10750. local res = copyOf1(node)
  10751. local forLimit = n1(res)
  10752. local i = 1
  10753. while i <= forLimit do
  10754. res[i] = copyNode1(nth1(res, i), lookup)
  10755. i = i + 1
  10756. end
  10757. return res
  10758. else
  10759. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"key\"`\n Tried: `\"number\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  10760. end
  10761. end
  10762. scoreNode1 = function(node, cumulative, threshold)
  10763. while true do
  10764. local temp = type1(node)
  10765. if temp == "string" then
  10766. return cumulative
  10767. elseif temp == "key" then
  10768. return cumulative
  10769. elseif temp == "number" then
  10770. return cumulative
  10771. elseif temp == "symbol" then
  10772. return cumulative + 1
  10773. elseif temp == "list" then
  10774. local temp1 = type1(car1(node))
  10775. if temp1 == "symbol" then
  10776. local func = car1(node)["var"]
  10777. if func["kind"] ~= "builtin" then
  10778. return scoreNodes1(node, 1, cumulative + n1(node) + 1, threshold)
  10779. elseif func == builtins1["lambda"] then
  10780. return scoreNodes1(node, 3, cumulative + 10, threshold)
  10781. elseif func == builtins1["cond"] then
  10782. cumulative = cumulative + 3
  10783. local len, _ = n1(node)
  10784. local i = 2
  10785. while true do
  10786. if (i > len) then
  10787. break
  10788. else
  10789. cumulative = cumulative + 4
  10790. if cumulative <= threshold then
  10791. cumulative = scoreNodes1(nth1(node, i), 1, cumulative, threshold)
  10792. i = i + 1
  10793. else
  10794. break
  10795. end
  10796. end
  10797. end
  10798. return cumulative
  10799. elseif func == builtins1["set!"] then
  10800. node, cumulative = nth1(node, 3), cumulative + 5
  10801. elseif func == builtins1["quote"] then
  10802. if type1((nth1(node, 2))) == "list" then
  10803. return cumulative + n1(node)
  10804. else
  10805. return cumulative
  10806. end
  10807. elseif func == builtins1["import"] then
  10808. return cumulative
  10809. elseif func == builtins1["syntax-quote"] then
  10810. node, cumulative = nth1(node, 2), cumulative + 3
  10811. elseif func == builtins1["unquote"] then
  10812. node = nth1(node, 2)
  10813. elseif func == builtins1["unquote-splice"] then
  10814. node, cumulative = nth1(node, 2), cumulative + 10
  10815. elseif func == builtins1["struct-literal"] then
  10816. return scoreNodes1(node, 2, cumulative + (n1(node) - 1) / 2 + 3, threshold)
  10817. else
  10818. _error("unmatched item")
  10819. end
  10820. elseif temp1 == "list" then
  10821. if builtin_3f_1(caar1(node), "lambda") then
  10822. local temp2 = scoreNodes1(node, 2, cumulative, threshold)
  10823. return scoreNodes1(car1(node), 3, temp2, threshold)
  10824. else
  10825. return scoreNodes1(node, 1, cumulative + n1(node) + 1, threshold)
  10826. end
  10827. else
  10828. return scoreNodes1(node, 1, cumulative + n1(node) + 1, threshold)
  10829. end
  10830. else
  10831. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"key\"`\n Tried: `\"number\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  10832. end
  10833. end
  10834. end
  10835. scoreNodes1 = function(nodes, start, cumulative, threshold)
  10836. local len, _ = n1(nodes)
  10837. local i = start
  10838. while true do
  10839. if i > len then
  10840. break
  10841. elseif cumulative <= threshold then
  10842. cumulative = scoreNode1(nth1(nodes, i), cumulative, threshold)
  10843. i = i + 1
  10844. else
  10845. break
  10846. end
  10847. end
  10848. return cumulative
  10849. end
  10850. getScore1 = function(lookup, node)
  10851. local score = lookup[node]
  10852. if score == nil then
  10853. score = 0
  10854. local temp = nth1(node, 2)
  10855. local forLimit = n1(temp)
  10856. local i = 1
  10857. while i <= forLimit do
  10858. if temp[i]["var"]["is-variadic"] then
  10859. score = false
  10860. end
  10861. i = i + 1
  10862. end
  10863. if score then
  10864. score = scoreNodes1(node, 3, score, 20)
  10865. end
  10866. lookup[node] = score
  10867. end
  10868. return score or huge1
  10869. end
  10870. inline1 = {name="inline", help="Inline simple functions.", cat={tag="list", n=2, "opt", "usage"}, level=2, run=function(temp, state, nodes, usage)
  10871. local scoreLookup, forLimit = {}, n1(nodes)
  10872. local i = 1
  10873. while i <= forLimit do
  10874. local root = nodes[i]
  10875. visitNode1(root, function(node)
  10876. if type1(node) == "list" and type1((car1(node))) == "symbol" then
  10877. local func = car1(node)["var"]
  10878. local def = getVar1(usage, func)
  10879. if func ~= root["def-var"] and n1(def["defs"]) == 1 then
  10880. local val = car1(def["defs"])["value"]
  10881. if type1(val) == "list" and (builtin_3f_1(car1(val), "lambda") and getScore1(scoreLookup, val) <= 20) then
  10882. node[1] = (copyNode1(val, {scopes={}, vars={}, root=func["scope"]}))
  10883. temp["changed"] = temp["changed"] + 1
  10884. return nil
  10885. else
  10886. return nil
  10887. end
  10888. else
  10889. return nil
  10890. end
  10891. else
  10892. return nil
  10893. end
  10894. end)
  10895. local var = root["def-var"]
  10896. if var then
  10897. scoreLookup[var] = nil
  10898. end
  10899. i = i + 1
  10900. end
  10901. return nil
  10902. end}
  10903. optimiseOnce1 = function(nodes, state, passes)
  10904. local tracker, lookup = {changed=0}, {}
  10905. local temp = passes["normal"]
  10906. local forLimit = n1(temp)
  10907. local i = 1
  10908. while i <= forLimit do
  10909. runPass1(temp[i], state, tracker, nodes, lookup)
  10910. i = i + 1
  10911. end
  10912. if not (empty_3f_1(passes["transform"]) and empty_3f_1(passes["usage"])) then
  10913. runPass1(tagUsage1, state, tracker, nodes, lookup)
  10914. end
  10915. if not empty_3f_1(passes["transform"]) then
  10916. runPass1(transformer1, state, tracker, nodes, lookup, passes["transform"])
  10917. end
  10918. local temp = passes["usage"]
  10919. local forLimit = n1(temp)
  10920. local i = 1
  10921. while i <= forLimit do
  10922. runPass1(temp[i], state, tracker, nodes, lookup)
  10923. i = i + 1
  10924. end
  10925. return tracker["changed"] > 0
  10926. end
  10927. optimise1 = function(nodes, state, passes)
  10928. stripDefsFast1(nodes)
  10929. local maxN, maxT, iteration = state["max-n"], state["max-time"], 0
  10930. local finish, changed = clock1() + maxT, true
  10931. while changed and ((maxN < 0 or iteration < maxN) and (maxT < 0 or clock1() < finish)) do
  10932. changed = optimiseOnce1(nodes, state, passes)
  10933. iteration = iteration + 1
  10934. end
  10935. return nil
  10936. end
  10937. default1 = function()
  10938. return {normal=list1(), usage=list1(stripDefs1, condEliminate1, inline1), transform=list1(stripImport1, stripPure1, constantFold1, condFold1, wrapValueFlatten1, prognFoldExpr1, prognFoldBlock1, variableFold1, stripArgs1, lambdaFold1, lowerValue1, expressionFold1, fusion1)}
  10939. end
  10940. visitQuote4 = function(defined, logger, node, level)
  10941. while true do
  10942. if level == 0 then
  10943. return visitNode4(defined, logger, node)
  10944. elseif type1(node) == "list" then
  10945. local first = nth1(node, 1)
  10946. if type1(first) == "symbol" then
  10947. if first["contents"] == "unquote" or first["contents"] == "unquote-splice" then
  10948. node, level = nth1(node, 2), level - 1
  10949. elseif first["contents"] == "syntax-quote" then
  10950. node, level = nth1(node, 2), level + 1
  10951. else
  10952. local forLimit = n1(node)
  10953. local i = 1
  10954. while i <= forLimit do
  10955. visitQuote4(defined, logger, node[i], level)
  10956. i = i + 1
  10957. end
  10958. return nil
  10959. end
  10960. else
  10961. local forLimit = n1(node)
  10962. local i = 1
  10963. while i <= forLimit do
  10964. visitQuote4(defined, logger, node[i], level)
  10965. i = i + 1
  10966. end
  10967. return nil
  10968. end
  10969. else
  10970. return nil
  10971. end
  10972. end
  10973. end
  10974. visitNode4 = function(defined, logger, node, last)
  10975. while true do
  10976. local temp = type1(node)
  10977. if temp == "string" then
  10978. return nil
  10979. elseif temp == "number" then
  10980. return nil
  10981. elseif temp == "key" then
  10982. return nil
  10983. elseif temp == "symbol" then
  10984. if node["var"]["scope"]["kind"] == "top-level" and not defined[node["var"]] then
  10985. return putNodeWarning_21_1(logger, node["contents"] .. " has not been defined yet", node["source"], "This symbol is not defined until later in the program, but is accessed here.\nConsequently, it's value may be undefined when executing the program.", sourceRange1(node["source"]), "")
  10986. else
  10987. return nil
  10988. end
  10989. elseif temp == "list" then
  10990. local first = nth1(node, 1)
  10991. local firstTy = type1(first)
  10992. if firstTy == "symbol" then
  10993. local func = first["var"]
  10994. local funcTy = func["kind"]
  10995. if funcTy == "defined" or funcTy == "arg" or funcTy == "native" or funcTy == "macro" then
  10996. return visitList1(defined, logger, node, 1)
  10997. elseif func == builtins1["lambda"] then
  10998. if last then
  10999. return nil
  11000. else
  11001. return visitBlock3(defined, logger, node, 3)
  11002. end
  11003. elseif func == builtins1["cond"] then
  11004. local forLimit = n1(node)
  11005. local i = 2
  11006. while i <= forLimit do
  11007. local case = nth1(node, i)
  11008. visitNode4(defined, logger, nth1(case, 1))
  11009. visitBlock3(defined, logger, case, 2, last)
  11010. i = i + 1
  11011. end
  11012. return nil
  11013. elseif func == builtins1["set!"] then
  11014. node, last = nth1(node, 3)
  11015. elseif func == builtins1["struct-literal"] then
  11016. return visitList1(defined, logger, node, 2)
  11017. elseif func == builtins1["syntax-quote"] then
  11018. return visitQuote4(defined, logger, nth1(node, 2), 1)
  11019. elseif func == builtins1["define"] or func == builtins1["define-macro"] then
  11020. visitNode4(defined, logger, nth1(node, n1(node)), true)
  11021. defined[node["def-var"]] = true
  11022. return nil
  11023. elseif func == builtins1["define-native"] then
  11024. defined[node["def-var"]] = true
  11025. return nil
  11026. elseif func == builtins1["quote"] then
  11027. return nil
  11028. elseif func == builtins1["import"] then
  11029. return nil
  11030. elseif func == builtins1["unquote"] or func == builtins1["unquote-splice"] then
  11031. return error1("unquote/unquote-splice should never appear here", 0)
  11032. else
  11033. return error1("Unknown kind " .. funcTy .. " for variable " .. func["name"], 0)
  11034. end
  11035. elseif firstTy == "list" and builtin_3f_1(car1(first), "lambda") then
  11036. visitList1(defined, logger, node, 2)
  11037. return visitBlock3(defined, logger, first, 3, last)
  11038. else
  11039. return visitList1(defined, logger, node, 1)
  11040. end
  11041. else
  11042. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `\"string\"`\n Tried: `\"number\"`\n Tried: `\"key\"`\n Tried: `\"symbol\"`\n Tried: `\"list\"`")
  11043. end
  11044. end
  11045. end
  11046. visitBlock3 = function(defined, logger, node, start, last)
  11047. local forLimit = n1(node) - 1
  11048. local i = start
  11049. while i <= forLimit do
  11050. visitNode4(defined, logger, nth1(node, i))
  11051. i = i + 1
  11052. end
  11053. if n1(node) >= start then
  11054. return visitNode4(defined, logger, nth1(node, n1(node)), last)
  11055. else
  11056. return nil
  11057. end
  11058. end
  11059. visitList1 = function(defined, logger, node, start)
  11060. local forLimit = n1(node)
  11061. local i = start
  11062. while i <= forLimit do
  11063. visitNode4(defined, logger, nth1(node, i))
  11064. i = i + 1
  11065. end
  11066. return nil
  11067. end
  11068. checkOrder1 = {name="check-order", help="Check each node only eagerly accesses nodes defined after it.", cat={tag="list", n=1, "warn"}, run=function(temp, state, nodes)
  11069. return visitList1({}, state["logger"], nodes, 1)
  11070. end}
  11071. checkArity1 = {name="check-arity", help="Produce a warning if any NODE in NODES calls a function with too many arguments.\n\nLOOKUP is the variable usage lookup table.", cat={tag="list", n=2, "warn", "usage"}, run=function(temp, state, nodes, lookup)
  11072. local arity, updateArity_21_, getArity = {}
  11073. updateArity_21_ = function(var, min, max)
  11074. local ari = list1(min, max)
  11075. arity[var] = ari
  11076. return ari
  11077. end
  11078. getArity = function(var)
  11079. local ari = arity[var]
  11080. if ari ~= nil then
  11081. return ari
  11082. elseif var["kind"] == "native" then
  11083. local native = varNative1(var)
  11084. local ari1, signature = native["syntax-arity"], native["signature"]
  11085. if signature then
  11086. local min, max = n1(signature), n1(signature)
  11087. local forLimit = n1(signature)
  11088. local i = 1
  11089. while i <= forLimit do
  11090. local temp1 = sub1(symbol_2d3e_string1((signature[i])), 1, 1)
  11091. if temp1 == "&" then
  11092. max = huge1
  11093. elseif temp1 == "?" then
  11094. min = min - 1
  11095. end
  11096. i = i + 1
  11097. end
  11098. return updateArity_21_(var, min, max)
  11099. elseif ari1 then
  11100. if native["syntax-fold"] then
  11101. return updateArity_21_(var, ari1, huge1)
  11102. else
  11103. return updateArity_21_(var, ari1, ari1)
  11104. end
  11105. else
  11106. return updateArity_21_(var, 0, huge1)
  11107. end
  11108. else
  11109. local defs = getVar1(lookup, var)["defs"]
  11110. if n1(defs) ~= 1 then
  11111. return updateArity_21_(var, 0, huge1)
  11112. else
  11113. local defData = car1(defs)
  11114. local temp1 = type1(defData)
  11115. if temp1 == "var" then
  11116. return updateArity_21_(var, 0, huge1)
  11117. elseif temp1 == "val" then
  11118. local node = defData["value"]
  11119. while true do
  11120. if type1(node) == "symbol" then
  11121. arity[var] = false
  11122. local ari1 = getArity(node["var"])
  11123. arity[var] = ari1
  11124. return ari1
  11125. elseif type1(node) == "list" and builtin_3f_1(car1(node), "lambda") then
  11126. local signature = cadr1(node)
  11127. local max = n1(signature)
  11128. local forLimit = n1(signature)
  11129. local i = 1
  11130. while i <= forLimit do
  11131. if signature[i]["var"]["is-variadic"] then
  11132. max = huge1
  11133. end
  11134. i = i + 1
  11135. end
  11136. return updateArity_21_(var, 0, max)
  11137. elseif type1(node) == "list" and (type1((car1(node))) == "list" and (builtin_3f_1(caar1(node), "lambda") and n1(car1(node)) >= 3)) then
  11138. node = last1(car1(node))
  11139. elseif type1(node) == "list" then
  11140. return updateArity_21_(var, 0, huge1)
  11141. else
  11142. arity[var] = false
  11143. return false
  11144. end
  11145. end
  11146. else
  11147. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp1) .. ", but none matched.\n" .. " Tried: `\"var\"`\n Tried: `\"val\"`")
  11148. end
  11149. end
  11150. end
  11151. end
  11152. return visitBlock1(nodes, 1, function(node)
  11153. if type1(node) == "list" and (type1((car1(node))) == "symbol" and car1(node)["var"]["kind"] ~= "builtin") then
  11154. local arity1 = getArity(car1(node)["var"])
  11155. local minArgs
  11156. if singleReturn_3f_1(last1(node)) then
  11157. minArgs = n1(node) - 1
  11158. else
  11159. minArgs = huge1
  11160. end
  11161. local maxArgs = n1(node) - 1
  11162. if arity1 == false then
  11163. return putNodeWarning_21_1(state["logger"], formatOutput_21_1(nil, "Calling non-function value " .. display1(car1(node))), node["source"], nil, sourceRange1(node["source"]), "Called here")
  11164. elseif minArgs < car1(arity1) then
  11165. return putNodeWarning_21_1(state["logger"], formatOutput_21_1(nil, "Calling " .. display1(car1(node)) .. " with " .. display1(minArgs) .. " arguments, expected at least " .. display1(car1(arity1))), node["source"], nil, sourceRange1(node["source"]), "Called here")
  11166. elseif maxArgs > cadr1(arity1) then
  11167. return putNodeWarning_21_1(state["logger"], formatOutput_21_1(nil, "Calling " .. display1(car1(node)) .. " with " .. display1(maxArgs) .. " arguments, expected at most " .. display1(cadr1(arity1))), node["source"], nil, sourceRange1(node["source"]), "Called here")
  11168. else
  11169. return nil
  11170. end
  11171. else
  11172. return nil
  11173. end
  11174. end)
  11175. end}
  11176. deprecated1 = {name="deprecated", help="Produce a warning whenever a deprecated variable is used.", cat={tag="list", n=2, "warn", "usage"}, run=function(temp, state, nodes)
  11177. local forLimit = n1(nodes)
  11178. local i = 1
  11179. while i <= forLimit do
  11180. local node = nodes[i]
  11181. local defVar = node["def-var"]
  11182. visitNode1(node, function(node1)
  11183. if type1(node1) == "symbol" then
  11184. local var = node1["var"]
  11185. if var ~= defVar and var["deprecated"] then
  11186. return putNodeWarning_21_1(state["logger"], (function()
  11187. if string_3f_1(var["deprecated"]) then
  11188. return format1("%s is deprecated: %s", node1["contents"], var["deprecated"])
  11189. else
  11190. return format1("%s is deprecated.", node1["contents"])
  11191. end
  11192. end)(), node1["source"], nil, sourceRange1(node1["source"]), "")
  11193. else
  11194. return nil
  11195. end
  11196. else
  11197. return nil
  11198. end
  11199. end)
  11200. i = i + 1
  11201. end
  11202. return nil
  11203. end}
  11204. documentation1 = {name="documentation", help="Ensure doc comments are valid.", cat={tag="list", n=1, "warn"}, run=function(temp, state, nodes)
  11205. local validate, forLimit = function(node, var, doc, kind)
  11206. local temp1 = parseDocstring1(doc)
  11207. local forLimit1 = n1(temp1)
  11208. local i = 1
  11209. while i <= forLimit1 do
  11210. local tok = temp1[i]
  11211. if tok["kind"] == "link" then
  11212. if not lookup1(var["scope"], tok["contents"]) then
  11213. putNodeWarning_21_1(state["logger"], format1("%s is not defined.", quoted1(tok["contents"])), node["source"], nil, sourceRange1(node["source"]), format1("Referenced in %s.", kind))
  11214. end
  11215. end
  11216. i = i + 1
  11217. end
  11218. return nil
  11219. end, n1(nodes)
  11220. local i = 1
  11221. while i <= forLimit do
  11222. local node = nodes[i]
  11223. local var = node["def-var"]
  11224. if var then
  11225. if string_3f_1(var["doc"]) then
  11226. validate(node, var, var["doc"], "docstring")
  11227. end
  11228. if string_3f_1(var["deprecated"]) then
  11229. validate(node, var, var["deprecated"], "deprecation message")
  11230. end
  11231. end
  11232. i = i + 1
  11233. end
  11234. return nil
  11235. end}
  11236. unusedVars1 = {name="unused-vars", help="Ensure all non-exported NODES are used.", cat={tag="list", n=2, "warn", "usage"}, level=2, run=function(temp, state, _5f_, lookup)
  11237. local unused = {tag="list", n=0}
  11238. local temp1 = lookup["usage-vars"]
  11239. local temp2, entry = next1(temp1)
  11240. while temp2 ~= nil do
  11241. if not (n1(entry["usages"]) > 0 or n1(entry["soft"]) > 0 or temp2["name"] == "_" or temp2["display-name"] ~= nil or empty_3f_1(entry["defs"])) then
  11242. local def = car1(entry["defs"])["node"]
  11243. local temp3
  11244. if def["def-var"] == nil then
  11245. temp3 = true
  11246. elseif temp2["kind"] ~= "macro" then
  11247. local scope, name = temp2["scope"], temp2["name"]
  11248. temp3 = not scope["exported"][name]
  11249. else
  11250. temp3 = false
  11251. end
  11252. if temp3 then
  11253. push_21_1(unused, list1(temp2, def))
  11254. end
  11255. end
  11256. temp2, entry = next1(temp1, temp2)
  11257. end
  11258. sort1(unused, function(node1, node2)
  11259. return range_3c_1(sourceRange1(cadr1(node1)["source"]), sourceRange1(cadr1(node2)["source"]))
  11260. end)
  11261. local forLimit = n1(unused)
  11262. local i = 1
  11263. while i <= forLimit do
  11264. local pair = unused[i]
  11265. putNodeWarning_21_1(state["logger"], format1("%s is not used.", quoted1(car1(pair)["name"])), cadr1(pair)["source"], nil, sourceRange1(cadr1(pair)["source"]), "Defined here")
  11266. i = i + 1
  11267. end
  11268. return nil
  11269. end}
  11270. macroUsage1 = {name="macro-usage", help="Determines whether any macro is used.", cat={tag="list", n=1, "warn"}, run=function(temp, state, nodes)
  11271. return visitBlock1(nodes, 1, function(node)
  11272. if type1(node) == "list" and (builtin_3f_1(car1(node), "define-macro") and type1((nth1(node, 3))) == "symbol") then
  11273. return false
  11274. elseif type1(node) == "symbol" and node["var"]["kind"] == "macro" then
  11275. return putNodeWarning_21_1(state["logger"], format1("The macro %s is not expanded", quoted1(node["contents"])), node["source"], "This macro is used in such a way that it'll be called as a normal function\ninstead of expanding into executable code. Sometimes this may be intentional,\nbut more often than not it is the result of a misspelled variable name.", sourceRange1(node["source"]), "macro used here")
  11276. else
  11277. return nil
  11278. end
  11279. end)
  11280. end}
  11281. mutableDefinitions1 = {name="mutable-definitions", help="Determines whether any macro is used.", cat={tag="list", n=2, "warn", "usage"}, run=function(temp, state, nodes, lookup)
  11282. local forLimit = n1(nodes)
  11283. local i = 1
  11284. while i <= forLimit do
  11285. local node = nodes[i]
  11286. local var = node["def-var"]
  11287. if var then
  11288. local info = getVar1(lookup, var)
  11289. if not var["const"] and (n1(info["defs"]) == 1 and (function()
  11290. local scope, name = var["scope"], var["name"]
  11291. return scope["exported"][name]
  11292. end)() ~= var) then
  11293. putNodeWarning_21_1(state["logger"], format1("%s is never mutated", quoted1(var["name"])), node["source"], "This definition is explicitly marked as :mutable, but is\nnever mutated. Consider removing the annotation.", sourceRange1(node["source"]), "variable defined here")
  11294. end
  11295. end
  11296. i = i + 1
  11297. end
  11298. return nil
  11299. end}
  11300. analyse1 = function(nodes, state, passes)
  11301. local lookup = {}
  11302. local temp = passes["normal"]
  11303. local forLimit = n1(temp)
  11304. local i = 1
  11305. while i <= forLimit do
  11306. runPass1(temp[i], state, nil, nodes, lookup)
  11307. i = i + 1
  11308. end
  11309. if not empty_3f_1(passes["usage"]) then
  11310. runPass1(tagUsage1, state, nil, nodes, lookup, visitEagerExported_3f_1)
  11311. end
  11312. local temp = passes["usage"]
  11313. local forLimit = n1(temp)
  11314. local i = 1
  11315. while i <= forLimit do
  11316. runPass1(temp[i], state, nil, nodes, lookup)
  11317. i = i + 1
  11318. end
  11319. return nil
  11320. end
  11321. default2 = function()
  11322. return {normal=list1(documentation1, checkOrder1, deprecated1, macroUsage1), usage=list1(checkArity1, unusedVars1, mutableDefinitions1)}
  11323. end
  11324. estimateLength1 = function(node, max)
  11325. local tag = type1(node)
  11326. if tag == "string" or tag == "number" or tag == "symbol" or tag == "key" then
  11327. return n1(tostring1(node["contents"]))
  11328. elseif tag == "list" then
  11329. local sum, i = 2, 1
  11330. while sum <= max and i <= n1(node) do
  11331. sum = sum + estimateLength1(nth1(node, i), max - sum)
  11332. if i > 1 then
  11333. sum = sum + 1
  11334. end
  11335. i = i + 1
  11336. end
  11337. return sum
  11338. else
  11339. return error1("Unknown tag " .. tag, 0)
  11340. end
  11341. end
  11342. expression2 = function(node, writer)
  11343. local tag = type1(node)
  11344. if tag == "string" then
  11345. return append_21_1(writer, quoted1(node["value"]))
  11346. elseif tag == "number" then
  11347. return append_21_1(writer, tostring1(node["value"]))
  11348. elseif tag == "key" then
  11349. return append_21_1(writer, ":" .. node["value"])
  11350. elseif tag == "symbol" then
  11351. return append_21_1(writer, node["contents"])
  11352. elseif tag == "list" then
  11353. append_21_1(writer, "(")
  11354. if empty_3f_1(node) then
  11355. return append_21_1(writer, ")")
  11356. else
  11357. local newline, max = false, 60 - estimateLength1(car1(node), 60)
  11358. expression2(car1(node), writer)
  11359. if max <= 0 then
  11360. newline = true
  11361. writer["indent"] = writer["indent"] + 1
  11362. end
  11363. local forLimit = n1(node)
  11364. local i = 2
  11365. while i <= forLimit do
  11366. local entry = nth1(node, i)
  11367. if not newline and max > 0 then
  11368. max = max - estimateLength1(entry, max)
  11369. if max <= 0 then
  11370. newline = true
  11371. writer["indent"] = writer["indent"] + 1
  11372. end
  11373. end
  11374. if newline then
  11375. line_21_1(writer)
  11376. else
  11377. append_21_1(writer, " ")
  11378. end
  11379. expression2(entry, writer)
  11380. i = i + 1
  11381. end
  11382. if newline then
  11383. writer["indent"] = writer["indent"] - 1
  11384. end
  11385. return append_21_1(writer, ")")
  11386. end
  11387. else
  11388. return error1("Unknown tag " .. tag, 0)
  11389. end
  11390. end
  11391. block2 = function(list, writer)
  11392. local forLimit = n1(list)
  11393. local i = 1
  11394. while i <= forLimit do
  11395. expression2(list[i], writer)
  11396. line_21_1(writer)
  11397. i = i + 1
  11398. end
  11399. return nil
  11400. end
  11401. emitLua1 = {name="emit-lua", setup=function(spec)
  11402. addArgument_21_1(spec, {tag="list", n=1, "--emit-lua"}, "help", "Emit a Lua file.", "narg", "?", "var", "OUTPUT", "value", true, "cat", "out")
  11403. addArgument_21_1(spec, {tag="list", n=1, "--shebang"}, "help", "Set the executable to use for the shebang.", "cat", "out", "value", _2a_arguments_2a_1[-1] or (_2a_arguments_2a_1[0] or "lua"), "narg", "?")
  11404. return addArgument_21_1(spec, {tag="list", n=1, "--chmod"}, "help", "Run chmod +x on the resulting file", "cat", "out")
  11405. end, pred=function(args)
  11406. return args["emit-lua"]
  11407. end, run=function(compiler, args)
  11408. if empty_3f_1(args["input"]) then
  11409. self1(compiler["log"], "put-error!", "No inputs to compile.")
  11410. exit_21_1(1)
  11411. end
  11412. local out = file1(compiler, args["shebang"])
  11413. local name
  11414. if string_3f_1(args["emit-lua"]) then
  11415. name = args["emit-lua"]
  11416. else
  11417. name = args["output"] .. ".lua"
  11418. end
  11419. local handle, error = open1(name, "w")
  11420. if not handle then
  11421. self1(compiler["log"], "put-error!", (sprintf1("Cannot open %q (%s)", name, error)))
  11422. exit_21_1(1)
  11423. end
  11424. self1(handle, "write", concat2(out["out"]))
  11425. self1(handle, "close")
  11426. if args["chmod"] then
  11427. return execute1("chmod +x " .. quoted1(name))
  11428. else
  11429. return nil
  11430. end
  11431. end}
  11432. emitLisp1 = {name="emit-lisp", setup=function(spec)
  11433. return addArgument_21_1(spec, {tag="list", n=1, "--emit-lisp"}, "help", "Emit a Lisp file.", "narg", "?", "var", "OUTPUT", "value", true, "cat", "out")
  11434. end, pred=function(args)
  11435. return args["emit-lisp"]
  11436. end, run=function(compiler, args)
  11437. if empty_3f_1(args["input"]) then
  11438. self1(compiler["log"], "put-error!", "No inputs to compile.")
  11439. exit_21_1(1)
  11440. end
  11441. local writer = {out={tag="list", n=0}, indent=0, ["tabs-pending"]=false, line=1, lines={}, ["node-stack"]={tag="list", n=0}, ["active-pos"]=nil}
  11442. local name
  11443. if string_3f_1(args["emit-lisp"]) then
  11444. name = args["emit-lisp"]
  11445. else
  11446. name = args["output"] .. ".lisp"
  11447. end
  11448. block2(compiler["out"], writer)
  11449. local handle, error = open1(name, "w")
  11450. if not handle then
  11451. self1(compiler["log"], "put-error!", (sprintf1("Cannot open %q (%s)", args["output"] .. ".lisp", error)))
  11452. exit_21_1(1)
  11453. end
  11454. self1(handle, "write", concat2(writer["out"]))
  11455. return self1(handle, "close")
  11456. end}
  11457. passArg1 = function(arg, data, value, usage_21_)
  11458. local val, name = tonumber1(value), arg["name"] .. "-override"
  11459. local override = data[name]
  11460. if not override then
  11461. override = {}
  11462. data[name] = override
  11463. end
  11464. if val then
  11465. data[arg["name"]] = val
  11466. return nil
  11467. elseif sub1(value, 1, 1) == "-" then
  11468. override[sub1(value, 2)] = false
  11469. return nil
  11470. elseif sub1(value, 1, 1) == "+" then
  11471. override[sub1(value, 2)] = true
  11472. return nil
  11473. else
  11474. return usage_21_("Expected number or enable/disable flag for --" .. arg["name"] .. " , got " .. value)
  11475. end
  11476. end
  11477. passRun1 = function(fun, name)
  11478. return function(compiler, args)
  11479. local options = {track=true, level=args[name], override=args[name .. "-override"] or {}, ["max-n"]=args[name .. "-n"], ["max-time"]=args[name .. "-time"], compiler=compiler, logger=compiler["log"], timer=compiler["timer"]}
  11480. return fun(compiler["out"], options, filterPasses1(compiler[name], options))
  11481. end
  11482. end
  11483. warning1 = {name="warning", setup=function(spec)
  11484. return addArgument_21_1(spec, {tag="list", n=2, "--warning", "-W"}, "help", "Either the warning level to use or an enable/disable flag for a pass.", "default", 1, "narg", 1, "var", "LEVEL", "many", true, "action", passArg1)
  11485. end, pred=function()
  11486. return true
  11487. end, run=passRun1(analyse1, "warning")}
  11488. optimise2 = {name="optimise", setup=function(spec)
  11489. addCategory_21_1(spec, "optimise", "Optimisation", "Various controls for how the source code is optimised.")
  11490. addArgument_21_1(spec, {tag="list", n=2, "--optimise", "-O"}, "help", "Either the optimisation level to use or an enable/disable flag for a pass.", "cat", "optimise", "default", 1, "narg", 1, "var", "LEVEL", "many", true, "action", passArg1)
  11491. addArgument_21_1(spec, {tag="list", n=2, "--optimise-n", "--optn"}, "help", "The maximum number of iterations the optimiser should run for.", "cat", "optimise", "default", 10, "narg", 1, "action", setNumAction1)
  11492. return addArgument_21_1(spec, {tag="list", n=2, "--optimise-time", "--optt"}, "help", "The maximum time the optimiser should run for.", "cat", "optimise", "default", -1, "narg", 1, "action", setNumAction1)
  11493. end, pred=function()
  11494. return true
  11495. end, run=passRun1(optimise1, "optimise")}
  11496. printError_21_1 = function(msg)
  11497. if not string_3f_1(msg) then
  11498. msg = pretty1(msg)
  11499. end
  11500. local lines = split1(msg, "\n", 1)
  11501. print1(coloured1(31, "[ERROR] " .. car1(lines)))
  11502. if cadr1(lines) then
  11503. return print1(cadr1(lines))
  11504. else
  11505. return nil
  11506. end
  11507. end
  11508. printWarning_21_1 = function(msg)
  11509. local lines = split1(msg, "\n", 1)
  11510. print1(coloured1(33, "[WARN] " .. car1(lines)))
  11511. if cadr1(lines) then
  11512. return print1(cadr1(lines))
  11513. else
  11514. return nil
  11515. end
  11516. end
  11517. printVerbose_21_1 = function(verbosity, msg)
  11518. if verbosity > 0 then
  11519. return formatOutput_21_1(true, "[VERBOSE] " .. msg)
  11520. else
  11521. return nil
  11522. end
  11523. end
  11524. printDebug_21_1 = function(verbosity, msg)
  11525. if verbosity > 1 then
  11526. return formatOutput_21_1(true, "[DEBUG] " .. msg)
  11527. else
  11528. return nil
  11529. end
  11530. end
  11531. printTime_21_1 = function(maximum, name, time, level)
  11532. if level <= maximum then
  11533. return formatOutput_21_1(true, "[TIME] " .. name .. " took " .. time)
  11534. else
  11535. return nil
  11536. end
  11537. end
  11538. printExplain_21_1 = function(explain, lines)
  11539. if explain then
  11540. local temp = split1(lines, "\n")
  11541. local forLimit = n1(temp)
  11542. local i = 1
  11543. while i <= forLimit do
  11544. print1(" " .. (temp[i]))
  11545. i = i + 1
  11546. end
  11547. return nil
  11548. else
  11549. return nil
  11550. end
  11551. end
  11552. create4 = function(verbosity, explain, time)
  11553. return {verbosity=verbosity or 0, explain=explain == true, time=time or 0, ["put-error!"]=putError_21_1, ["put-warning!"]=putWarning_21_1, ["put-verbose!"]=putVerbose_21_1, ["put-debug!"]=putDebug_21_1, ["put-time!"]=putTime_21_1, ["put-node-error!"]=putNodeError_21_2, ["put-node-warning!"]=putNodeWarning_21_2}
  11554. end
  11555. putError_21_1 = function(logger, msg)
  11556. return printError_21_1(msg)
  11557. end
  11558. putWarning_21_1 = function(logger, msg)
  11559. return printWarning_21_1(msg)
  11560. end
  11561. putVerbose_21_1 = function(logger, msg)
  11562. return printVerbose_21_1(logger["verbosity"], msg)
  11563. end
  11564. putDebug_21_1 = function(logger, msg)
  11565. return printDebug_21_1(logger["verbosity"], msg)
  11566. end
  11567. putTime_21_1 = function(logger, name, time, level)
  11568. return printTime_21_1(logger["time"], name, time, level)
  11569. end
  11570. putNodeError_21_2 = function(logger, msg, source, explain, lines)
  11571. printError_21_1(msg)
  11572. putTrace_21_1(source)
  11573. if explain then
  11574. printExplain_21_1(logger["explain"], explain)
  11575. end
  11576. return putLines_21_1(true, lines)
  11577. end
  11578. putNodeWarning_21_2 = function(logger, msg, source, explain, lines)
  11579. printWarning_21_1(msg)
  11580. putTrace_21_1(source)
  11581. if explain then
  11582. printExplain_21_1(logger["explain"], explain)
  11583. end
  11584. return putLines_21_1(true, lines)
  11585. end
  11586. putLines_21_1 = function(ranges, entries)
  11587. if empty_3f_1(entries) then
  11588. error1("Positions cannot be empty")
  11589. end
  11590. if n1(entries) % 2 ~= 0 then
  11591. error1("Positions must be a multiple of 2, is " .. n1(entries))
  11592. end
  11593. local previous, file, code, forLimit = -1, nth1(entries, 1)["name"], coloured1("32;1", " %" .. n1(tostring1((reduce1(function(max, range)
  11594. if string_3f_1(range) then
  11595. return max
  11596. else
  11597. return max1(max, range["start"]["line"])
  11598. end
  11599. end, 0, entries)))) .. "s │") .. " %s", n1(entries)
  11600. local i = 1
  11601. while i <= forLimit do
  11602. local range, message = entries[i], entries[i + 1]
  11603. if file ~= range["name"] then
  11604. file = range["name"]
  11605. print1(coloured1("35;1", " " .. file))
  11606. elseif previous ~= -1 and abs1(range["start"]["line"] - previous) > 2 then
  11607. print1(coloured1("32;1", " ..."))
  11608. end
  11609. previous = range["start"]["line"]
  11610. print1(format1(code, tostring1(range["start"]["line"]), nth1(range["lines"], range["start"]["line"])))
  11611. local pointer
  11612. if not ranges then
  11613. pointer = "^"
  11614. elseif range["finish"] and range["start"]["line"] == range["finish"]["line"] then
  11615. pointer = rep1("^", (range["finish"]["column"] - range["start"]["column"]) + 1)
  11616. else
  11617. pointer = "^..."
  11618. end
  11619. print1(format1(code, "", rep1(" ", range["start"]["column"] - 1) .. pointer .. " " .. message))
  11620. i = i + 2
  11621. end
  11622. return nil
  11623. end
  11624. putTrace_21_1 = function(source)
  11625. local source1, previous = source, nil
  11626. while true do
  11627. local formatted = formatSource1(source1)
  11628. if previous == nil then
  11629. print1(coloured1("36;1", " => " .. formatted))
  11630. elseif previous ~= formatted then
  11631. print1(" in " .. formatted)
  11632. end
  11633. if nodeSource_3f_1(source1) then
  11634. source1, previous = source1["parent"], formatted
  11635. else
  11636. return nil
  11637. end
  11638. end
  11639. end
  11640. includeRocks1 = function(logger, paths)
  11641. local ok, cfg = pcall1(require1, "luarocks.core.cfg")
  11642. if ok then
  11643. call1(cfg, "init_package_paths")
  11644. return includeRocksImpl1(logger, paths, cfg, require1("luarocks.core.path"), require1("luarocks.core.manif"), require1("luarocks.core.vers"), require1("luarocks.core.util"), require1("luarocks.dir"))
  11645. else
  11646. local ok1, cfg1 = pcall1(require1, "luarocks.cfg")
  11647. if ok1 then
  11648. call1(cfg1, "init_package_paths")
  11649. return includeRocksImpl1(logger, paths, cfg1, require1("luarocks.path"), require1("luarocks.manif_core"), require1("luarocks.deps"), require1("luarocks.util"), require1("luarocks.dir"))
  11650. else
  11651. return nil_3f_1
  11652. end
  11653. end
  11654. end
  11655. includeRocksImpl1 = function(logger, paths, cfg, path, manif, vers, util, dir)
  11656. local temp
  11657. local tbl = cfg["rocks_trees"]
  11658. temp = updateStruct1(tbl, "tag", "list", "n", #tbl)
  11659. local forLimit = n1(temp)
  11660. local i = 1
  11661. while i <= forLimit do
  11662. local tree = temp[i]
  11663. local temp1 = call1(manif, "load_local_manifest", (call1(path, "rocks_dir", tree)))["repository"]
  11664. local temp2, versions = next1(temp1)
  11665. while temp2 ~= nil do
  11666. if not (not next1(versions) or temp2 == "urn") then
  11667. local mainVersion = apply1(min1, ((function()
  11668. local temp3 = keys1(versions)
  11669. return map2(vers["parse_version"], temp3)
  11670. end)()))["string"]
  11671. local rootPath = call1(path, "install_dir", temp2, mainVersion, tree)
  11672. self1(logger, "put-verbose!", (format1("Including %s %s (located at %s)", temp2, mainVersion, rootPath)))
  11673. push_21_1(paths, call1(dir, "path", rootPath, "urn-lib", "?"))
  11674. push_21_1(paths, call1(dir, "path", rootPath, "urn-lib", "?", "init"))
  11675. end
  11676. temp2, versions = next1(temp1, temp2)
  11677. end
  11678. i = i + 1
  11679. end
  11680. return nil
  11681. end
  11682. createPluginState1 = function(compiler)
  11683. local logger, variables, states, warnings, optimise, activeScope, activeNode = compiler["log"], compiler["variables"], compiler["states"], compiler["warning"], compiler["optimise"], function()
  11684. return compiler["active-scope"]
  11685. end, function()
  11686. return compiler["active-node"]
  11687. end
  11688. return {["logger/put-error!"]=function(temp)
  11689. return self1(logger, "put-error!", temp)
  11690. end, ["logger/put-warning!"]=function(temp)
  11691. return self1(logger, "put-warning!", temp)
  11692. end, ["logger/put-verbose!"]=function(temp)
  11693. return self1(logger, "put-verbose!", temp)
  11694. end, ["logger/put-debug!"]=function(temp)
  11695. return self1(logger, "put-debug!", temp)
  11696. end, ["logger/put-node-error!"]=function(msg, node, explain, ...)
  11697. local lines = _pack(...) lines.tag = "list"
  11698. return putNodeError_21_1(logger, msg, node["source"], explain, splice1(lines))
  11699. end, ["logger/put-node-warning!"]=function(msg, node, explain, ...)
  11700. local lines = _pack(...) lines.tag = "list"
  11701. return putNodeWarning_21_1(logger, msg, node["source"], explain, splice1(lines))
  11702. end, ["logger/do-node-error!"]=function(msg, node, explain, ...)
  11703. local lines = _pack(...) lines.tag = "list"
  11704. return doNodeError_21_1(logger, msg, node["source"], explain, splice1(lines))
  11705. end, ["range/get-source"]=getSource1, flags=function()
  11706. return map2(id1, compiler["flags"])
  11707. end, ["flag?"]=function(...)
  11708. local flags = _pack(...) flags.tag = "list"
  11709. return any1(function(temp)
  11710. return elem_3f_1(temp, compiler["flags"])
  11711. end, flags)
  11712. end, ["visit-node"]=visitNode1, ["visit-nodes"]=visitBlock1, ["traverse-nodes"]=traverseNode1, ["traverse-nodes"]=traverseList1, ["symbol->var"]=function(x)
  11713. local var = x["var"]
  11714. if string_3f_1(var) then
  11715. return variables[var]
  11716. else
  11717. return var
  11718. end
  11719. end, ["var->symbol"]=makeSymbol1, builtin=builtin1, ["builtin?"]=builtin_3f_1, ["constant?"]=constant_3f_1, ["node->val"]=urn_2d3e_val1, ["val->node"]=val_2d3e_urn1, ["node-contains-var?"]=nodeContainsVar_3f_1, ["node-contains-vars?"]=nodeContainsVars_3f_1, ["fusion/add-rule!"]=addRule_21_1, ["add-pass!"]=function(pass)
  11720. if type1(pass) ~= "table" then
  11721. error1(demandFailure1(nil, "(= (type pass) \"table\")"))
  11722. end
  11723. if not string_3f_1(pass["name"]) then
  11724. error1("Expected string for name, got " .. type1(pass["name"]))
  11725. end
  11726. if not invokable_3f_1(pass["run"]) then
  11727. error1("Expected function for run, got " .. type1(pass["run"]))
  11728. end
  11729. if type1((pass["cat"])) ~= "list" then
  11730. error1("Expected list for cat, got " .. type1(pass["cat"]))
  11731. end
  11732. local func = pass["run"]
  11733. pass["run"] = function(...)
  11734. local args = _pack(...) args.tag = "list"
  11735. local temp = list1(xpcall1(function()
  11736. return apply1(func, args)
  11737. end, traceback2))
  11738. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  11739. local msg = nth1(temp, 2)
  11740. return error1(remapTraceback1(compiler["compile-state"]["mappings"], msg), 0)
  11741. elseif type1(temp) == "list" and (n1(temp) >= 1 and (nth1(temp, 1) == true and true)) then
  11742. return splice1((slice1(temp, 2)))
  11743. else
  11744. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(false ?msg)`\n Tried: `(true . ?rest)`")
  11745. end
  11746. end
  11747. local cats = pass["cat"]
  11748. if elem_3f_1("opt", cats) then
  11749. if any1(function(temp)
  11750. return sub1(temp, 1, 10) == "transform-"
  11751. end, cats) then
  11752. push_21_1(optimise["transform"], pass)
  11753. elseif elem_3f_1("usage", cats) then
  11754. push_21_1(optimise["usage"], pass)
  11755. else
  11756. push_21_1(optimise["normal"], pass)
  11757. end
  11758. elseif elem_3f_1("warn", cats) then
  11759. if elem_3f_1("usage", cats) then
  11760. push_21_1(warnings["usage"], pass)
  11761. else
  11762. push_21_1(warnings["normal"], pass)
  11763. end
  11764. else
  11765. error1("Cannot register " .. pretty1(pass["name"]) .. " (do not know how to process " .. pretty1(cats) .. ")")
  11766. end
  11767. return nil
  11768. end, ["var-usage"]=getVar1, ["active-scope"]=activeScope, ["active-node"]=activeNode, ["active-module"]=function()
  11769. local scp = compiler["active-scope"]
  11770. while true do
  11771. if not scp then
  11772. return nil
  11773. elseif scp["kind"] == "top-level" then
  11774. return scp
  11775. else
  11776. scp = scp["parent"]
  11777. end
  11778. end
  11779. end, ["scope-vars"]=function(scope)
  11780. if not scope then
  11781. scope = compiler["active-scope"]
  11782. end
  11783. if type1(scope) ~= "scope" then
  11784. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  11785. end
  11786. return scope["variables"]
  11787. end, ["scope-exported"]=function(scope)
  11788. if not scope then
  11789. scope = compiler["active-scope"]
  11790. end
  11791. if type1(scope) ~= "scope" then
  11792. error1(demandFailure1(nil, "(= (type scope) \"scope\")"))
  11793. end
  11794. return scope["exported"]
  11795. end, ["var-lookup"]=function(symb, scope)
  11796. if type1(symb) ~= "symbol" then
  11797. error1(demandFailure1(nil, "(= (type symb) \"symbol\")"))
  11798. end
  11799. if compiler["active-node"] == nil then
  11800. error1("Not currently resolving")
  11801. end
  11802. if not scope then
  11803. scope = compiler["active-scope"]
  11804. end
  11805. return lookupAlways_21_1(scope, symbol_2d3e_string1(symb), compiler["active-node"])
  11806. end, ["try-var-lookup"]=function(symb, scope)
  11807. if type1(symb) ~= "symbol" then
  11808. error1(demandFailure1(nil, "(= (type symb) \"symbol\")"))
  11809. end
  11810. if compiler["active-node"] == nil then
  11811. error1("Not currently resolving")
  11812. end
  11813. if not scope then
  11814. scope = compiler["active-scope"]
  11815. end
  11816. return lookup1(scope, symbol_2d3e_string1(symb))
  11817. end, ["var-definition"]=function(var)
  11818. if compiler["active-node"] == nil then
  11819. error1("Not currently resolving")
  11820. end
  11821. local state = states[var]
  11822. if state then
  11823. if state["stage"] == "parsed" then
  11824. yield1({tag="build", state=state})
  11825. end
  11826. return state["node"]
  11827. else
  11828. return nil
  11829. end
  11830. end, ["var-value"]=function(var)
  11831. if compiler["active-node"] == nil then
  11832. error1("Not currently resolving")
  11833. end
  11834. local state = states[var]
  11835. if state then
  11836. return get_21_1(state)
  11837. else
  11838. return nil
  11839. end
  11840. end, ["var-docstring"]=varDoc1}
  11841. end
  11842. normalisePath1 = function(path, trailing)
  11843. path = gsub1(path, "\\", "/")
  11844. if trailing and (path ~= "" and sub1(path, -1, -1) ~= "/") then
  11845. path = path .. "/"
  11846. end
  11847. while sub1(path, 1, 2) == "./" do
  11848. path = sub1(path, 3)
  11849. end
  11850. return path
  11851. end
  11852. local spec = create1("The compiler and REPL for the Urn programming language.")
  11853. local directory
  11854. local dir = getenv1 and getenv1("URN_ROOT")
  11855. if dir then
  11856. directory = normalisePath1(dir, true)
  11857. else
  11858. local path = _2a_arguments_2a_1[0] or (getinfo1 and gsub1(getinfo1(1, "S")["short_src"], "^@", "") or "urn")
  11859. if find1(path, "urn[/\\]cli%.lisp$") then
  11860. path = gsub1(path, "urn[/\\]cli%.lisp$", "")
  11861. elseif find1(path, "urn[/\\]cli$") then
  11862. path = gsub1(path, "urn[/\\]cli$", "")
  11863. elseif find1(path, "bin[/\\][^/\\]*$") then
  11864. path = gsub1(path, "bin[/\\][^/\\]*$", "")
  11865. else
  11866. path = gsub1(path, "[^/\\]*$", "")
  11867. end
  11868. directory = normalisePath1(path, true)
  11869. end
  11870. local libName
  11871. local handle = open1(directory .. "urn-lib/prelude.lisp")
  11872. if handle then
  11873. self1(handle, "close")
  11874. libName = "urn-lib"
  11875. else
  11876. libName = "lib"
  11877. end
  11878. local paths, tasks = list1("?", "?/init", directory .. libName .. "/?", directory .. libName .. "/?/init"), list1(coverageReport1, task1, task2, warning1, optimise2, emitLisp1, emitLua1, task3, execTask1, replTask1)
  11879. addHelp_21_1(spec)
  11880. addCategory_21_1(spec, "out", "Output", "Customise what is emitted, as well as where and how it is generated.")
  11881. addCategory_21_1(spec, "path", "Input paths", "Locations used to configure where libraries are loaded from.")
  11882. addArgument_21_1(spec, {tag="list", n=2, "--explain", "-e"}, "help", "Explain error messages in more detail.")
  11883. addArgument_21_1(spec, {tag="list", n=2, "--time", "-t"}, "help", "Time how long each task takes to execute. Multiple usages will show more detailed timings.", "many", true, "default", 0, "action", function(arg, data)
  11884. data[arg["name"]] = (data[arg["name"]] or 0) + 1
  11885. return nil
  11886. end)
  11887. addArgument_21_1(spec, {tag="list", n=2, "--verbose", "-v"}, "help", "Make the output more verbose. Can be used multiple times", "many", true, "default", 0, "action", function(arg, data)
  11888. data[arg["name"]] = (data[arg["name"]] or 0) + 1
  11889. return nil
  11890. end)
  11891. addArgument_21_1(spec, {tag="list", n=2, "--include", "-i"}, "help", "Add an additional argument to the include path.", "cat", "path", "many", true, "narg", 1, "default", {tag="list", n=0}, "action", addAction1)
  11892. addArgument_21_1(spec, {tag="list", n=2, "--prelude", "-P"}, "help", "A custom prelude path to use.", "cat", "path", "narg", 1, "default", directory .. libName .. "/prelude")
  11893. addArgument_21_1(spec, {tag="list", n=2, "--include-rocks", "-R"}, "help", "Include all installed LuaRocks on the search path.", "cat", "path")
  11894. addArgument_21_1(spec, {tag="list", n=3, "--output", "--out", "-o"}, "help", "The destination to output to.", "cat", "Output", "narg", 1, "default", "out", "action", function(arg, data, value)
  11895. data[arg["name"]] = gsub1(value, "%.lua$", "")
  11896. return nil
  11897. end)
  11898. addArgument_21_1(spec, {tag="list", n=2, "--wrapper", "-w"}, "help", "A wrapper script to launch Urn with", "narg", 1, "action", function(a, b, value)
  11899. local args, i = map2(id1, _2a_arguments_2a_1), 1
  11900. local len = n1(args)
  11901. while i <= len do
  11902. local item = nth1(args, i)
  11903. if item == "--wrapper" or item == "-w" then
  11904. removeNth_21_1(args, i)
  11905. removeNth_21_1(args, i)
  11906. i = len + 1
  11907. elseif find1(item, "^%-%-wrapper=.*$") then
  11908. removeNth_21_1(args, i)
  11909. i = len + 1
  11910. elseif find1(item, "^%-[^-]+w$") then
  11911. args[i] = sub1(item, 1, -2)
  11912. removeNth_21_1(args, i + 1)
  11913. i = len + 1
  11914. end
  11915. end
  11916. local command = list1(value)
  11917. local interp = _2a_arguments_2a_1[-1]
  11918. if interp then
  11919. push_21_1(command, interp)
  11920. end
  11921. push_21_1(command, _2a_arguments_2a_1[0])
  11922. local temp = list1(execute1(concat2(append1(command, args), " ")))
  11923. if type1(temp) == "list" and (n1(temp) >= 1 and (number_3f_1(nth1(temp, 1)) and true)) then
  11924. return exit1((nth1(temp, 1)))
  11925. elseif type1(temp) == "list" and (n1(temp) >= 3 and (n1(temp) <= 3 and true)) then
  11926. return exit1((nth1(temp, 3)))
  11927. else
  11928. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `((number? @ ?code) . _)`\n Tried: `(_ _ ?code)`")
  11929. end
  11930. end)
  11931. addArgument_21_1(spec, {tag="list", n=1, "--plugin"}, "help", "Specify a compiler plugin to load.", "var", "FILE", "default", {tag="list", n=0}, "narg", 1, "many", true, "action", addAction1)
  11932. addArgument_21_1(spec, {tag="list", n=2, "--flag", "-f"}, "help", "Turn on a compiler flag, enabling or disabling a specific feature.", "default", {tag="list", n=0}, "narg", 1, "many", true, "action", addAction1)
  11933. addArgument_21_1(spec, {tag="list", n=1, "input"}, "help", "The file(s) to load.", "var", "FILE", "narg", "*")
  11934. local forLimit = n1(tasks)
  11935. local i = 1
  11936. while i <= forLimit do
  11937. local task = tasks[i]
  11938. task["setup"](spec)
  11939. i = i + 1
  11940. end
  11941. local args = parse_21_1(spec)
  11942. local logger = create4(args["verbose"], args["explain"], args["time"])
  11943. local temp = args["include"]
  11944. local forLimit = n1(temp)
  11945. local i = 1
  11946. while i <= forLimit do
  11947. local path = temp[i]
  11948. if find1(path, "%?") then
  11949. push_21_1(paths, normalisePath1(path, false))
  11950. else
  11951. path = normalisePath1(path, true)
  11952. push_21_1(paths, path .. "?")
  11953. push_21_1(paths, path .. "?/init")
  11954. end
  11955. i = i + 1
  11956. end
  11957. if args["include-rocks"] then
  11958. includeRocks1(logger, paths)
  11959. end
  11960. self1(logger, "put-verbose!", ("Using path: " .. pretty1(paths)))
  11961. if args["prelude"] == directory .. libName .. "/prelude" and empty_3f_1(args["plugin"]) then
  11962. push_21_1(args["plugin"], directory .. "plugins/fold-defgeneric.lisp")
  11963. end
  11964. if empty_3f_1(args["input"]) then
  11965. args["repl"] = true
  11966. elseif not args["emit-lua"] then
  11967. args["emit-lua"] = true
  11968. end
  11969. local compiler = {log=logger, timer={callback=function(temp, temp1, temp2)
  11970. return self1(logger, "put-time!", temp, temp1, temp2)
  11971. end, timers={}}, paths=paths, flags=args["flag"], libs=libraryCache1(), prelude=nil, ["root-scope"]=rootScope1, warning=default2(), optimise=default1(), exec=function(func)
  11972. return list1(xpcall1(func, traceback2))
  11973. end, variables={}, states={}, out={tag="list", n=0}}
  11974. compiler["compile-state"] = createState1()
  11975. compiler["loader"] = function(temp)
  11976. return namedLoader1(compiler, temp)
  11977. end
  11978. compiler["global"] = setmetatable1({_libs=compiler["libs"]["values"], _compiler=createPluginState1(compiler)}, {__index=_5f_G1})
  11979. local temp = rootScope1["variables"]
  11980. local temp1, var = next1(temp)
  11981. while temp1 ~= nil do
  11982. compiler["variables"][tostring1(var)] = var
  11983. temp1, var = next1(temp, temp1)
  11984. end
  11985. local forLimit = n1(tasks)
  11986. local i = 1
  11987. while i <= forLimit do
  11988. local task = tasks[i]
  11989. if task["pred"](args) then
  11990. local setup = task["init"]
  11991. if setup then
  11992. setup(compiler, args)
  11993. end
  11994. end
  11995. i = i + 1
  11996. end
  11997. startTimer_21_1(compiler["timer"], "loading")
  11998. local doLoad_21_ = function(name)
  11999. local temp = list1(xpcall1(function()
  12000. return pathLoader1(compiler, name)
  12001. end, traceback3))
  12002. if type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and compilerError_3f_1(nth1(temp, 2))))) then
  12003. return exit_21_1(1)
  12004. elseif type1(temp) == "list" and (n1(temp) >= 2 and (n1(temp) <= 2 and (nth1(temp, 1) == false and true))) then
  12005. return error1(nth1(temp, 2), 0)
  12006. else
  12007. local temp1
  12008. if type1(temp) == "list" then
  12009. if n1(temp) >= 2 then
  12010. if n1(temp) <= 2 then
  12011. if nth1(temp, 1) == true then
  12012. local temp2 = nth1(temp, 2)
  12013. temp1 = type1(temp2) == "list" and (n1(temp2) >= 2 and (n1(temp2) <= 2 and (nth1(temp2, 1) == nil and true)))
  12014. else
  12015. temp1 = false
  12016. end
  12017. else
  12018. temp1 = false
  12019. end
  12020. else
  12021. temp1 = false
  12022. end
  12023. else
  12024. temp1 = false
  12025. end
  12026. if temp1 then
  12027. self1(logger, "put-error!", (nth1(nth1(temp, 2), 2)))
  12028. return exit_21_1(1)
  12029. else
  12030. local temp1
  12031. if type1(temp) == "list" then
  12032. if n1(temp) >= 2 then
  12033. if n1(temp) <= 2 then
  12034. if nth1(temp, 1) == true then
  12035. local temp2 = nth1(temp, 2)
  12036. temp1 = type1(temp2) == "list" and (n1(temp2) >= 1 and (n1(temp2) <= 1 and true))
  12037. else
  12038. temp1 = false
  12039. end
  12040. else
  12041. temp1 = false
  12042. end
  12043. else
  12044. temp1 = false
  12045. end
  12046. else
  12047. temp1 = false
  12048. end
  12049. if temp1 then
  12050. return (nth1(nth1(temp, 2), 1))
  12051. else
  12052. return error1("Pattern matching failure!\nTried to match the following patterns against " .. pretty1(temp) .. ", but none matched.\n" .. " Tried: `(false error/compiler-error?)`\n Tried: `(false ?error-message)`\n Tried: `(true (nil ?error-message))`\n Tried: `(true (?lib))`")
  12053. end
  12054. end
  12055. end
  12056. end
  12057. setupPrelude_21_1(compiler, (doLoad_21_(args["prelude"])))
  12058. local temp = append1(args["plugin"], args["input"])
  12059. local forLimit = n1(temp)
  12060. local i = 1
  12061. while i <= forLimit do
  12062. doLoad_21_((temp[i]))
  12063. i = i + 1
  12064. end
  12065. stopTimer_21_1(compiler["timer"], "loading")
  12066. local forLimit = n1(tasks)
  12067. local i = 1
  12068. while i <= forLimit do
  12069. local task = tasks[i]
  12070. if task["pred"](args) then
  12071. startTimer_21_1(compiler["timer"], task["name"], 1)
  12072. task["run"](compiler, args)
  12073. stopTimer_21_1(compiler["timer"], task["name"])
  12074. end
  12075. i = i + 1
  12076. end
  12077. return nil