qic.c 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185
  1. #include <ctype.h>
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <time.h>
  7. #define QIC_VERSION "qic v01 " __DATE__
  8. size_t GID = 0;
  9. char *PREFIX = NULL;
  10. void *malloc_checked(size_t s) {
  11. void *p = malloc(s);
  12. if (!p) {
  13. fprintf(stderr, "fatal: out of memory.\n");
  14. abort();
  15. }
  16. memset(p, 0, s);
  17. return p;
  18. }
  19. void *realloc_checked(void *p, size_t s) {
  20. p = realloc(p, s);
  21. if (!p) {
  22. fprintf(stderr, "fatal: out of memory.\n");
  23. abort();
  24. }
  25. return p;
  26. }
  27. void *calloc_checked(size_t k, size_t s) {
  28. void *p = calloc(k, s);
  29. if (!p) {
  30. fprintf(stderr, "fatal: out of memory.\n");
  31. abort();
  32. }
  33. return p;
  34. }
  35. typedef struct {
  36. void **data;
  37. size_t length;
  38. } list_t;
  39. list_t *list_new(void) {
  40. list_t *list = malloc_checked(sizeof(list_t));
  41. list->data = NULL;
  42. list->length = 0;
  43. return list;
  44. }
  45. list_t *list_copy(list_t *list) {
  46. list_t *nlist = malloc_checked(sizeof(list_t));
  47. nlist->length = list->length;
  48. nlist->data = realloc_checked(nlist->data, nlist->length * sizeof(void *));
  49. memcpy(nlist->data, list->data, nlist->length * sizeof(void *));
  50. return nlist;
  51. }
  52. void list_push(list_t *l, void *v) {
  53. size_t i = l->length++;
  54. l->data = realloc_checked(l->data, l->length * sizeof(void *));
  55. l->data[i] = v;
  56. }
  57. void *list_pop(list_t *l) {
  58. if (!l->length)
  59. return NULL;
  60. return l->data[--l->length];
  61. }
  62. void *list_index(list_t *l, ssize_t index) {
  63. if (!l->length)
  64. return NULL;
  65. if (index < 0)
  66. index += ((ssize_t)l->length);
  67. if (index < 0 || index >= l->length)
  68. return NULL;
  69. return l->data[index];
  70. }
  71. void list_set(list_t *l, ssize_t index, void *v) {
  72. if (!l->length)
  73. return;
  74. if (index < 0)
  75. index += ((ssize_t)l->length);
  76. if (index < 0 || index >= l->length)
  77. return;
  78. l->data[index] = v;
  79. }
  80. typedef struct {
  81. size_t *data;
  82. size_t length;
  83. } int_stack_t;
  84. int_stack_t *stack_new(void) {
  85. int_stack_t *stack = malloc_checked(sizeof(list_t));
  86. stack->data = NULL;
  87. stack->length = 0;
  88. return stack;
  89. }
  90. void stack_push(int_stack_t *l, size_t v) {
  91. size_t i = l->length++;
  92. l->data = realloc_checked(l->data, l->length * sizeof(size_t));
  93. l->data[i] = v;
  94. }
  95. size_t stack_pop(int_stack_t *l) {
  96. if (!l->length)
  97. return 0;
  98. return l->data[--l->length];
  99. }
  100. struct entry_t {
  101. char *key;
  102. void *value;
  103. };
  104. struct table_t {
  105. struct entry_t *entries;
  106. size_t used;
  107. size_t capacity;
  108. };
  109. typedef struct entry_t entry_t;
  110. typedef struct table_t table_t;
  111. table_t *table_new() {
  112. table_t *table = malloc_checked(sizeof(table_t));
  113. table->used = 0;
  114. table->capacity = 32;
  115. table->entries = calloc_checked(table->capacity, sizeof(entry_t));
  116. return table;
  117. }
  118. unsigned long ht_hash(const char *key) {
  119. unsigned long hash = 5381;
  120. int c;
  121. while ((c = *key++))
  122. hash = ((hash << 5) + hash) + c;
  123. return hash;
  124. }
  125. void *table_get(table_t *table, char *key) {
  126. if (!table->used)
  127. return NULL;
  128. unsigned long hash = ht_hash(key);
  129. size_t index = hash % table->capacity;
  130. size_t i = index;
  131. while (table->entries[i].key) {
  132. if (strcmp(table->entries[i].key, key) == 0)
  133. return table->entries[i].value;
  134. i++;
  135. if (i >= table->capacity)
  136. i = 0;
  137. if (i == index)
  138. break;
  139. }
  140. return NULL;
  141. }
  142. int table_has(table_t *table, char *key) {
  143. if (!table->used)
  144. return 0;
  145. unsigned long hash = ht_hash(key);
  146. size_t index = hash % table->capacity;
  147. size_t i = index;
  148. while (table->entries[i].key) {
  149. if (strcmp(table->entries[i].key, key) == 0)
  150. return 1;
  151. i++;
  152. if (i >= table->capacity)
  153. i = 0;
  154. if (i == index)
  155. break;
  156. }
  157. return 0;
  158. }
  159. static void table_entry_set(entry_t *entries, char *key, void *value,
  160. size_t capacity, size_t *used) {
  161. unsigned long hash = ht_hash(key);
  162. size_t index = hash % capacity;
  163. size_t i = index;
  164. while (entries[i].key) {
  165. if (strcmp(entries[i].key, key) == 0) {
  166. entries[i].value = value;
  167. return;
  168. }
  169. i++;
  170. if (i >= capacity)
  171. i = 0;
  172. if (i == index)
  173. break;
  174. }
  175. if (used)
  176. (*used)++;
  177. entries[i].key = key;
  178. entries[i].value = value;
  179. }
  180. table_t *table_set(table_t *table, char *key, void *value) {
  181. if (table->used >= table->capacity) {
  182. size_t capacity = table->capacity + 32;
  183. entry_t *entries = calloc_checked(capacity, sizeof(entry_t));
  184. for (size_t i = 0; i < table->capacity; i++) {
  185. entry_t entry = table->entries[i];
  186. if (entry.key)
  187. table_entry_set(entries, entry.key, entry.value, capacity, NULL);
  188. }
  189. table->entries = entries;
  190. table->capacity = capacity;
  191. }
  192. table_entry_set(table->entries, key, value, table->capacity, &table->used);
  193. return table;
  194. }
  195. #define table_iterate(table, code) \
  196. { \
  197. if ((table)->used) { \
  198. size_t i = 0; \
  199. while (i < (table)->capacity) { \
  200. entry_t entry = (table)->entries[i]; \
  201. if (entry.key) { \
  202. code; \
  203. } \
  204. i++; \
  205. } \
  206. } \
  207. }
  208. typedef struct {
  209. char *str;
  210. size_t size;
  211. } buffer_t;
  212. buffer_t *buffer_new(void) {
  213. buffer_t *buf = malloc_checked(sizeof(buffer_t));
  214. buf->str = NULL;
  215. buf->size = 0;
  216. return buf;
  217. }
  218. void buffer_append(buffer_t *buf, char c) {
  219. buf->size++;
  220. buf->str = realloc_checked(buf->str, sizeof(char) * buf->size);
  221. buf->str[buf->size - 1] = c;
  222. }
  223. char *buffer_read(buffer_t *buf) {
  224. if (buf->size == 0 || buf->str[buf->size - 1])
  225. buffer_append(buf, 0);
  226. return buf->str;
  227. }
  228. void buffer_appends(buffer_t *buf, char *s) {
  229. for (size_t i = 0; i < strlen(s); i++)
  230. buffer_append(buf, s[i]);
  231. }
  232. void buffer_appendb(buffer_t *dst, buffer_t *src) {
  233. for (size_t i = 0; i < src->size; i++)
  234. buffer_append(dst, src->str[i]);
  235. }
  236. void buffer_fmt(buffer_t *buf, const char *fmt, ...) {
  237. va_list args;
  238. va_list largs;
  239. va_start(largs, fmt);
  240. va_copy(args, largs);
  241. size_t size = vsnprintf(NULL, 0, fmt, largs) + 1;
  242. char *str = malloc_checked(sizeof(char) * size);
  243. vsnprintf(str, size, fmt, args);
  244. va_end(args);
  245. va_end(largs);
  246. buffer_appends(buf, str);
  247. }
  248. typedef struct {
  249. enum {
  250. T_EOF,
  251. T_NUMBER,
  252. T_STRING,
  253. T_FSTRING,
  254. T_USTRING,
  255. T_NAME,
  256. T_TRUE,
  257. T_FALSE,
  258. T_NIL,
  259. T_VAR,
  260. T_LET,
  261. T_CONST,
  262. T_IF,
  263. T_ELSE,
  264. T_ELIF,
  265. T_SWITCH,
  266. T_CASE,
  267. T_DEFAULT,
  268. T_FOR,
  269. T_OF,
  270. T_BREAK,
  271. T_CONTINUE,
  272. T_PASS,
  273. T_FUNC,
  274. T_USE,
  275. T_RETURN,
  276. T_DEFER,
  277. T_REQUIRE,
  278. T_TRY,
  279. T_CATCH,
  280. T_FINALLY,
  281. T_THROW,
  282. T_GOTO,
  283. T_CLASS,
  284. T_DEL,
  285. T_IS,
  286. T_IN,
  287. T_LPAR,
  288. T_RPAR,
  289. T_LSB,
  290. T_RSB,
  291. T_LCB,
  292. T_RCB,
  293. T_EQUALS,
  294. T_NOTEQUALS,
  295. T_PLUSASSIGN,
  296. T_MINUSASSIGN,
  297. T_SLASHASSIGN,
  298. T_STARASSIGN,
  299. T_SLASHSLASHASSIGN,
  300. T_PERCENTASSIGN,
  301. T_STARSTARASSIGN,
  302. T_BARASSIGN,
  303. T_ANDASSIGN,
  304. T_RAISEASSIGN,
  305. T_LTLTASSIGN,
  306. T_GTGTASSIGN,
  307. T_BARBAR,
  308. T_ANDAND,
  309. T_STARSTAR,
  310. T_PLUSPLUS,
  311. T_MINUSMINUS,
  312. T_SLASHSLASH,
  313. T_PLUS,
  314. T_MINUS,
  315. T_QM,
  316. T_COLON,
  317. T_BAR,
  318. T_AND,
  319. T_LT,
  320. T_LTLT,
  321. T_GT,
  322. T_GTGT,
  323. T_LE,
  324. T_GE,
  325. T_STAR,
  326. T_SLASH,
  327. T_PERCENT,
  328. T_COMMA,
  329. T_DOT,
  330. T_BANG,
  331. T_RAISE,
  332. T_TILDE,
  333. T_AT,
  334. T_INLINE,
  335. T_HEADER,
  336. T_INCLUDE,
  337. T_MACRO,
  338. T_ASSIGN,
  339. T_SEMI,
  340. T_MVAR
  341. } tag;
  342. char *text;
  343. size_t fi;
  344. size_t pos;
  345. } token_t;
  346. token_t *token(int tag, char *text) {
  347. token_t *tok = malloc_checked(sizeof(token_t));
  348. tok->tag = tag;
  349. tok->text = text;
  350. return tok;
  351. }
  352. #define TK(tk) (token(T_##tk, NULL))
  353. #define WS() \
  354. while (source[*pos] == ' ' || source[*pos] == '\t' || \
  355. source[*pos] == '\n' || source[*pos] == '\r') { \
  356. (*pos)++; \
  357. }
  358. void consume_ignored(char *source, size_t *pos) {
  359. WS();
  360. while (source[*pos] == '#') {
  361. (*pos)++;
  362. for (;;) {
  363. if (!source[*pos])
  364. break;
  365. if (source[*pos] == '\n') {
  366. (*pos)++;
  367. break;
  368. }
  369. (*pos)++;
  370. }
  371. WS();
  372. }
  373. }
  374. list_t *FILES;
  375. list_t *REQUIRED;
  376. int is_required(char *path) {
  377. for (size_t i = 0; i < REQUIRED->length; i++)
  378. if (strcmp(REQUIRED->data[i], path) == 0)
  379. return 1;
  380. return 0;
  381. }
  382. char *traverse(char *source, size_t pos, size_t *line, size_t *col) {
  383. if (line)
  384. *line = 1;
  385. if (col)
  386. *col = 1;
  387. size_t p = 0;
  388. for (size_t i = 0; i < pos; i++) {
  389. if (source[i] == '\n') {
  390. if (line)
  391. (*line)++;
  392. if (col)
  393. (*col) = 1;
  394. p = i + 1;
  395. } else if (col)
  396. (*col)++;
  397. }
  398. return &source[p];
  399. }
  400. void format_error(char *filename, char *source, size_t pos, char *fmt, ...) {
  401. size_t line, col;
  402. char *src = traverse(source, pos, &line, &col);
  403. va_list args;
  404. va_start(args, fmt);
  405. fprintf(stderr, "%s (%zu:%zu): ", filename, line, col);
  406. vfprintf(stderr, fmt, args);
  407. fputc('\n', stderr);
  408. va_end(args);
  409. if (!*src)
  410. return;
  411. int empty = 1;
  412. for (size_t i = 0; src[i] && src[i] != '\n'; i++)
  413. if (!isspace(src[i])) {
  414. empty = 0;
  415. break;
  416. }
  417. if (empty)
  418. return;
  419. fputc('\t', stderr);
  420. for (size_t i = 0; src[i] && src[i] != '\n' && i < 64; i++)
  421. fputc(src[i], stderr);
  422. fputc('\n', stderr);
  423. fputc('\t', stderr);
  424. for (size_t i = 1; i < col && i < 64; i++)
  425. fputc(' ', stderr);
  426. fputs("^\n", stderr);
  427. }
  428. #define GETFNAME(fi) ((char *)((list_t *)list_index(FILES, fi))->data[0])
  429. #define GETSRC(fi) ((char *)((list_t *)list_index(FILES, fi))->data[1])
  430. #define LEX_ERROR(fmt, ...) \
  431. { \
  432. format_error(GETFNAME(-1), source, *pos, fmt, ##__VA_ARGS__); \
  433. exit(1); \
  434. }
  435. token_t *tokenize_string(char *source, size_t *pos) {
  436. char term = source[(*pos)++];
  437. buffer_t *text = buffer_new();
  438. while (source[*pos] != term) {
  439. if (!source[*pos])
  440. LEX_ERROR("unterminated string literal");
  441. char c = source[(*pos)++];
  442. if (c == '\n' && term != '`')
  443. LEX_ERROR("unterminated string literal");
  444. if (term != '`' && c == '\\') {
  445. char nc = source[(*pos)++];
  446. if (!nc)
  447. continue;
  448. switch (nc) {
  449. case 'x': {
  450. char buf[3];
  451. int k = 0;
  452. while (k < 2) {
  453. if (!source[*pos] || !strchr("0123456789abcdefABCDEF", source[*pos]))
  454. break;
  455. buf[k++] = source[(*pos)++];
  456. }
  457. if (k != 2)
  458. LEX_ERROR("malformed \\x escape sequence");
  459. buf[k] = 0;
  460. buffer_fmt(text, "\\x%s", buf);
  461. } break;
  462. case 'n':
  463. buffer_appends(text, "\\n");
  464. break;
  465. case 't':
  466. buffer_appends(text, "\\t");
  467. break;
  468. case 'r':
  469. buffer_appends(text, "\\r");
  470. break;
  471. case 'a':
  472. buffer_appends(text, "\\a");
  473. break;
  474. case 'b':
  475. buffer_appends(text, "\\b");
  476. break;
  477. case 'e':
  478. buffer_appends(text, "\\x1b");
  479. break;
  480. case 's':
  481. buffer_appends(text, " ");
  482. break;
  483. case '"':
  484. buffer_appends(text, "\\\"");
  485. break;
  486. case '?':
  487. buffer_appends(text, "\\\?");
  488. break;
  489. case '\\':
  490. buffer_appends(text, "\\\\");
  491. break;
  492. case '\n':
  493. buffer_appends(text, "\\n");
  494. break;
  495. default:
  496. buffer_append(text, nc);
  497. break;
  498. }
  499. continue;
  500. }
  501. if (c == '"' || c == '\\' || c == '?')
  502. buffer_append(text, '\\');
  503. else if (c == '\n')
  504. buffer_appends(text, "\\n");
  505. buffer_append(text, c);
  506. }
  507. (*pos)++;
  508. return token(T_STRING, buffer_read(text));
  509. }
  510. int NEEDS_UTF8 = 0;
  511. token_t *next_token(char *source, size_t *pos) {
  512. if (!source[*pos])
  513. return token(T_EOF, NULL);
  514. if (source[*pos] == '"' || source[*pos] == '\'' || source[*pos] == '`')
  515. return tokenize_string(source, pos);
  516. else if (source[*pos] == 'f' &&
  517. (source[(*pos) + 1] == '"' || source[(*pos) + 1] == '\'' ||
  518. source[(*pos) + 1] == '`')) {
  519. (*pos)++;
  520. token_t *t = tokenize_string(source, pos);
  521. t->tag = T_FSTRING;
  522. return t;
  523. } else if (source[*pos] == 'u' &&
  524. (source[(*pos) + 1] == '"' || source[(*pos) + 1] == '\'' ||
  525. source[(*pos) + 1] == '`')) {
  526. (*pos)++;
  527. token_t *t = tokenize_string(source, pos);
  528. t->tag = T_USTRING;
  529. NEEDS_UTF8 = 1;
  530. return t;
  531. } else if (source[*pos] == '0' &&
  532. (source[(*pos) + 1] == 'x' || source[(*pos) + 1] == 'b' ||
  533. source[(*pos) + 1] == 'o')) {
  534. buffer_t *number = buffer_new();
  535. buffer_append(number, source[(*pos)++]);
  536. char b = source[(*pos)++];
  537. buffer_append(number, b);
  538. while (source[*pos] && strchr(b == 'x' ? "0123456789abcdefABCDEF"
  539. : b == 'b' ? "01"
  540. : "01234567",
  541. source[*pos]) != NULL)
  542. buffer_append(number, source[(*pos)++]);
  543. if (number->size < 3)
  544. LEX_ERROR("illegal number literal (trailing base)");
  545. return token(T_NUMBER, buffer_read(number));
  546. } else if ((source[*pos] == '.' && isdigit(source[(*pos) + 1])) ||
  547. isdigit(source[*pos])) {
  548. buffer_t *number = buffer_new();
  549. int dot = 0;
  550. int sub = 0;
  551. int skip = 0;
  552. if (source[*pos] == '.') {
  553. buffer_append(number, '0');
  554. skip = 1;
  555. }
  556. do {
  557. if (skip)
  558. skip = 0;
  559. else
  560. buffer_append(number, source[(*pos)++]);
  561. if (!dot && source[*pos] == '.') {
  562. buffer_append(number, source[(*pos)++]);
  563. if (!isdigit(source[*pos]))
  564. LEX_ERROR(
  565. "illegal number literal (missing part after floating point)");
  566. dot = 1;
  567. } else if (!sub && source[*pos] == '_') {
  568. (*pos)++;
  569. if (!isdigit(source[*pos]))
  570. LEX_ERROR("illegal number literal (missing part after underscore)");
  571. sub = 1;
  572. } else if (sub)
  573. sub = 0;
  574. } while (isdigit(source[*pos]));
  575. return token(T_NUMBER, buffer_read(number));
  576. } else if (source[*pos] == '$') {
  577. (*pos)++;
  578. buffer_t *name = buffer_new();
  579. if (source[*pos] == '$' || source[*pos] == '{' || source[*pos] == ':' ||
  580. source[*pos] == '*')
  581. buffer_append(name, source[(*pos)++]);
  582. else {
  583. if (!source[*pos] || !isalpha(source[*pos]))
  584. LEX_ERROR("illegal macro variable (missing or malformed part after "
  585. "dollar sign)");
  586. do {
  587. buffer_append(name, source[(*pos)++]);
  588. } while (isalpha(source[*pos]) || source[*pos] == '_' ||
  589. isdigit(source[*pos]));
  590. }
  591. return token(T_MVAR, buffer_read(name));
  592. } else if (isalpha(source[*pos]) || source[*pos] == '_') {
  593. buffer_t *text = buffer_new();
  594. do {
  595. buffer_append(text, source[(*pos)++]);
  596. } while (isalpha(source[*pos]) || source[*pos] == '_' ||
  597. isdigit(source[*pos]));
  598. char *name = buffer_read(text);
  599. if (strcmp(name, "var") == 0)
  600. return TK(VAR);
  601. else if (strcmp(name, "let") == 0)
  602. return TK(LET);
  603. else if (strcmp(name, "const") == 0)
  604. return TK(CONST);
  605. else if (strcmp(name, "if") == 0)
  606. return TK(IF);
  607. else if (strcmp(name, "else") == 0)
  608. return TK(ELSE);
  609. else if (strcmp(name, "elif") == 0)
  610. return TK(ELIF);
  611. else if (strcmp(name, "switch") == 0)
  612. return TK(SWITCH);
  613. else if (strcmp(name, "case") == 0)
  614. return TK(CASE);
  615. else if (strcmp(name, "default") == 0)
  616. return TK(DEFAULT);
  617. else if (strcmp(name, "for") == 0)
  618. return TK(FOR);
  619. else if (strcmp(name, "break") == 0)
  620. return TK(BREAK);
  621. else if (strcmp(name, "continue") == 0)
  622. return TK(CONTINUE);
  623. else if (strcmp(name, "func") == 0)
  624. return TK(FUNC);
  625. else if (strcmp(name, "use") == 0)
  626. return TK(USE);
  627. else if (strcmp(name, "return") == 0)
  628. return TK(RETURN);
  629. else if (strcmp(name, "defer") == 0)
  630. return TK(DEFER);
  631. else if (strcmp(name, "pass") == 0)
  632. return TK(PASS);
  633. else if (strcmp(name, "require") == 0)
  634. return TK(REQUIRE);
  635. else if (strcmp(name, "try") == 0)
  636. return TK(TRY);
  637. else if (strcmp(name, "catch") == 0)
  638. return TK(CATCH);
  639. else if (strcmp(name, "finally") == 0)
  640. return TK(FINALLY);
  641. else if (strcmp(name, "throw") == 0)
  642. return TK(THROW);
  643. else if (strcmp(name, "goto") == 0)
  644. return TK(GOTO);
  645. else if (strcmp(name, "class") == 0)
  646. return TK(CLASS);
  647. else if (strcmp(name, "del") == 0)
  648. return TK(DEL);
  649. else if (strcmp(name, "is") == 0)
  650. return TK(IS);
  651. else if (strcmp(name, "in") == 0)
  652. return TK(IN);
  653. else if (strcmp(name, "of") == 0)
  654. return TK(OF);
  655. else if (strcmp(name, "inline") == 0)
  656. return TK(INLINE);
  657. else if (strcmp(name, "header") == 0)
  658. return TK(HEADER);
  659. else if (strcmp(name, "include") == 0)
  660. return TK(INCLUDE);
  661. else if (strcmp(name, "macro") == 0)
  662. return TK(MACRO);
  663. else if (strcmp(name, "true") == 0)
  664. return TK(TRUE);
  665. else if (strcmp(name, "false") == 0)
  666. return TK(FALSE);
  667. else if (strcmp(name, "nil") == 0)
  668. return TK(NIL);
  669. return token(T_NAME, name);
  670. } else if (strncmp(&source[*pos], "==", 2) == 0 && ++(*pos) && ++(*pos))
  671. return TK(EQUALS);
  672. else if (strncmp(&source[*pos], "!=", 2) == 0 && ++(*pos) && ++(*pos))
  673. return TK(NOTEQUALS);
  674. else if (strncmp(&source[*pos], "+=", 2) == 0 && ++(*pos) && ++(*pos))
  675. return TK(PLUSASSIGN);
  676. else if (strncmp(&source[*pos], "-=", 2) == 0 && ++(*pos) && ++(*pos))
  677. return TK(MINUSASSIGN);
  678. else if (strncmp(&source[*pos], "*=", 2) == 0 && ++(*pos) && ++(*pos))
  679. return TK(STARASSIGN);
  680. else if (strncmp(&source[*pos], "/=", 2) == 0 && ++(*pos) && ++(*pos))
  681. return TK(SLASHASSIGN);
  682. else if (strncmp(&source[*pos], "//=", 3) == 0 && ++(*pos) && ++(*pos) &&
  683. ++(*pos))
  684. return TK(SLASHSLASHASSIGN);
  685. else if (strncmp(&source[*pos], "%=", 2) == 0 && ++(*pos) && ++(*pos))
  686. return TK(PERCENTASSIGN);
  687. else if (strncmp(&source[*pos], "**=", 3) == 0 && ++(*pos) && ++(*pos) &&
  688. ++(*pos))
  689. return TK(STARSTARASSIGN);
  690. else if (strncmp(&source[*pos], "|=", 2) == 0 && ++(*pos) && ++(*pos))
  691. return TK(BARASSIGN);
  692. else if (strncmp(&source[*pos], "&=", 2) == 0 && ++(*pos) && ++(*pos))
  693. return TK(ANDASSIGN);
  694. else if (strncmp(&source[*pos], "^=", 2) == 0 && ++(*pos) && ++(*pos))
  695. return TK(RAISEASSIGN);
  696. else if (strncmp(&source[*pos], "<<=", 3) == 0 && ++(*pos) && ++(*pos) &&
  697. ++(*pos))
  698. return TK(LTLTASSIGN);
  699. else if (strncmp(&source[*pos], ">>=", 3) == 0 && ++(*pos) && ++(*pos) &&
  700. ++(*pos))
  701. return TK(GTGTASSIGN);
  702. else if (strncmp(&source[*pos], "||", 2) == 0 && ++(*pos) && ++(*pos))
  703. return TK(BARBAR);
  704. else if (strncmp(&source[*pos], "&&", 2) == 0 && ++(*pos) && ++(*pos))
  705. return TK(ANDAND);
  706. else if (strncmp(&source[*pos], "++", 2) == 0 && ++(*pos) && ++(*pos))
  707. return TK(PLUSPLUS);
  708. else if (strncmp(&source[*pos], "--", 2) == 0 && ++(*pos) && ++(*pos))
  709. return TK(MINUSMINUS);
  710. else if (strncmp(&source[*pos], "//", 2) == 0 && ++(*pos) && ++(*pos))
  711. return TK(SLASHSLASH);
  712. else if (strncmp(&source[*pos], "**", 2) == 0 && ++(*pos) && ++(*pos))
  713. return TK(STARSTAR);
  714. else if (strncmp(&source[*pos], "<<", 2) == 0 && ++(*pos) && ++(*pos))
  715. return TK(LTLT);
  716. else if (strncmp(&source[*pos], ">>", 2) == 0 && ++(*pos) && ++(*pos))
  717. return TK(GTGT);
  718. else if (strncmp(&source[*pos], "<=", 2) == 0 && ++(*pos) && ++(*pos))
  719. return TK(LE);
  720. else if (strncmp(&source[*pos], ">=", 2) == 0 && ++(*pos) && ++(*pos))
  721. return TK(GE);
  722. else if (source[*pos] == '(' && ++(*pos))
  723. return TK(LPAR);
  724. else if (source[*pos] == ')' && ++(*pos))
  725. return TK(RPAR);
  726. else if (source[*pos] == '[' && ++(*pos))
  727. return TK(LSB);
  728. else if (source[*pos] == ']' && ++(*pos))
  729. return TK(RSB);
  730. else if (source[*pos] == '{' && ++(*pos))
  731. return TK(LCB);
  732. else if (source[*pos] == '}' && ++(*pos)) {
  733. if (source[*pos] == '$' && ++(*pos))
  734. return token(T_MVAR, strdup("}"));
  735. return TK(RCB);
  736. } else if (source[*pos] == '+' && ++(*pos))
  737. return TK(PLUS);
  738. else if (source[*pos] == '-' && ++(*pos))
  739. return TK(MINUS);
  740. else if (source[*pos] == '*' && ++(*pos))
  741. return TK(STAR);
  742. else if (source[*pos] == '/' && ++(*pos))
  743. return TK(SLASH);
  744. else if (source[*pos] == '%' && ++(*pos))
  745. return TK(PERCENT);
  746. else if (source[*pos] == '?' && ++(*pos))
  747. return TK(QM);
  748. else if (source[*pos] == ':' && ++(*pos))
  749. return TK(COLON);
  750. else if (source[*pos] == '=' && ++(*pos))
  751. return TK(ASSIGN);
  752. else if (source[*pos] == ';' && ++(*pos))
  753. return TK(SEMI);
  754. else if (source[*pos] == ',' && ++(*pos))
  755. return TK(COMMA);
  756. else if (source[*pos] == '.' && ++(*pos))
  757. return TK(DOT);
  758. else if (source[*pos] == '<' && ++(*pos))
  759. return TK(LT);
  760. else if (source[*pos] == '>' && ++(*pos))
  761. return TK(GT);
  762. else if (source[*pos] == '!' && ++(*pos))
  763. return TK(BANG);
  764. else if (source[*pos] == '|' && ++(*pos))
  765. return TK(BAR);
  766. else if (source[*pos] == '&' && ++(*pos))
  767. return TK(AND);
  768. else if (source[*pos] == '^' && ++(*pos))
  769. return TK(RAISE);
  770. else if (source[*pos] == '~' && ++(*pos))
  771. return TK(TILDE);
  772. else if (source[*pos] == '@' && ++(*pos))
  773. return TK(AT);
  774. LEX_ERROR("unexpected input")
  775. }
  776. list_t *tokenize(char *source) {
  777. size_t pos = 0;
  778. list_t *toks = list_new();
  779. do {
  780. consume_ignored(source, &pos);
  781. size_t tok_pos = pos;
  782. token_t *tok = next_token(source, &pos);
  783. tok->fi = FILES->length - 1;
  784. tok->pos = tok_pos;
  785. list_push(toks, tok);
  786. if (tok->tag == T_EOF)
  787. break;
  788. } while (1);
  789. return toks;
  790. }
  791. int DEBUG = 0;
  792. list_t *DEBUGDATA;
  793. list_t *FUNCNAMES;
  794. struct _node_t {
  795. enum {
  796. N_TOPLEVEL,
  797. N_PROGRAM,
  798. N_EXPRSTMT,
  799. N_BLOCK,
  800. N_EXPRS_BEGIN,
  801. N_COMMA,
  802. N_NOT,
  803. N_NEGATE,
  804. N_UNARY_PLUS,
  805. N_BNOT,
  806. N_LITERAL,
  807. N_LIST,
  808. N_LISTGEN,
  809. N_TUPLE,
  810. N_NILTUPLE,
  811. N_TABLE,
  812. N_CALL,
  813. N_MEMBER,
  814. N_INDEX,
  815. N_SLICE,
  816. N_ADD,
  817. N_SUB,
  818. N_MUL,
  819. N_DIV,
  820. N_IDIV,
  821. N_MOD,
  822. N_POW,
  823. N_SHL,
  824. N_SHR,
  825. N_XOR,
  826. N_BOR,
  827. N_BAND,
  828. N_ASSIGN,
  829. N_ASSIGN_ADD,
  830. N_ASSIGN_SUB,
  831. N_ASSIGN_MUL,
  832. N_ASSIGN_DIV,
  833. N_ASSIGN_IDIV,
  834. N_ASSIGN_MOD,
  835. N_ASSIGN_POW,
  836. N_ASSIGN_BOR,
  837. N_ASSIGN_BAND,
  838. N_ASSIGN_XOR,
  839. N_ASSIGN_SHL,
  840. N_ASSIGN_SHR,
  841. N_EQUALS,
  842. N_NOTEQUALS,
  843. N_IS,
  844. N_IN,
  845. N_NOTIS,
  846. N_NOTIN,
  847. N_LT,
  848. N_GT,
  849. N_LE,
  850. N_GE,
  851. N_INC,
  852. N_DEC,
  853. N_PINC,
  854. N_PDEC,
  855. N_IFEXPR,
  856. N_FUNCEXPR,
  857. N_LOGOR,
  858. N_LOGAND,
  859. N_EXPRS_END,
  860. N_STAR,
  861. N_VAR,
  862. N_LET,
  863. N_VARUNPACK,
  864. N_LETUNPACK,
  865. N_CONST,
  866. N_IF,
  867. N_SWITCH,
  868. N_FOR,
  869. N_FOROF,
  870. N_FOROFVAR,
  871. N_FOROFUNPACK,
  872. N_FOROFVARUNPACK,
  873. N_BREAK,
  874. N_CONTINUE,
  875. N_FUNCDEF,
  876. N_RETURN,
  877. N_DEFER,
  878. N_PASS,
  879. N_REQUIRE,
  880. N_TRY,
  881. N_THROW,
  882. N_LABEL,
  883. N_GOTO,
  884. N_CLASS,
  885. N_DEL,
  886. N_INLINE,
  887. N_HEADER,
  888. N_INCLUDE,
  889. N_BUFFER,
  890. N_MACRO_CALL,
  891. N_MVAR,
  892. N_MIF,
  893. N_MFOR,
  894. N_MREPEAT,
  895. N_MSET,
  896. N_MPUSH,
  897. N_MSTMT,
  898. N_MEXPR
  899. } tag;
  900. struct _node_t *a;
  901. struct _node_t *b;
  902. struct _node_t *c;
  903. struct _node_t *d;
  904. list_t *l;
  905. list_t *l2;
  906. table_t *h;
  907. table_t *h2;
  908. token_t *t;
  909. token_t *t2;
  910. buffer_t *buf;
  911. size_t fi;
  912. size_t pos;
  913. };
  914. typedef struct _node_t node_t;
  915. node_t *node_pos(node_t *node, size_t fi, size_t pos) {
  916. node->fi = fi;
  917. node->pos = pos;
  918. return node;
  919. }
  920. node_t *node_copy(node_t *node) {
  921. node_t *nnode = malloc_checked(sizeof(node_t));
  922. memcpy(nnode, node, sizeof(node_t));
  923. return nnode;
  924. }
  925. node_t *nodet(int tag, token_t *t) {
  926. node_t *node = malloc_checked(sizeof(node_t));
  927. node->tag = tag;
  928. node->t = t;
  929. return node;
  930. }
  931. #define NODET(n, a) \
  932. (node_pos(nodet(N_##n, (a)), \
  933. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  934. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  935. node_t *nodel(int tag, list_t *l) {
  936. node_t *node = malloc_checked(sizeof(node_t));
  937. node->tag = tag;
  938. node->l = l;
  939. return node;
  940. }
  941. #define NODEL(n, a) \
  942. (node_pos(nodel(N_##n, (a)), \
  943. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  944. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  945. node_t *nodetl(int tag, token_t *t, list_t *l) {
  946. node_t *node = malloc_checked(sizeof(node_t));
  947. node->tag = tag;
  948. node->t = t;
  949. node->l = l;
  950. return node;
  951. }
  952. #define NODETL(n, t, l) \
  953. (node_pos(nodetl(N_##n, (t), (l)), \
  954. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  955. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  956. node_t *nodeh(int tag, table_t *h) {
  957. node_t *node = malloc_checked(sizeof(node_t));
  958. node->tag = tag;
  959. node->h = h;
  960. return node;
  961. }
  962. #define NODEH(n, a) \
  963. (node_pos(nodeh(N_##n, (a)), \
  964. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  965. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  966. node_t *node0(int tag) {
  967. node_t *node = malloc_checked(sizeof(node_t));
  968. node->tag = tag;
  969. return node;
  970. }
  971. #define NODE0(n) \
  972. (node_pos(node0(N_##n), \
  973. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  974. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  975. node_t *node1(int tag, node_t *a) {
  976. node_t *node = malloc_checked(sizeof(node_t));
  977. node->tag = tag;
  978. node->a = a;
  979. return node;
  980. }
  981. #define NODE1(n, a) \
  982. (node_pos(node1(N_##n, (a)), \
  983. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  984. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  985. node_t *node1l(int tag, node_t *a, list_t *l) {
  986. node_t *node = malloc_checked(sizeof(node_t));
  987. node->tag = tag;
  988. node->a = a;
  989. node->l = l;
  990. return node;
  991. }
  992. #define NODE1l(n, a, l) \
  993. (node_pos(node1l(N_##n, (a), (l)), \
  994. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  995. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  996. node_t *node1l2(int tag, node_t *a, list_t *l, list_t *l2) {
  997. node_t *node = malloc_checked(sizeof(node_t));
  998. node->tag = tag;
  999. node->a = a;
  1000. node->l = l;
  1001. node->l2 = l2;
  1002. return node;
  1003. }
  1004. #define NODE1l2(n, a, l, l2) \
  1005. (node_pos(node1l2(N_##n, (a), (l), (l2)), \
  1006. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1007. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1008. node_t *node1t(int tag, node_t *a, token_t *t) {
  1009. node_t *node = malloc_checked(sizeof(node_t));
  1010. node->tag = tag;
  1011. node->a = a;
  1012. node->t = t;
  1013. return node;
  1014. }
  1015. #define NODE1t(n, a, t) \
  1016. (node_pos(node1t(N_##n, (a), (t)), \
  1017. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1018. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1019. node_t *node2(int tag, node_t *a, node_t *b) {
  1020. node_t *node = malloc_checked(sizeof(node_t));
  1021. node->tag = tag;
  1022. node->a = a;
  1023. node->b = b;
  1024. return node;
  1025. }
  1026. #define NODE2(n, a, b) \
  1027. (node_pos(node2(N_##n, (a), (b)), \
  1028. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1029. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1030. node_t *node2l(int tag, node_t *a, node_t *b, list_t *l) {
  1031. node_t *node = malloc_checked(sizeof(node_t));
  1032. node->tag = tag;
  1033. node->a = a;
  1034. node->b = b;
  1035. node->l = l;
  1036. return node;
  1037. }
  1038. #define NODE2l(n, a, b, l) \
  1039. (node_pos(node2l(N_##n, (a), (b), (l)), \
  1040. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1041. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1042. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t) {
  1043. node_t *node = malloc_checked(sizeof(node_t));
  1044. node->tag = tag;
  1045. node->a = a;
  1046. node->b = b;
  1047. node->t = t;
  1048. return node;
  1049. }
  1050. #define NODE2t(n, a, b, c) \
  1051. (node_pos(node2t(N_##n, (a), (b), (c)), \
  1052. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1053. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1054. node_t *node3(int tag, node_t *a, node_t *b, node_t *c) {
  1055. node_t *node = malloc_checked(sizeof(node_t));
  1056. node->tag = tag;
  1057. node->a = a;
  1058. node->b = b;
  1059. node->c = c;
  1060. return node;
  1061. }
  1062. #define NODE3(n, a, b, c) \
  1063. (node_pos(node3(N_##n, (a), (b), (c)), \
  1064. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1065. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1066. node_t *node3t(int tag, node_t *a, node_t *b, node_t *c, token_t *t) {
  1067. node_t *node = malloc_checked(sizeof(node_t));
  1068. node->tag = tag;
  1069. node->a = a;
  1070. node->b = b;
  1071. node->c = c;
  1072. node->t = t;
  1073. return node;
  1074. }
  1075. #define NODE3t(n, a, b, c, d) \
  1076. (node_pos(node3t(N_##n, (a), (b), (c), (d)), \
  1077. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1078. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1079. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d) {
  1080. node_t *node = malloc_checked(sizeof(node_t));
  1081. node->tag = tag;
  1082. node->a = a;
  1083. node->b = b;
  1084. node->c = c;
  1085. node->d = d;
  1086. return node;
  1087. }
  1088. #define NODE4(n, a, b, c, d) \
  1089. (node_pos(node4(N_##n, (a), (b), (c), (d)), \
  1090. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1091. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1092. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured,
  1093. node_t *body) {
  1094. node_t *node = malloc_checked(sizeof(node_t));
  1095. node->tag = tag;
  1096. node->t = name;
  1097. node->h = params;
  1098. node->h2 = captured;
  1099. node->a = body;
  1100. return node;
  1101. }
  1102. #define NODEF(n, a, b, c, d) \
  1103. (node_pos(nodef(N_##n, (a), (b), (c), (d)), \
  1104. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1105. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1106. node_t *nodeb(buffer_t *buf) {
  1107. node_t *node = malloc_checked(sizeof(node_t));
  1108. node->tag = N_BUFFER;
  1109. node->buf = buf;
  1110. return node;
  1111. }
  1112. typedef struct {
  1113. char *name;
  1114. list_t *params;
  1115. list_t *body;
  1116. int variable;
  1117. } macro_t;
  1118. list_t *MACROS;
  1119. #define LABELLOOP(n) \
  1120. node_t *ln = (n); \
  1121. ln->t2 = label;
  1122. #define AT(tk) \
  1123. (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  1124. #define ATP(tk, p) \
  1125. ((*pos) + p < tokens->length && \
  1126. ((token_t *)tokens->data[(*pos) + p])->tag == T_##tk)
  1127. #define MATCH(tk) (AT(tk) && ++(*pos))
  1128. #define PARSE_ERROR(fmt, ...) \
  1129. { \
  1130. format_error( \
  1131. GETFNAME( \
  1132. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi), \
  1133. GETSRC( \
  1134. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi), \
  1135. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos, fmt, \
  1136. ##__VA_ARGS__); \
  1137. exit(1); \
  1138. }
  1139. #define EXPECT(tk, s) \
  1140. { \
  1141. if (!MATCH(tk)) \
  1142. PARSE_ERROR("expected %s", (s)); \
  1143. }
  1144. node_t *parse_expr(list_t *tokens, size_t *pos);
  1145. list_t *parse_sequence(list_t *tokens, size_t *pos, int term) {
  1146. list_t *seq = list_new();
  1147. do {
  1148. if (term != -1 && *pos < tokens->length &&
  1149. ((token_t *)tokens->data[*pos])->tag == term)
  1150. break;
  1151. if (MATCH(STAR))
  1152. list_push(seq, NODE1(STAR, parse_expr(tokens, pos)));
  1153. else
  1154. list_push(seq, parse_expr(tokens, pos));
  1155. } while (MATCH(COMMA));
  1156. return seq;
  1157. }
  1158. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  1159. char *unescape(char *s);
  1160. node_t *parse_primary(list_t *tokens, size_t *pos) {
  1161. if (MATCH(MVAR))
  1162. return NODET(MVAR, tokens->data[(*pos) - 1]);
  1163. else if (MATCH(FUNC))
  1164. return parse_func(tokens, pos, 1);
  1165. else if (MATCH(LPAR)) {
  1166. if (MATCH(RPAR))
  1167. return NODE0(NILTUPLE);
  1168. node_t *a = parse_expr(tokens, pos);
  1169. if (MATCH(COMMA)) {
  1170. list_t *l = list_new();
  1171. list_push(l, a);
  1172. if (!AT(RPAR))
  1173. do {
  1174. node_t *n = parse_expr(tokens, pos);
  1175. list_push(l, n);
  1176. } while (MATCH(COMMA));
  1177. a = NODEL(TUPLE, l);
  1178. }
  1179. EXPECT(RPAR, ")");
  1180. return a;
  1181. } else if (MATCH(LSB)) {
  1182. list_t *a = parse_sequence(tokens, pos, T_RSB);
  1183. node_t *loop = NULL;
  1184. node_t *cond = NULL;
  1185. if (MATCH(FOR)) {
  1186. if (MATCH(LSB)) {
  1187. list_t *l = list_new();
  1188. do {
  1189. if (!AT(NAME))
  1190. PARSE_ERROR("expected identifier");
  1191. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1192. } while (MATCH(COMMA));
  1193. EXPECT(RSB, "]");
  1194. EXPECT(OF, "of");
  1195. loop = NODE2l(FOROFUNPACK, parse_expr(tokens, pos), NODEL(LIST, a), l);
  1196. } else {
  1197. if (!AT(NAME))
  1198. PARSE_ERROR("expected identifier");
  1199. token_t *t = tokens->data[(*pos)++];
  1200. EXPECT(OF, "of");
  1201. loop = NODE2t(FOROF, parse_expr(tokens, pos), NODEL(LIST, a), t);
  1202. }
  1203. if (MATCH(IF))
  1204. cond = parse_expr(tokens, pos);
  1205. }
  1206. EXPECT(RSB, "]");
  1207. if (loop)
  1208. return NODE2(LISTGEN, loop, cond);
  1209. return NODEL(LIST, a);
  1210. } else if (MATCH(LCB)) {
  1211. table_t *table = table_new();
  1212. do {
  1213. if (AT(RCB))
  1214. break;
  1215. if (!AT(NAME) && !AT(STRING))
  1216. PARSE_ERROR("expected identifier or string");
  1217. int is_str = AT(STRING);
  1218. char *key = ((token_t *)tokens->data[(*pos)++])->text;
  1219. EXPECT(COLON, ":");
  1220. node_t *val = parse_expr(tokens, pos);
  1221. table_set(table, is_str ? unescape(key) : key, val);
  1222. } while (MATCH(COMMA));
  1223. EXPECT(RCB, "}");
  1224. return NODEH(TABLE, table);
  1225. } else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(FSTRING) || MATCH(USTRING) || MATCH(NAME) || MATCH(TRUE) || MATCH(FALSE) || MATCH(NIL))
  1226. return NODET(LITERAL, tokens->data[(*pos) - 1]);
  1227. if (MATCH(RPAR)) {
  1228. PARSE_ERROR("extraneous )");
  1229. } else if (MATCH(RSB)) {
  1230. PARSE_ERROR("extraneous ]");
  1231. } else if (MATCH(RCB)) {
  1232. PARSE_ERROR("extraneous }");
  1233. } else {
  1234. PARSE_ERROR("expected expression");
  1235. }
  1236. return NULL;
  1237. }
  1238. size_t get_lineno(token_t *tok) {
  1239. size_t line, col;
  1240. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  1241. return line;
  1242. }
  1243. #define CLIFF \
  1244. (get_lineno(((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])) != \
  1245. get_lineno( \
  1246. ((token_t *)tokens \
  1247. ->data[(*pos) >= tokens->length ? tokens->length - 1 : (*pos)])))
  1248. #define CLIFF_AHEAD \
  1249. (get_lineno(( \
  1250. (token_t *)tokens \
  1251. ->data[(*pos) >= tokens->length ? tokens->length - 1 : (*pos)])) != \
  1252. get_lineno(((token_t *)tokens \
  1253. ->data[(*pos) + 1 >= tokens->length ? tokens->length - 1 \
  1254. : (*pos) + 1])))
  1255. node_t *_parse_stmt(list_t *tokens, size_t *pos, int allow_comma);
  1256. #define parse_stmt(t, p) (_parse_stmt((t), (p), 0))
  1257. #define parse_stmt_c(t, p) (_parse_stmt((t), (p), 1))
  1258. node_t *parse_call(list_t *tokens, size_t *pos) {
  1259. node_t *a = parse_primary(tokens, pos);
  1260. if (a->tag == N_LITERAL && a->t->tag == T_NAME && !CLIFF && !CLIFF_AHEAD &&
  1261. AT(BANG) && ATP(LPAR, 1)) {
  1262. MATCH(BANG);
  1263. MATCH(LPAR);
  1264. list_t *args = list_new();
  1265. if (!AT(RPAR))
  1266. do {
  1267. node_t *n = parse_stmt(tokens, pos);
  1268. if (n->tag == N_BLOCK)
  1269. n->tag = N_PROGRAM;
  1270. else if (n->tag == N_EXPRSTMT)
  1271. n = n->a;
  1272. list_push(args, n);
  1273. } while (MATCH(COMMA));
  1274. EXPECT(RPAR, ")");
  1275. return NODETL(MACRO_CALL, a->t, args);
  1276. }
  1277. do {
  1278. if (!CLIFF && MATCH(LPAR)) {
  1279. list_t *b = NULL;
  1280. if (!AT(RPAR))
  1281. b = parse_sequence(tokens, pos, -1);
  1282. EXPECT(RPAR, ")");
  1283. a = NODE1l(CALL, a, b);
  1284. continue;
  1285. } else if (!CLIFF && MATCH(LSB)) {
  1286. if (MATCH(COLON)) {
  1287. a = NODE3(SLICE, a, NULL, parse_expr(tokens, pos));
  1288. EXPECT(RSB, "]");
  1289. continue;
  1290. }
  1291. node_t *b = parse_expr(tokens, pos);
  1292. if (MATCH(COLON)) {
  1293. node_t *c = NULL;
  1294. if (!AT(RSB))
  1295. c = parse_expr(tokens, pos);
  1296. EXPECT(RSB, "]");
  1297. a = NODE3(SLICE, a, b, c);
  1298. continue;
  1299. }
  1300. EXPECT(RSB, "]");
  1301. a = NODE2(INDEX, a, b);
  1302. continue;
  1303. } else if (!CLIFF && MATCH(DOT)) {
  1304. if (!AT(NAME))
  1305. PARSE_ERROR("expected identifier after .");
  1306. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  1307. continue;
  1308. }
  1309. break;
  1310. } while (1);
  1311. return a;
  1312. }
  1313. node_t *parse_postfix(list_t *tokens, size_t *pos) {
  1314. node_t *a = parse_call(tokens, pos);
  1315. if (CLIFF)
  1316. return a;
  1317. if (MATCH(PLUSPLUS))
  1318. return NODE1(INC, a);
  1319. else if (MATCH(MINUSMINUS))
  1320. return NODE1(DEC, a);
  1321. return a;
  1322. }
  1323. node_t *parse_unary(list_t *tokens, size_t *pos) {
  1324. if (MATCH(MINUS)) {
  1325. node_t *a = parse_unary(tokens, pos);
  1326. return NODE1(NEGATE, a);
  1327. } else if (MATCH(PLUS)) {
  1328. node_t *a = parse_unary(tokens, pos);
  1329. return NODE1(UNARY_PLUS, a);
  1330. } else if (MATCH(BANG)) {
  1331. node_t *a = parse_unary(tokens, pos);
  1332. return NODE1(NOT, a);
  1333. } else if (MATCH(TILDE)) {
  1334. node_t *a = parse_unary(tokens, pos);
  1335. return NODE1(BNOT, a);
  1336. } else if (MATCH(PLUSPLUS)) {
  1337. node_t *a = parse_postfix(tokens, pos);
  1338. return NODE1(PINC, a);
  1339. } else if (MATCH(MINUSMINUS)) {
  1340. node_t *a = parse_postfix(tokens, pos);
  1341. return NODE1(PDEC, a);
  1342. }
  1343. return parse_postfix(tokens, pos);
  1344. }
  1345. node_t *parse_pow(list_t *tokens, size_t *pos) {
  1346. node_t *a = parse_unary(tokens, pos);
  1347. do {
  1348. if (MATCH(STARSTAR)) {
  1349. node_t *b = parse_unary(tokens, pos);
  1350. a = NODE2(POW, a, b);
  1351. continue;
  1352. }
  1353. break;
  1354. } while (1);
  1355. return a;
  1356. }
  1357. node_t *parse_mul(list_t *tokens, size_t *pos) {
  1358. node_t *a = parse_pow(tokens, pos);
  1359. do {
  1360. if (MATCH(STAR)) {
  1361. node_t *b = parse_pow(tokens, pos);
  1362. a = NODE2(MUL, a, b);
  1363. continue;
  1364. } else if (MATCH(SLASH)) {
  1365. node_t *b = parse_pow(tokens, pos);
  1366. a = NODE2(DIV, a, b);
  1367. continue;
  1368. } else if (MATCH(SLASHSLASH)) {
  1369. node_t *b = parse_pow(tokens, pos);
  1370. a = NODE2(IDIV, a, b);
  1371. continue;
  1372. } else if (MATCH(PERCENT)) {
  1373. node_t *b = parse_pow(tokens, pos);
  1374. a = NODE2(MOD, a, b);
  1375. continue;
  1376. }
  1377. break;
  1378. } while (1);
  1379. return a;
  1380. }
  1381. node_t *parse_add(list_t *tokens, size_t *pos) {
  1382. node_t *a = parse_mul(tokens, pos);
  1383. do {
  1384. if (MATCH(PLUS)) {
  1385. node_t *b = parse_mul(tokens, pos);
  1386. a = NODE2(ADD, a, b);
  1387. continue;
  1388. } else if (MATCH(MINUS)) {
  1389. node_t *b = parse_mul(tokens, pos);
  1390. a = NODE2(SUB, a, b);
  1391. continue;
  1392. }
  1393. break;
  1394. } while (1);
  1395. return a;
  1396. }
  1397. node_t *parse_shift(list_t *tokens, size_t *pos) {
  1398. node_t *a = parse_add(tokens, pos);
  1399. do {
  1400. if (MATCH(LTLT)) {
  1401. node_t *b = parse_add(tokens, pos);
  1402. a = NODE2(SHL, a, b);
  1403. continue;
  1404. } else if (MATCH(GTGT)) {
  1405. node_t *b = parse_add(tokens, pos);
  1406. a = NODE2(SHR, a, b);
  1407. continue;
  1408. }
  1409. break;
  1410. } while (1);
  1411. return a;
  1412. }
  1413. node_t *parse_relation(list_t *tokens, size_t *pos) {
  1414. node_t *a = parse_shift(tokens, pos);
  1415. do {
  1416. if (MATCH(LT)) {
  1417. node_t *b = parse_shift(tokens, pos);
  1418. a = NODE2(LT, a, b);
  1419. continue;
  1420. } else if (MATCH(GT)) {
  1421. node_t *b = parse_shift(tokens, pos);
  1422. a = NODE2(GT, a, b);
  1423. continue;
  1424. } else if (MATCH(LE)) {
  1425. node_t *b = parse_shift(tokens, pos);
  1426. a = NODE2(LE, a, b);
  1427. continue;
  1428. } else if (MATCH(GE)) {
  1429. node_t *b = parse_shift(tokens, pos);
  1430. a = NODE2(GE, a, b);
  1431. continue;
  1432. }
  1433. break;
  1434. } while (1);
  1435. return a;
  1436. }
  1437. node_t *parse_equality(list_t *tokens, size_t *pos) {
  1438. node_t *a = parse_relation(tokens, pos);
  1439. do {
  1440. if (MATCH(EQUALS)) {
  1441. node_t *b = parse_relation(tokens, pos);
  1442. a = NODE2(EQUALS, a, b);
  1443. continue;
  1444. } else if (MATCH(NOTEQUALS)) {
  1445. node_t *b = parse_relation(tokens, pos);
  1446. a = NODE2(NOTEQUALS, a, b);
  1447. continue;
  1448. } else if (MATCH(IS)) {
  1449. node_t *b = parse_relation(tokens, pos);
  1450. a = NODE2(IS, a, b);
  1451. continue;
  1452. } else if (AT(BANG) && ATP(IS, 1)) {
  1453. EXPECT(BANG, "!");
  1454. EXPECT(IS, "is");
  1455. node_t *b = parse_relation(tokens, pos);
  1456. a = NODE2(NOTIS, a, b);
  1457. continue;
  1458. } else if (MATCH(IN)) {
  1459. node_t *b = parse_relation(tokens, pos);
  1460. a = NODE2(IN, a, b);
  1461. continue;
  1462. } else if (AT(BANG) && ATP(IN, 1)) {
  1463. EXPECT(BANG, "!");
  1464. EXPECT(IN, "in");
  1465. node_t *b = parse_relation(tokens, pos);
  1466. a = NODE2(NOTIN, a, b);
  1467. continue;
  1468. }
  1469. break;
  1470. } while (1);
  1471. return a;
  1472. }
  1473. node_t *parse_bitand(list_t *tokens, size_t *pos) {
  1474. node_t *a = parse_equality(tokens, pos);
  1475. while (MATCH(AND)) {
  1476. node_t *b = parse_equality(tokens, pos);
  1477. a = NODE2(BAND, a, b);
  1478. }
  1479. return a;
  1480. }
  1481. node_t *parse_bitxor(list_t *tokens, size_t *pos) {
  1482. node_t *a = parse_bitand(tokens, pos);
  1483. while (MATCH(RAISE)) {
  1484. node_t *b = parse_bitand(tokens, pos);
  1485. a = NODE2(XOR, a, b);
  1486. }
  1487. return a;
  1488. }
  1489. node_t *parse_bitor(list_t *tokens, size_t *pos) {
  1490. node_t *a = parse_bitxor(tokens, pos);
  1491. while (MATCH(BAR)) {
  1492. node_t *b = parse_bitxor(tokens, pos);
  1493. a = NODE2(BOR, a, b);
  1494. }
  1495. return a;
  1496. }
  1497. node_t *parse_logand(list_t *tokens, size_t *pos) {
  1498. node_t *a = parse_bitor(tokens, pos);
  1499. if (MATCH(ANDAND)) {
  1500. node_t *b = parse_logand(tokens, pos);
  1501. return NODE2(LOGAND, a, b);
  1502. }
  1503. return a;
  1504. }
  1505. node_t *parse_logor(list_t *tokens, size_t *pos) {
  1506. node_t *a = parse_logand(tokens, pos);
  1507. if (MATCH(BARBAR)) {
  1508. node_t *b = parse_logor(tokens, pos);
  1509. return NODE2(LOGOR, a, b);
  1510. }
  1511. return a;
  1512. }
  1513. node_t *parse_assignment(list_t *tokens, size_t *pos);
  1514. node_t *parse_conditional(list_t *tokens, size_t *pos) {
  1515. node_t *a = parse_logor(tokens, pos);
  1516. if (MATCH(QM)) {
  1517. node_t *b = parse_assignment(tokens, pos);
  1518. EXPECT(COLON, ":");
  1519. node_t *c = parse_assignment(tokens, pos);
  1520. return NODE3(IFEXPR, a, b, c);
  1521. }
  1522. return a;
  1523. }
  1524. node_t *parse_assignment(list_t *tokens, size_t *pos) {
  1525. node_t *a = parse_conditional(tokens, pos);
  1526. if (MATCH(ASSIGN)) {
  1527. node_t *b = parse_assignment(tokens, pos);
  1528. return NODE2(ASSIGN, a, b);
  1529. } else if (MATCH(PLUSASSIGN)) {
  1530. node_t *b = parse_assignment(tokens, pos);
  1531. return NODE2(ASSIGN_ADD, a, b);
  1532. } else if (MATCH(MINUSASSIGN)) {
  1533. node_t *b = parse_assignment(tokens, pos);
  1534. return NODE2(ASSIGN_SUB, a, b);
  1535. } else if (MATCH(STARASSIGN)) {
  1536. node_t *b = parse_assignment(tokens, pos);
  1537. return NODE2(ASSIGN_MUL, a, b);
  1538. } else if (MATCH(SLASHASSIGN)) {
  1539. node_t *b = parse_assignment(tokens, pos);
  1540. return NODE2(ASSIGN_DIV, a, b);
  1541. } else if (MATCH(SLASHSLASHASSIGN)) {
  1542. node_t *b = parse_assignment(tokens, pos);
  1543. return NODE2(ASSIGN_IDIV, a, b);
  1544. } else if (MATCH(PERCENTASSIGN)) {
  1545. node_t *b = parse_assignment(tokens, pos);
  1546. return NODE2(ASSIGN_MOD, a, b);
  1547. } else if (MATCH(STARSTARASSIGN)) {
  1548. node_t *b = parse_assignment(tokens, pos);
  1549. return NODE2(ASSIGN_POW, a, b);
  1550. } else if (MATCH(BARASSIGN)) {
  1551. node_t *b = parse_assignment(tokens, pos);
  1552. return NODE2(ASSIGN_BOR, a, b);
  1553. } else if (MATCH(ANDASSIGN)) {
  1554. node_t *b = parse_assignment(tokens, pos);
  1555. return NODE2(ASSIGN_BAND, a, b);
  1556. } else if (MATCH(RAISEASSIGN)) {
  1557. node_t *b = parse_assignment(tokens, pos);
  1558. return NODE2(ASSIGN_XOR, a, b);
  1559. } else if (MATCH(LTLTASSIGN)) {
  1560. node_t *b = parse_assignment(tokens, pos);
  1561. return NODE2(ASSIGN_SHL, a, b);
  1562. } else if (MATCH(GTGTASSIGN)) {
  1563. node_t *b = parse_assignment(tokens, pos);
  1564. return NODE2(ASSIGN_SHR, a, b);
  1565. }
  1566. return a;
  1567. }
  1568. node_t *parse_expr(list_t *tokens, size_t *pos) {
  1569. return parse_assignment(tokens, pos);
  1570. }
  1571. node_t *parse_comma_expr(list_t *tokens, size_t *pos) {
  1572. node_t *a = parse_expr(tokens, pos);
  1573. if (MATCH(COMMA)) {
  1574. list_t *exprs = list_new();
  1575. list_push(exprs, a);
  1576. do {
  1577. list_push(exprs, parse_expr(tokens, pos));
  1578. } while (MATCH(COMMA));
  1579. a = NODEL(COMMA, exprs);
  1580. }
  1581. return a;
  1582. }
  1583. node_t *parse_block(list_t *tokens, size_t *pos) {
  1584. EXPECT(LCB, "{");
  1585. list_t *stmts = list_new();
  1586. while (!AT(EOF) && !AT(RCB)) {
  1587. list_push(stmts, parse_stmt_c(tokens, pos));
  1588. MATCH(SEMI);
  1589. }
  1590. EXPECT(RCB, "}");
  1591. return NODEL(PROGRAM, stmts);
  1592. }
  1593. #define BLOCK() \
  1594. (CLIFF || MATCH(COLON) ? parse_stmt(tokens, pos) : parse_block(tokens, pos))
  1595. #define STMT_OR_BLOCK() \
  1596. (MATCH(COLON) ? parse_stmt(tokens, pos) \
  1597. : AT(LCB) ? parse_block(tokens, pos) \
  1598. : parse_stmt(tokens, pos))
  1599. node_t *parse_if(list_t *tokens, size_t *pos) {
  1600. node_t *a = parse_expr(tokens, pos);
  1601. node_t *b = BLOCK();
  1602. node_t *c = NULL;
  1603. if (MATCH(ELSE))
  1604. c = STMT_OR_BLOCK();
  1605. else if (MATCH(ELIF))
  1606. c = parse_if(tokens, pos);
  1607. return NODE3(IF, a, b, c);
  1608. }
  1609. node_t *parse_var(list_t *tokens, size_t *pos, int is_let) {
  1610. table_t *h = table_new();
  1611. do {
  1612. if (!AT(NAME))
  1613. PARSE_ERROR("expected identifier");
  1614. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1615. node_t *v = NULL;
  1616. if (is_let) {
  1617. EXPECT(ASSIGN, "=");
  1618. v = parse_expr(tokens, pos);
  1619. } else if (MATCH(ASSIGN))
  1620. v = parse_expr(tokens, pos);
  1621. table_set(h, k, v);
  1622. } while (MATCH(COMMA));
  1623. if (is_let)
  1624. return NODEH(LET, h);
  1625. return NODEH(VAR, h);
  1626. }
  1627. node_t *parse_unpack(list_t *tokens, size_t *pos, int tag) {
  1628. EXPECT(LSB, "[");
  1629. list_t *l = list_new();
  1630. do {
  1631. if (!AT(NAME))
  1632. PARSE_ERROR("expected identifier");
  1633. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1634. } while (MATCH(COMMA));
  1635. EXPECT(RSB, "]");
  1636. EXPECT(ASSIGN, "=");
  1637. node_t *a = parse_expr(tokens, pos);
  1638. if (tag == N_LETUNPACK)
  1639. return NODE1l(LETUNPACK, a, l);
  1640. return NODE1l(VARUNPACK, a, l);
  1641. }
  1642. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr) {
  1643. token_t *name = NULL;
  1644. if (!is_expr) {
  1645. if (!AT(NAME))
  1646. PARSE_ERROR("expected identifier");
  1647. name = tokens->data[(*pos)++];
  1648. }
  1649. table_t *params = NULL;
  1650. if (MATCH(LPAR)) {
  1651. if (!AT(RPAR)) {
  1652. int flag = 0;
  1653. params = table_new();
  1654. size_t argc = 0;
  1655. do {
  1656. if (!AT(NAME))
  1657. PARSE_ERROR("expected identifier");
  1658. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  1659. node_t *r = NULL;
  1660. if (!flag && AT(ASSIGN))
  1661. flag = 1;
  1662. if (flag) {
  1663. EXPECT(ASSIGN, "=");
  1664. r = parse_expr(tokens, pos);
  1665. }
  1666. list_t *pair = list_new();
  1667. size_t *argcp = malloc_checked(sizeof(size_t));
  1668. memcpy(argcp, &argc, sizeof(size_t));
  1669. argc++;
  1670. list_push(pair, argcp);
  1671. list_push(pair, r);
  1672. table_set(params, l, pair);
  1673. } while (MATCH(COMMA));
  1674. }
  1675. EXPECT(RPAR, ")");
  1676. }
  1677. table_t *captured = NULL;
  1678. if (MATCH(USE)) {
  1679. EXPECT(LPAR, "(");
  1680. captured = table_new();
  1681. do {
  1682. if (!AT(NAME))
  1683. PARSE_ERROR("expected identifier");
  1684. token_t *name = tokens->data[(*pos)++];
  1685. table_set(captured, name->text, NODET(LITERAL, name));
  1686. } while (MATCH(COMMA));
  1687. EXPECT(RPAR, ")");
  1688. }
  1689. int colon = AT(COLON);
  1690. node_t *body = !colon && !AT(LCB) ? parse_stmt(tokens, pos) : BLOCK();
  1691. if (colon && body->tag == N_EXPRSTMT)
  1692. body = NODE1(RETURN, body->a);
  1693. if (is_expr)
  1694. return NODEF(FUNCEXPR, NULL, params, captured, body);
  1695. return NODEF(FUNCDEF, name, params, captured, body);
  1696. }
  1697. node_t *_parse_stmt(list_t *tokens, size_t *pos, int allow_comma) {
  1698. if (MATCH(LCB)) {
  1699. list_t *stmts = list_new();
  1700. while (!AT(EOF) && !AT(RCB)) {
  1701. node_t *n = parse_stmt_c(tokens, pos);
  1702. MATCH(SEMI);
  1703. list_push(stmts, n);
  1704. }
  1705. EXPECT(RCB, "}");
  1706. return NODEL(BLOCK, stmts);
  1707. } else if (MATCH(VAR)) {
  1708. if (AT(LSB))
  1709. return parse_unpack(tokens, pos, N_VARUNPACK);
  1710. return parse_var(tokens, pos, 0);
  1711. } else if (MATCH(LET)) {
  1712. if (AT(LSB))
  1713. return parse_unpack(tokens, pos, N_LETUNPACK);
  1714. return parse_var(tokens, pos, 1);
  1715. } else if (MATCH(CONST)) {
  1716. table_t *h = table_new();
  1717. do {
  1718. if (!AT(NAME))
  1719. PARSE_ERROR("expected identifier");
  1720. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1721. if (k[0] != '_' && !(k[0] >= 'A' && k[0] <= 'Z'))
  1722. PARSE_ERROR("compile-time constant identifiers must begin with an "
  1723. "uppercase letter or with an underscore, but '%s' does not",
  1724. k);
  1725. if (table_get(h, k))
  1726. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  1727. EXPECT(ASSIGN, "=");
  1728. node_t *v = parse_expr(tokens, pos);
  1729. table_set(h, k, v);
  1730. } while (MATCH(COMMA));
  1731. return NODEH(CONST, h);
  1732. } else if (MATCH(IF))
  1733. return parse_if(tokens, pos);
  1734. else if (MATCH(SWITCH)) {
  1735. token_t *label = NULL;
  1736. if (MATCH(AT)) {
  1737. if (!AT(NAME))
  1738. PARSE_ERROR("expected identifier");
  1739. label = tokens->data[(*pos)++];
  1740. }
  1741. node_t *a = parse_expr(tokens, pos);
  1742. EXPECT(LCB, "{");
  1743. list_t *cases = list_new();
  1744. int has_default = 0;
  1745. for (;;) {
  1746. if (AT(RCB))
  1747. break;
  1748. node_t *expr = NULL;
  1749. list_t *stmts = list_new();
  1750. if (MATCH(DEFAULT)) {
  1751. if (has_default)
  1752. PARSE_ERROR("duplicated default case in switch");
  1753. has_default = 1;
  1754. } else {
  1755. EXPECT(CASE, "case");
  1756. expr = parse_expr(tokens, pos);
  1757. }
  1758. MATCH(COLON);
  1759. while (!AT(CASE) && !AT(DEFAULT) && !AT(RCB))
  1760. list_push(stmts, parse_stmt(tokens, pos));
  1761. list_t *pair = list_new();
  1762. list_push(pair, expr);
  1763. list_push(pair, NODEL(PROGRAM, stmts));
  1764. list_push(cases, pair);
  1765. }
  1766. EXPECT(RCB, "}");
  1767. if (!cases->length)
  1768. PARSE_ERROR("empty switch statement");
  1769. LABELLOOP(NODE1l(SWITCH, a, cases));
  1770. return ln;
  1771. } else if (MATCH(FOR)) {
  1772. token_t *label = NULL;
  1773. if (MATCH(AT)) {
  1774. if (!AT(NAME))
  1775. PARSE_ERROR("expected identifier");
  1776. label = tokens->data[(*pos)++];
  1777. }
  1778. node_t *a = NULL;
  1779. node_t *b = NULL;
  1780. node_t *c = NULL;
  1781. if (!AT(LCB) && !AT(COLON) && !CLIFF) {
  1782. if (MATCH(LSB)) {
  1783. list_t *l = list_new();
  1784. do {
  1785. if (!AT(NAME))
  1786. PARSE_ERROR("expected identifier");
  1787. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1788. } while (MATCH(COMMA));
  1789. EXPECT(RSB, "]");
  1790. EXPECT(OF, "of");
  1791. a = parse_expr(tokens, pos);
  1792. b = BLOCK();
  1793. LABELLOOP(NODE2l(FOROFUNPACK, a, b, l));
  1794. return ln;
  1795. }
  1796. if (AT(NAME) && ATP(OF, 1)) {
  1797. token_t *t = tokens->data[(*pos)++];
  1798. EXPECT(OF, "of");
  1799. a = parse_expr(tokens, pos);
  1800. b = BLOCK();
  1801. LABELLOOP(NODE2t(FOROF, a, b, t));
  1802. return ln;
  1803. }
  1804. if (MATCH(VAR)) {
  1805. if (MATCH(LSB)) {
  1806. list_t *l = list_new();
  1807. do {
  1808. if (!AT(NAME))
  1809. PARSE_ERROR("expected identifier");
  1810. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1811. } while (MATCH(COMMA));
  1812. EXPECT(RSB, "]");
  1813. EXPECT(OF, "of");
  1814. a = parse_expr(tokens, pos);
  1815. b = BLOCK();
  1816. LABELLOOP(NODE2l(FOROFVARUNPACK, a, b, l));
  1817. return ln;
  1818. }
  1819. if (AT(NAME) && ATP(OF, 1)) {
  1820. token_t *t = tokens->data[(*pos)++];
  1821. EXPECT(OF, "of");
  1822. a = parse_expr(tokens, pos);
  1823. b = BLOCK();
  1824. LABELLOOP(NODE2t(FOROFVAR, a, b, t));
  1825. return ln;
  1826. }
  1827. a = parse_var(tokens, pos, 0);
  1828. EXPECT(SEMI, ";");
  1829. b = parse_comma_expr(tokens, pos);
  1830. if (MATCH(SEMI))
  1831. c = parse_comma_expr(tokens, pos);
  1832. } else {
  1833. a = parse_comma_expr(tokens, pos);
  1834. if (MATCH(SEMI)) {
  1835. b = parse_comma_expr(tokens, pos);
  1836. if (MATCH(SEMI))
  1837. c = parse_comma_expr(tokens, pos);
  1838. }
  1839. }
  1840. }
  1841. node_t *d = BLOCK();
  1842. LABELLOOP(NODE4(FOR, a, b, c, d));
  1843. return ln;
  1844. } else if (MATCH(BREAK)) {
  1845. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1846. return NODET(BREAK, tokens->data[(*pos)++]);
  1847. return NODE0(BREAK);
  1848. } else if (MATCH(CONTINUE)) {
  1849. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1850. return NODET(CONTINUE, tokens->data[(*pos)++]);
  1851. return NODE0(CONTINUE);
  1852. } else if (MATCH(FUNC))
  1853. return parse_func(tokens, pos, 0);
  1854. else if (MATCH(RETURN)) {
  1855. node_t *a = NULL;
  1856. if (!AT(RCB) && !CLIFF)
  1857. a = parse_expr(tokens, pos);
  1858. return NODE1(RETURN, a);
  1859. } else if (MATCH(DEFER)) {
  1860. node_t *a;
  1861. if (AT(LCB))
  1862. a = BLOCK();
  1863. else
  1864. a = parse_stmt(tokens, pos);
  1865. return NODE1(DEFER, a);
  1866. } else if (MATCH(PASS))
  1867. return NODE0(PASS);
  1868. else if (MATCH(TRY)) {
  1869. node_t *a = BLOCK();
  1870. token_t *t = NULL;
  1871. EXPECT(CATCH, "catch");
  1872. if (!AT(COLON) && !AT(LCB) && !CLIFF) {
  1873. if (!AT(NAME))
  1874. PARSE_ERROR("expected identifier");
  1875. t = tokens->data[(*pos)++];
  1876. }
  1877. node_t *b = BLOCK();
  1878. node_t *c = NULL;
  1879. if (MATCH(FINALLY))
  1880. c = BLOCK();
  1881. return NODE3t(TRY, a, b, c, t);
  1882. } else if (MATCH(THROW)) {
  1883. node_t *a = NULL;
  1884. if (!CLIFF && !AT(COMMA) && !AT(RPAR) && !AT(RCB) && !AT(EOF))
  1885. a = parse_expr(tokens, pos);
  1886. return NODE1(THROW, a);
  1887. } else if (MATCH(GOTO)) {
  1888. if (!AT(NAME))
  1889. PARSE_ERROR("expected identifier");
  1890. token_t *t = tokens->data[(*pos)++];
  1891. return NODET(GOTO, t);
  1892. } else if (AT(NAME) && ATP(COLON, 1) && !CLIFF_AHEAD) {
  1893. token_t *t = tokens->data[(*pos)++];
  1894. EXPECT(COLON, ":");
  1895. return NODET(LABEL, t);
  1896. } else if (MATCH(CLASS)) {
  1897. if (!AT(NAME))
  1898. PARSE_ERROR("expected identifier");
  1899. token_t *t = tokens->data[(*pos)++];
  1900. list_t *l = NULL;
  1901. if (MATCH(LPAR)) {
  1902. l = list_new();
  1903. do {
  1904. if (!AT(NAME))
  1905. PARSE_ERROR("expected identifier");
  1906. token_t *t = tokens->data[(*pos)++];
  1907. list_push(l, t);
  1908. } while (MATCH(COMMA));
  1909. EXPECT(RPAR, ")");
  1910. }
  1911. EXPECT(LCB, "{");
  1912. list_t *triples = list_new();
  1913. for (;;) {
  1914. int is_out = 0;
  1915. int is_static = 0;
  1916. if (AT(RCB))
  1917. break;
  1918. if (MATCH(LET))
  1919. is_out = 1;
  1920. else if (MATCH(CONST))
  1921. is_static = 1;
  1922. if (!AT(NAME))
  1923. PARSE_ERROR("expected identifier");
  1924. list_t *triple = list_new();
  1925. token_t *t = tokens->data[(*pos)++];
  1926. list_push(triple, t);
  1927. int *flagp = malloc_checked(sizeof(int));
  1928. int flag = is_static ? 2 : is_out ? 1 : 0;
  1929. memcpy(flagp, &flag, sizeof(int));
  1930. if (MATCH(ASSIGN)) {
  1931. list_push(triple, flagp);
  1932. list_push(triple, parse_expr(tokens, pos));
  1933. } else {
  1934. list_push(triple, flagp);
  1935. list_push(triple, parse_func(tokens, pos, 1));
  1936. }
  1937. list_push(triples, triple);
  1938. }
  1939. EXPECT(RCB, "}");
  1940. list_t *pair = list_new();
  1941. list_push(pair, l);
  1942. list_push(pair, triples);
  1943. return NODETL(CLASS, t, pair);
  1944. } else if (MATCH(DEL)) {
  1945. node_t *a = parse_expr(tokens, pos);
  1946. return NODE1(DEL, a);
  1947. } else if (MATCH(INLINE)) {
  1948. if (!AT(STRING))
  1949. PARSE_ERROR("expected string");
  1950. token_t *t = tokens->data[(*pos)++];
  1951. return NODET(INLINE, t);
  1952. }
  1953. return NODE1(EXPRSTMT, allow_comma? parse_comma_expr(tokens, pos): parse_expr(tokens, pos));
  1954. }
  1955. #define ATM(t) \
  1956. (AT(MVAR) && strcmp(((token_t *)tokens->data[*pos])->text, t) == 0)
  1957. #define MATCHM(t) (ATM(t) && MATCH(MVAR))
  1958. node_t *parse_mexpr(list_t *tokens, size_t *pos);
  1959. node_t *parse_mprimary(list_t *tokens, size_t *pos) {
  1960. if (MATCH(STAR))
  1961. return NODET(LITERAL, token(T_NAME, strdup("*")));
  1962. else if (MATCHM("{")) {
  1963. node_t *a = parse_stmt(tokens, pos);
  1964. if (!MATCHM("}"))
  1965. PARSE_ERROR("expected }$");
  1966. if (a->tag == N_EXPRSTMT)
  1967. a = a->a;
  1968. return NODE1(MSTMT, a);
  1969. } else if (MATCH(LPAR)) {
  1970. node_t *a = parse_mexpr(tokens, pos);
  1971. EXPECT(RPAR, ")");
  1972. return a;
  1973. } else if (MATCH(NAME) || MATCH(TRUE) || MATCH(FALSE) || MATCH(NIL)) {
  1974. token_t *t = tokens->data[(*pos) - 1];
  1975. int macro = 0;
  1976. if (!CLIFF && !CLIFF_AHEAD && AT(BANG) && ATP(LPAR, 1)) {
  1977. MATCH(BANG);
  1978. macro = 1;
  1979. }
  1980. if (!CLIFF && MATCH(LPAR)) {
  1981. list_t *args = list_new();
  1982. if (!AT(RPAR))
  1983. do {
  1984. list_push(args, parse_mexpr(tokens, pos));
  1985. } while (MATCH(COMMA));
  1986. EXPECT(RPAR, ")");
  1987. if (macro)
  1988. return NODETL(MACRO_CALL, t, args);
  1989. return NODETL(CALL, t, args);
  1990. }
  1991. return NODET(LITERAL, t);
  1992. } else if (MATCH(NUMBER) || MATCH(STRING))
  1993. return NODET(LITERAL, tokens->data[(*pos) - 1]);
  1994. PARSE_ERROR("expected m-expression");
  1995. return NULL;
  1996. }
  1997. node_t *parse_mexpr(list_t *tokens, size_t *pos) {
  1998. if (MATCH(MINUS)) {
  1999. node_t *a = parse_mexpr(tokens, pos);
  2000. return NODE1(NEGATE, a);
  2001. }
  2002. node_t *a = parse_mprimary(tokens, pos);
  2003. do {
  2004. if (MATCH(BAR)) {
  2005. node_t *b = parse_mprimary(tokens, pos);
  2006. a = NODE2(LOGOR, a, b);
  2007. continue;
  2008. } else if (MATCH(AND)) {
  2009. node_t *b = parse_mprimary(tokens, pos);
  2010. a = NODE2(LOGAND, a, b);
  2011. continue;
  2012. } else if (MATCH(PLUS)) {
  2013. node_t *b = parse_mprimary(tokens, pos);
  2014. a = NODE2(ADD, a, b);
  2015. continue;
  2016. } else if (MATCH(MINUS)) {
  2017. node_t *b = parse_mprimary(tokens, pos);
  2018. a = NODE2(SUB, a, b);
  2019. continue;
  2020. } else if (MATCH(STAR)) {
  2021. node_t *b = parse_mprimary(tokens, pos);
  2022. a = NODE2(MUL, a, b);
  2023. continue;
  2024. } else if (MATCH(SLASH)) {
  2025. node_t *b = parse_mprimary(tokens, pos);
  2026. a = NODE2(DIV, a, b);
  2027. continue;
  2028. } else if (MATCH(ASSIGN)) {
  2029. node_t *b = parse_mprimary(tokens, pos);
  2030. a = NODE2(EQUALS, a, b);
  2031. continue;
  2032. } else if (MATCH(LT)) {
  2033. node_t *b = parse_mprimary(tokens, pos);
  2034. a = NODE2(LT, a, b);
  2035. continue;
  2036. } else if (MATCH(GT)) {
  2037. node_t *b = parse_mprimary(tokens, pos);
  2038. a = NODE2(GT, a, b);
  2039. continue;
  2040. }
  2041. break;
  2042. } while (1);
  2043. return a;
  2044. }
  2045. node_t *parse_mstmt(list_t *tokens, size_t *pos);
  2046. node_t *parse_mif(list_t *tokens, size_t *pos, int sub) {
  2047. node_t *a = parse_mexpr(tokens, pos);
  2048. list_t *l = list_new();
  2049. list_t *l2 = NULL;
  2050. while (!AT(EOF) && !ATM("else") && !ATM("elif") && !ATM("endif"))
  2051. list_push(l, parse_mstmt(tokens, pos));
  2052. if (MATCHM("elif")) {
  2053. l2 = list_new();
  2054. list_push(l2, parse_mif(tokens, pos, 1));
  2055. } else if (MATCHM("else")) {
  2056. l2 = list_new();
  2057. while (!AT(EOF) && !ATM("endif"))
  2058. list_push(l2, parse_mstmt(tokens, pos));
  2059. }
  2060. if (!sub && !MATCHM("endif"))
  2061. PARSE_ERROR("expected $endif");
  2062. return NODE1l2(MIF, a, l, l2);
  2063. }
  2064. node_t *parse_mstmt(list_t *tokens, size_t *pos) {
  2065. if (MATCHM("if"))
  2066. return parse_mif(tokens, pos, 0);
  2067. else if (MATCHM("for")) {
  2068. node_t *a = parse_mexpr(tokens, pos);
  2069. list_t *l = list_new();
  2070. while (!AT(EOF) && !ATM("endfor"))
  2071. list_push(l, parse_mstmt(tokens, pos));
  2072. if (!MATCHM("endfor"))
  2073. PARSE_ERROR("expected $endfor");
  2074. return NODE1l(MFOR, a, l);
  2075. } else if (MATCHM("repeat")) {
  2076. node_t *a = parse_mexpr(tokens, pos);
  2077. list_t *l = list_new();
  2078. while (!AT(EOF) && !ATM("endrep"))
  2079. list_push(l, parse_mstmt(tokens, pos));
  2080. if (!MATCHM("endrep"))
  2081. PARSE_ERROR("expected $endrep");
  2082. return NODE1l(MREPEAT, a, l);
  2083. } else if (MATCHM("set")) {
  2084. if (!AT(NAME))
  2085. PARSE_ERROR("expected identifier");
  2086. token_t *t = tokens->data[(*pos)++];
  2087. node_t *a = parse_mexpr(tokens, pos);
  2088. return NODE1t(MSET, a, t);
  2089. } else if (MATCHM("push")) {
  2090. if (!AT(NAME))
  2091. PARSE_ERROR("expected identifier");
  2092. token_t *t = tokens->data[(*pos)++];
  2093. node_t *a = parse_mexpr(tokens, pos);
  2094. return NODE1t(MPUSH, a, t);
  2095. } else if (MATCHM("$")) {
  2096. node_t *a = parse_stmt(tokens, pos);
  2097. if (a->tag == N_EXPRSTMT)
  2098. a = a->a;
  2099. return NODE1(MSTMT, a);
  2100. } else if (MATCHM("{")) {
  2101. list_t *stmts = list_new();
  2102. while (!AT(EOF) && !ATM("}")) {
  2103. list_push(stmts, parse_stmt(tokens, pos));
  2104. MATCH(SEMI);
  2105. }
  2106. if (!MATCHM("}"))
  2107. PARSE_ERROR("expected }$");
  2108. return NODE1(MSTMT, nodel(N_PROGRAM, stmts));
  2109. } else if (MATCHM(":"))
  2110. return NODE1(MEXPR, parse_mexpr(tokens, pos));
  2111. node_t *a = parse_stmt(tokens, pos);
  2112. if (a->tag == N_EXPRSTMT)
  2113. a = a->a;
  2114. return a;
  2115. }
  2116. list_t *macros_get(char *name) {
  2117. list_t *val = NULL;
  2118. for (ssize_t i = MACROS->length - 1; i >= 0; i--)
  2119. if ((val = table_get(MACROS->data[i], name)))
  2120. break;
  2121. return val;
  2122. }
  2123. node_t *parse_program(list_t *tokens, size_t *pos) {
  2124. if (AT(EOF))
  2125. PARSE_ERROR("empty program");
  2126. list_t *stmts = list_new();
  2127. int flag = 0;
  2128. while (!AT(EOF) && *pos < tokens->length) {
  2129. node_t *n = NULL;
  2130. if (MATCH(REQUIRE)) {
  2131. if (flag)
  2132. PARSE_ERROR("misplaced require statement")
  2133. list_t *paths = list_new();
  2134. do {
  2135. if (!AT(STRING))
  2136. PARSE_ERROR("expected string");
  2137. list_push(paths, tokens->data[(*pos)++]);
  2138. } while (MATCH(COMMA));
  2139. n = NODEL(REQUIRE, paths);
  2140. } else if (MATCH(HEADER)) {
  2141. if (flag)
  2142. PARSE_ERROR("misplaced header statement")
  2143. if (!AT(STRING))
  2144. PARSE_ERROR("expected string");
  2145. token_t *text = tokens->data[(*pos)++];
  2146. n = NODET(HEADER, text);
  2147. } else if (MATCH(INCLUDE)) {
  2148. if (flag)
  2149. PARSE_ERROR("misplaced include statement")
  2150. if (!AT(STRING))
  2151. PARSE_ERROR("expected string");
  2152. token_t *text = tokens->data[(*pos)++];
  2153. n = NODET(INCLUDE, text);
  2154. } else if (MATCH(MACRO)) {
  2155. if (!AT(NAME))
  2156. PARSE_ERROR("expected identifier");
  2157. char *name = ((token_t *)tokens->data[(*pos)++])->text;
  2158. EXPECT(LPAR, "(");
  2159. int variable = 0;
  2160. list_t *params = list_new();
  2161. if (!AT(RPAR)) {
  2162. if (MATCH(STAR))
  2163. variable = 1;
  2164. else
  2165. do {
  2166. if (!AT(NAME))
  2167. PARSE_ERROR("expected identifier");
  2168. list_push(params, tokens->data[(*pos)++]);
  2169. } while (MATCH(COMMA));
  2170. }
  2171. EXPECT(RPAR, ")");
  2172. list_t *body = list_new();
  2173. if (MATCH(COLON) || !AT(LCB))
  2174. list_push(body, parse_mstmt(tokens, pos));
  2175. else {
  2176. EXPECT(LCB, "{");
  2177. while (!AT(EOF) && !AT(RCB))
  2178. list_push(body, parse_mstmt(tokens, pos));
  2179. EXPECT(RCB, "}");
  2180. }
  2181. list_t *ms = macros_get(name);
  2182. if (!ms) {
  2183. ms = list_new();
  2184. table_set(list_index(MACROS, -1), name, ms);
  2185. }
  2186. macro_t *m = malloc_checked(sizeof(macro_t));
  2187. m->name = name;
  2188. m->params = params;
  2189. m->body = body;
  2190. m->variable = variable;
  2191. list_push(ms, m);
  2192. } else {
  2193. n = parse_stmt_c(tokens, pos);
  2194. flag = 1;
  2195. }
  2196. MATCH(SEMI);
  2197. if (n)
  2198. list_push(stmts, n);
  2199. }
  2200. return NODEL(TOPLEVEL, stmts);
  2201. }
  2202. node_t *parse(char *source) {
  2203. size_t pos = 0;
  2204. return parse_program(tokenize(source), &pos);
  2205. }
  2206. #define NEWGID() size_t gid = GID++
  2207. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  2208. #define BINOP(s) \
  2209. { \
  2210. EMIT("qi_" s "(state, "); \
  2211. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); \
  2212. EMIT(", "); \
  2213. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b); \
  2214. EMIT(")"); \
  2215. }
  2216. #define UNOP(s) \
  2217. { \
  2218. EMIT("qi_" s "(state, "); \
  2219. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); \
  2220. EMIT(")"); \
  2221. }
  2222. #define ASSIGNIN(buf, lhs, rhs, prefix) \
  2223. { \
  2224. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) { \
  2225. buffer_fmt(buf, "qi_set(state, " #prefix ", \"%s\", ", (lhs)->t->text); \
  2226. rhs; \
  2227. buffer_fmt(buf, ")"); \
  2228. } else if ((lhs)->tag == N_INDEX) { \
  2229. buffer_fmt(buf, "qi_index_set(state, " #prefix ", "); \
  2230. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a); \
  2231. buffer_fmt(buf, ", "); \
  2232. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->b); \
  2233. buffer_fmt(buf, ", "); \
  2234. rhs; \
  2235. buffer_fmt(buf, ")"); \
  2236. } else if ((lhs)->tag == N_MEMBER) { \
  2237. buffer_fmt(buf, "qi_index_set(state, " #prefix ", "); \
  2238. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a); \
  2239. buffer_fmt(buf, ", qi_make_string(state, \"%s\"), ", (lhs)->t->text); \
  2240. rhs; \
  2241. buffer_fmt(buf, ")"); \
  2242. } else \
  2243. COMPILE_ERROR("illegal assignment left-hand side"); \
  2244. }
  2245. #define ASSIGN(lhs, rhs) ASSIGNIN(buf, lhs, rhs, false)
  2246. #define COMPASSIGN(lhs, s, rhs) \
  2247. { \
  2248. ASSIGN(node->a, { \
  2249. EMIT("qi_%s(state, ", s); \
  2250. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)); \
  2251. EMIT(", "); \
  2252. rhs; \
  2253. EMIT(")"); \
  2254. }); \
  2255. }
  2256. #define COMPASSIGNP(lhs, s, rhs) \
  2257. { \
  2258. ASSIGNIN(buf, node->a, { \
  2259. EMIT("qi_%s(state, ", s); \
  2260. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)); \
  2261. EMIT(", "); \
  2262. rhs; \
  2263. EMIT(")"); \
  2264. }, true); \
  2265. }
  2266. #define COMPILE_ERROR(fmt, ...) \
  2267. { \
  2268. format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, \
  2269. ##__VA_ARGS__); \
  2270. exit(1); \
  2271. }
  2272. #define COMPILE_NOTE(fmt, ...) \
  2273. { \
  2274. format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, \
  2275. ##__VA_ARGS__); \
  2276. }
  2277. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2278. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2279. node_t *node);
  2280. char *tempvar() {
  2281. NEWGID();
  2282. char *s = malloc_checked(sizeof(char) * (64 + strlen(PREFIX)));
  2283. snprintf(s, 64 + strlen(PREFIX), "__%s%zu", PREFIX, gid);
  2284. return s;
  2285. }
  2286. void compile_list(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2287. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2288. list_t *seq) {
  2289. if (!seq || seq->length < 1) {
  2290. EMIT("NULL");
  2291. return;
  2292. }
  2293. int has_star = 0;
  2294. for (size_t i = 0; i < seq->length; i++)
  2295. if (((node_t *)seq->data[i])->tag == N_STAR) {
  2296. has_star = 1;
  2297. break;
  2298. }
  2299. buffer_t *tbuf = buffer_new();
  2300. NEWGID();
  2301. buffer_fmt(tbuf, "inline static qi_list_t *__%s%d(qi_state_t *state) {\n",
  2302. PREFIX, gid);
  2303. if (has_star)
  2304. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  2305. else
  2306. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make_n(%d);\n", seq->length);
  2307. for (size_t i = 0; i < seq->length; i++) {
  2308. node_t *node = seq->data[i];
  2309. if (!has_star) {
  2310. buffer_fmt(tbuf, "qi_list_data(list, %d) = ", i);
  2311. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  2312. buffer_fmt(tbuf, ";\n");
  2313. continue;
  2314. }
  2315. if (node->tag == N_STAR) {
  2316. char *varname = tempvar();
  2317. buffer_fmt(tbuf, "qi_value_t *%s = qi_iter(state, ", varname);
  2318. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2319. buffer_fmt(tbuf, ");\n");
  2320. buffer_fmt(tbuf,
  2321. "for (qi_size_t i = 0; i < %s->value.list->length; i++)\n",
  2322. varname);
  2323. buffer_fmt(tbuf,
  2324. "qi_list_push(list, qi_index(state, %s, qi_make_number(state, "
  2325. "i)));\n",
  2326. varname);
  2327. } else {
  2328. buffer_fmt(tbuf, "qi_list_push(list, ");
  2329. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  2330. buffer_fmt(tbuf, ");\n");
  2331. }
  2332. }
  2333. buffer_fmt(tbuf, "return list;\n");
  2334. buffer_fmt(tbuf, "}\n");
  2335. buffer_appendb(gbuf, tbuf);
  2336. EMIT("__%s%d(state)", PREFIX, gid);
  2337. }
  2338. void compile_table(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2339. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2340. table_t *table) {
  2341. if (!table || table->used < 1) {
  2342. EMIT("NULL");
  2343. return;
  2344. }
  2345. buffer_t *tbuf = buffer_new();
  2346. NEWGID();
  2347. buffer_fmt(tbuf, "inline static qi_table_t *__%s%d(qi_state_t *state) {\n",
  2348. PREFIX, gid);
  2349. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  2350. table_iterate(table, {
  2351. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  2352. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, entry.value);
  2353. buffer_fmt(tbuf, ");\n");
  2354. });
  2355. buffer_fmt(tbuf, "return table;\n");
  2356. buffer_fmt(tbuf, "}\n");
  2357. buffer_appendb(gbuf, tbuf);
  2358. EMIT("__%s%d(state)", PREFIX, gid);
  2359. }
  2360. #define CTXPUSH(s) list_push(ctx, (s))
  2361. #define CTXPOP() list_pop(ctx)
  2362. int in_context(list_t *ctx, char *s) {
  2363. if (!ctx->length)
  2364. return 0;
  2365. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2366. if (strcmp(ctx->data[i], "gap") == 0)
  2367. break;
  2368. else if (strcmp(ctx->data[i], s) == 0)
  2369. return 1;
  2370. }
  2371. return 0;
  2372. }
  2373. int in_switch(list_t *ctx) {
  2374. if (!ctx->length)
  2375. return 0;
  2376. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2377. if (strcmp(ctx->data[i], "gap") == 0 || strcmp(ctx->data[i], "for") == 0)
  2378. break;
  2379. else if (strcmp(ctx->data[i], "switch") == 0)
  2380. return 1;
  2381. }
  2382. return 0;
  2383. }
  2384. size_t count_ctxs(list_t *ctx, char *s) {
  2385. if (!ctx->length)
  2386. return 0;
  2387. size_t k = 0;
  2388. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2389. if (strcmp(ctx->data[i], "gap") == 0)
  2390. break;
  2391. else if (strcmp(ctx->data[i], s) == 0)
  2392. k++;
  2393. }
  2394. return k;
  2395. }
  2396. list_t *CONSTANTS;
  2397. #define INCTX(s) (in_context(ctx, (s)))
  2398. #define SCOPESK (count_ctxs(ctx, "scope"))
  2399. #define TRAPSK (count_ctxs(ctx, "trap"))
  2400. #define LPUSH(i) stack_push(lstk, (i))
  2401. #define LPOP() stack_pop(lstk)
  2402. #define LID (lstk->data[lstk->length - 1])
  2403. #define SPUSH(i) stack_push(sstk, (i))
  2404. #define SPOP() stack_pop(sstk)
  2405. #define SID (sstk->data[sstk->length - 1])
  2406. #define LBPUSH() list_push(lbl, table_new())
  2407. #define LBPOP() list_pop(lbl)
  2408. size_t insert_debug(node_t *node) {
  2409. size_t line;
  2410. (void)traverse(GETSRC(node->fi), node->pos, &line, NULL);
  2411. buffer_t *tbuf = buffer_new();
  2412. buffer_fmt(tbuf, "File \"%s\", line %d", GETFNAME(node->fi), line);
  2413. if (FUNCNAMES->length)
  2414. buffer_fmt(tbuf, ", in %s", list_index(FUNCNAMES, -1));
  2415. list_push(DEBUGDATA, buffer_read(tbuf));
  2416. return DEBUGDATA->length - 1;
  2417. }
  2418. void emit_debug(buffer_t *buf, node_t *node) {
  2419. buffer_fmt(buf, "state->_debug_data = __debugData[%d];\n",
  2420. insert_debug(node));
  2421. }
  2422. void compile_func(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2423. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2424. node_t *node, char *name) {
  2425. NEWGID();
  2426. char *funname = name ? name : node->t ? node->t->text : "<anon>";
  2427. buffer_t *tbuf = buffer_new();
  2428. buffer_fmt(tbuf,
  2429. "qi_value_t *__%s%d(qi_state_t *state, qi_size_t pargc, qi_list_t "
  2430. "*pargs) {\n",
  2431. PREFIX, gid);
  2432. LBPUSH();
  2433. CTXPUSH("gap");
  2434. CTXPUSH("func");
  2435. list_push(CONSTANTS, table_new());
  2436. list_push(MACROS, table_new());
  2437. list_push(FUNCNAMES, funname);
  2438. if (DEBUG)
  2439. emit_debug(tbuf, node);
  2440. size_t optargc = 0;
  2441. if (node->h) {
  2442. table_iterate(node->h, {
  2443. list_t *pair = entry.value;
  2444. size_t argc = *(size_t *)pair->data[0];
  2445. if (pair->data[1]) {
  2446. optargc++;
  2447. buffer_fmt(
  2448. tbuf,
  2449. "qi_decl(state, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ",
  2450. entry.key, argc + 1, argc);
  2451. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  2452. buffer_fmt(tbuf, ");\n");
  2453. } else
  2454. buffer_fmt(tbuf, "qi_decl(state, \"%s\", qi_list_index(pargs, %d));\n",
  2455. entry.key, argc);
  2456. argc++;
  2457. });
  2458. }
  2459. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl,
  2460. node->a);
  2461. list_pop(FUNCNAMES);
  2462. list_pop(MACROS);
  2463. list_pop(CONSTANTS);
  2464. CTXPOP();
  2465. CTXPOP();
  2466. LBPOP();
  2467. buffer_fmt(tbuf, "return state->nil;\n");
  2468. buffer_fmt(tbuf, "}\n");
  2469. buffer_appendb(gbuf, tbuf);
  2470. tbuf = buffer_new();
  2471. buffer_fmt(tbuf, "qi_make_function(state, \"%s\", %d, __%s%d, ", funname,
  2472. !node->h ? 0 : (node->h->used - optargc), PREFIX, gid);
  2473. compile_table(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->h2);
  2474. buffer_fmt(tbuf, ")");
  2475. if (node->tag == N_FUNCEXPR) {
  2476. buffer_appendb(buf, tbuf);
  2477. return;
  2478. }
  2479. EMIT("qi_set(state, false, \"%s\", ", node->t->text);
  2480. buffer_appendb(buf, tbuf);
  2481. EMIT(");");
  2482. }
  2483. int const_set(char *name, node_t *val) {
  2484. table_t *table = list_index(CONSTANTS, -1);
  2485. if (table_get(table, name))
  2486. return 0;
  2487. table_set(table, name, val);
  2488. return 1;
  2489. }
  2490. node_t *const_get(char *name) {
  2491. node_t *val = NULL;
  2492. for (ssize_t i = CONSTANTS->length - 1; i >= 0; i--)
  2493. if ((val = table_get(CONSTANTS->data[i], name)))
  2494. break;
  2495. return val;
  2496. }
  2497. void compile_block(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2498. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2499. list_t *block) {
  2500. for (size_t i = 0; i < block->length; i++) {
  2501. node_t *node = block->data[i];
  2502. if (node->tag == N_CONST) {
  2503. table_iterate(node->h, {
  2504. char *name = entry.key;
  2505. if (!const_set(name, entry.value))
  2506. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  2507. });
  2508. } else if (node->tag == N_FUNCDEF) {
  2509. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  2510. EMIT("\n");
  2511. } else if (node->tag == N_CLASS) {
  2512. NEWGID();
  2513. char *name = node->t->text;
  2514. list_t *supers = list_index(node->l, 0);
  2515. list_t *triples = list_index(node->l, 1);
  2516. buffer_t *tbuf = buffer_new();
  2517. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX,
  2518. gid);
  2519. buffer_fmt(tbuf, "qi_list_t *supers = qi_list_make_n(%d);\n",
  2520. !supers ? 0 : supers->length);
  2521. if (supers)
  2522. for (size_t i = 0; i < supers->length; i++) {
  2523. token_t *t = supers->data[i];
  2524. buffer_fmt(tbuf,
  2525. "qi_list_data(supers, %d) = qi_get(state, \"%s\");\n", i,
  2526. t->text);
  2527. }
  2528. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  2529. buffer_fmt(tbuf, "qi_table_t *metatable = qi_table_make();\n");
  2530. buffer_fmt(tbuf, "qi_table_t *statictable = qi_table_make();\n");
  2531. for (size_t i = 0; i < triples->length; i++) {
  2532. list_t *triple = triples->data[i];
  2533. token_t *t = triple->data[0];
  2534. int flag = *(int *)triple->data[1];
  2535. if (flag == 0) {
  2536. buffer_fmt(tbuf, "qi_table_set(metatable, \"%s\", ", t->text);
  2537. if (((node_t *)triple->data[2])->tag == N_FUNCEXPR) {
  2538. buffer_t *methodname = buffer_new();
  2539. buffer_fmt(methodname, "%s.%s", name, t->text);
  2540. compile_func(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  2541. triple->data[2], buffer_read(methodname));
  2542. } else
  2543. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  2544. triple->data[2]);
  2545. } else {
  2546. buffer_fmt(tbuf, "qi_table_set(%s, \"%s\", ",
  2547. flag == 1 ? "table" : "statictable", t->text);
  2548. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2]);
  2549. }
  2550. buffer_fmt(tbuf, ");\n");
  2551. }
  2552. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(5);\n");
  2553. buffer_fmt(tbuf,
  2554. "qi_list_data(pargs, 0) = qi_make_string(state, \"%s\");\n",
  2555. name);
  2556. buffer_fmt(tbuf,
  2557. "qi_list_data(pargs, 1) = qi_make_list(state, supers);\n");
  2558. buffer_fmt(tbuf,
  2559. "qi_list_data(pargs, 2) = qi_make_table(state, table);\n");
  2560. buffer_fmt(tbuf,
  2561. "qi_list_data(pargs, 3) = qi_make_table(state, metatable);\n");
  2562. buffer_fmt(
  2563. tbuf,
  2564. "qi_list_data(pargs, 4) = qi_make_table(state, statictable);\n");
  2565. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, "
  2566. "\"__class_wrapper\"), pargs);\n");
  2567. buffer_fmt(tbuf, "}\n");
  2568. buffer_appendb(gbuf, tbuf);
  2569. EMIT("qi_set(state, false, \"%s\", __%s%d(state));", name, PREFIX, gid);
  2570. } else if (node->tag == N_LABEL) {
  2571. char *label = node->t->text;
  2572. if (table_get(list_index(lbl, -1), label))
  2573. COMPILE_ERROR("duplicated label: '%s'", label);
  2574. NEWGID();
  2575. size_t *n = malloc_checked(sizeof(size_t));
  2576. memcpy(n, &gid, sizeof(size_t));
  2577. table_set(list_index(lbl, -1), label, n);
  2578. }
  2579. }
  2580. for (size_t i = 0; i < block->length; i++) {
  2581. node_t *n = block->data[i];
  2582. if (n->tag == N_CONST || n->tag == N_FUNCDEF || n->tag == N_CLASS ||
  2583. n->tag == N_PASS)
  2584. continue;
  2585. if (DEBUG)
  2586. emit_debug(buf, n);
  2587. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  2588. EMIT("\n");
  2589. }
  2590. }
  2591. const char *STD[][2] = {
  2592. {"utf8", "func utf8_chrlen(s) {\n"
  2593. " s = bytes(s)\n"
  2594. " var z = len(s)\n"
  2595. " if z < 2\n"
  2596. " return z\n"
  2597. " var l = 1\n"
  2598. " for var i = 1; i < z && (s[i] & 0xc0) == 0x80; i++\n"
  2599. " l++\n"
  2600. " return l\n"
  2601. "}\n"
  2602. "func utf8_decode(s) {\n"
  2603. " s = bytes(s)\n"
  2604. " var l = utf8_chrlen(s)\n"
  2605. " if !l\n"
  2606. " throw \"malformed sequence\"\n"
  2607. " var c = (s[0] & ((1 << (8 - l)) - 1)) << (l - 1) * 6\n"
  2608. " for var i = 1; i < l; i++\n"
  2609. " c |= (s[i] & 0x3f) << (l - i - 1) * 6\n"
  2610. " return (c, l)\n"
  2611. "}\n"
  2612. "func utf8_encode(c) {\n"
  2613. " if c <= 0x7f\n"
  2614. " return bytes([c & 0xFF])\n"
  2615. " elif c >= 0x80 && c <= 0x7ff\n"
  2616. " return bytes([0xC0 | ((c >> 6) & 0x1f), 0x80 | (c & 0x3f)])\n"
  2617. " elif c >= 0x800 && c <= 0xfff\n"
  2618. " return bytes([0xe0 | ((c >> 12) & 0xf), 0x80 | ((c >> 6) & "
  2619. "0x3f), 0x80 | (c & 0x3f)])\n"
  2620. " elif c >= 0x10000 && c <= 0x10ffff\n"
  2621. " return bytes([0xf0 | ((c >> 18) & 0x7), 0x80 | ((c >> 12) & "
  2622. "0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  2623. " throw \"malformed codepoint\"\n"
  2624. "}\n"
  2625. "class ustr {\n"
  2626. " _ucs = nil\n"
  2627. " constructor (this, s=\"\") {\n"
  2628. " if type(s) == \"list\" && all(map(func (x): type(x) == \"number\", s)) {\n"
  2629. " this._ucs = s\n"
  2630. " return\n"
  2631. " }\n"
  2632. " s = str(s)\n"
  2633. " this._ucs = []\n"
  2634. " for var i = 0; i < len(s) {\n"
  2635. " let [c, l] = utf8_decode(slice(s, i))\n"
  2636. " this._ucs.push(c)\n"
  2637. " i += l\n"
  2638. " }\n"
  2639. " }\n"
  2640. " nth (this, i): this._ucs[i]\n"
  2641. " __type (this): \"ustr\"\n"
  2642. " __str (this) {\n"
  2643. " var s = \"\"\n"
  2644. " for var uc of this._ucs\n"
  2645. " s += str(utf8_encode(uc))\n"
  2646. " return s\n"
  2647. " }\n"
  2648. " __len (this): len(this._ucs)\n"
  2649. " __index (this, i): ustr([this._ucs[i]])\n"
  2650. " __index_set (this): throw\n"
  2651. " __iter (this): this._ucs\n"
  2652. " __list (this): list_copy(this._ucs)\n"
  2653. " __add (this, other) {\n"
  2654. " if type(other) != \"ustr\"\n"
  2655. " throw\n"
  2656. " return ustr(this._ucs + other._ucs)\n"
  2657. " }\n"
  2658. " __equals (this, other) {\n"
  2659. " if type(other) != \"ustr\"\n"
  2660. " return false\n"
  2661. " return this._ucs == other._ucs\n"
  2662. " }\n"
  2663. "}\n"},
  2664. {"thread",
  2665. "include `pthread.h`\n"
  2666. "func thread_create(fn, args=[]) {\n"
  2667. " if type(fn) != \"function\"\n"
  2668. " throw \"expected first argument to be: function, but got: \" + "
  2669. "type(fn)\n"
  2670. " if type(args) != \"list\"\n"
  2671. " throw \"expected second argument to be: list, but got: \" + "
  2672. "type(args)\n"
  2673. " inline `qi_value_t *args = qi_get(state, \"args\")`\n"
  2674. " inline `qi_list_t *list`\n"
  2675. " inline `LOCKED(args, {list = qi_list_copy(args->value.list);})`\n"
  2676. " inline `void *td = qi_thread_create(state, qi_get(state, \"fn\"), "
  2677. "list)`\n"
  2678. " inline `qi_decl(state, \"td\", qi_make_data(state, 'T', td))`\n"
  2679. " return Object({\n"
  2680. " __str: func (this): \"<Thread>\",\n"
  2681. " _td: td,\n"
  2682. " joined: false,\n"
  2683. " join: func (this) {\n"
  2684. " if this.joined\n"
  2685. " return\n"
  2686. " var td = this._td\n"
  2687. " inline `qi_value_t *ret = qi_thread_join(state, qi_get_data(state, "
  2688. "'T', qi_get(state, \"td\")))`\n"
  2689. " this.joined = true\n"
  2690. " inline `return ret`\n"
  2691. " }\n"
  2692. " })\n"
  2693. "}\n"
  2694. "func Thread(fn, args=[]): Object({\n"
  2695. " __str: func (this) use (fn, args): format(\"<Thread _ _>\", fn, "
  2696. "args),\n"
  2697. " _thread: nil,\n"
  2698. " start: func (this) use (fn, args) {\n"
  2699. " if this._thread !is nil\n"
  2700. " return\n"
  2701. " this._thread = thread_create(fn, args)\n"
  2702. " return this\n"
  2703. " },\n"
  2704. " join: func (this) {\n"
  2705. " if this._thread !is nil\n"
  2706. " return this._thread.join()\n"
  2707. " },\n"
  2708. " is_joined: func (this): this._thread.joined\n"
  2709. "})\n"
  2710. "func Mutex() {\n"
  2711. " inline `void *mutex = qi_mutex_create()`\n"
  2712. " inline `if (!mutex) qi_throw_format(state, \"mutex init failed\")`\n"
  2713. " inline `qi_decl(state, \"mutex\", qi_make_data(state, 'M', mutex))`\n"
  2714. " return Object({\n"
  2715. " __fin: func (this) {\n"
  2716. " mutex = this._mutex\n"
  2717. " this._mutex = nil\n"
  2718. " inline `qi_mutex_destroy(qi_get_data(state, 'M', qi_get(state, "
  2719. "\"mutex\")))`\n"
  2720. " },\n"
  2721. " __str: func (this): \"<Mutex>\",\n"
  2722. " _mutex: mutex,\n"
  2723. " lock: func (this) {\n"
  2724. " var mutex = this._mutex\n"
  2725. " inline `qi_mutex_lock(qi_get_data(state, 'M', qi_get(state, "
  2726. "\"mutex\")))`\n"
  2727. " },\n"
  2728. " trylock: func (this) {\n"
  2729. " var mutex = this._mutex\n"
  2730. " inline `return qi_make_boolean(state, "
  2731. "qi_mutex_trylock(qi_get_data(state, 'M', qi_get(state, \"mutex\"))))`\n"
  2732. " },\n"
  2733. " unlock: func (this) {\n"
  2734. " var mutex = this._mutex\n"
  2735. " inline `qi_mutex_unlock(qi_get_data(state, 'M', qi_get(state, "
  2736. "\"mutex\")))`\n"
  2737. " }\n"
  2738. " })\n"
  2739. "}\n"
  2740. "func Cond() {\n"
  2741. " inline `void *cond = qi_cond_create()`\n"
  2742. " inline `if (!cond) qi_throw_format(state, \"cond init failed\")`\n"
  2743. " inline `qi_decl(state, \"cond\", qi_make_data(state, 'C', cond))`\n"
  2744. " return Object({\n"
  2745. " __fin: func (this) {\n"
  2746. " cond = this._cond\n"
  2747. " this._cond = nil\n"
  2748. " inline `qi_cond_destroy(qi_get_data(state, 'C', qi_get(state, "
  2749. "\"cond\")))`\n"
  2750. " },\n"
  2751. " __str: func (this): \"<Cond>\",\n"
  2752. " _cond: cond,\n"
  2753. " wait: func (this, mutex) {\n"
  2754. " var cond = this._cond\n"
  2755. " mutex = mutex._mutex\n"
  2756. " inline `qi_cond_wait(qi_get_data(state, 'C', qi_get(state, "
  2757. "\"cond\")), qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2758. " },\n"
  2759. " signal: func (this) {\n"
  2760. " var cond = this._cond\n"
  2761. " inline `qi_cond_signal(qi_get_data(state, 'C', qi_get(state, "
  2762. "\"cond\")))`\n"
  2763. " },\n"
  2764. " broadcast: func (this) {\n"
  2765. " var cond = this._cond\n"
  2766. " inline `qi_cond_broadcast(qi_get_data(state, 'C', qi_get(state, "
  2767. "\"cond\")))`\n"
  2768. " }\n"
  2769. " })\n"
  2770. "}\n"
  2771. "func thread_exit(ret=nil)\n"
  2772. " inline `qi_thread_exit(state, qi_get(state, \"ret\"))`\n"
  2773. "func is_main_thread()\n"
  2774. " inline `return qi_make_boolean(state, qi_thread_main())`\n"},
  2775. {"os",
  2776. "header `#ifdef _WIN32`\n"
  2777. "include `Windows.h`\n"
  2778. "header `#endif`\n"
  2779. "func getenv(n) {\n"
  2780. " if type(n) != \"string\"\n"
  2781. " throw \"expected first argument to be: string, but got: \" + "
  2782. "type(n)\n"
  2783. " inline `char *value = getenv(qi_get(state, \"n\")->value.string)`\n"
  2784. " inline `return value? qi_make_string_copy(state, value): state->nil`\n"
  2785. "}\n"
  2786. "func setenv(n, v) {\n"
  2787. " if type(n) != \"string\"\n"
  2788. " throw \"expected first argument to be: string, but got: \" + "
  2789. "type(n)\n"
  2790. " v = str(v)\n"
  2791. " inline \"#ifdef _WIN32\"\n"
  2792. " var s = n + \"=\" + v\n"
  2793. " inline `_putenv(qi_get(state, \"s\")->value.string)`\n"
  2794. " inline \"#else\"\n"
  2795. " inline `setenv(qi_get(state, \"n\")->value.string, qi_get(state, "
  2796. "\"v\")->value.string, 1)`\n"
  2797. " inline \"#endif\"\n"
  2798. "}\n"
  2799. "func exit(c) {\n"
  2800. " if type(c) != \"number\"\n"
  2801. " throw \"expected first argument to be: number, but got: \" + type(c)\n"
  2802. " inline `qi_exit(state, qi_get(state, \"c\")->value.number)`\n"
  2803. "}\n"
  2804. "func die(msg, c=1) {\n"
  2805. " fputs(STDERR, str(msg) + \"\\n\")\n"
  2806. " exit(c)\n"
  2807. "}\n"},
  2808. {"string", "let STR_LETTERS = "
  2809. "\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2810. "let STR_ASCII_LC = \"abcdefghijklmnopqrstuvwxyz\"\n"
  2811. "let STR_ASCII_UC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2812. "let STR_DIGITS = \"0123456789\"\n"
  2813. "let STR_WS = \" \\t\\n\\r\\x0b\\x0c\"\n"
  2814. "let STR_PUNCTS = \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"\n"
  2815. "func is_char(c): return type(c) == \"string\" && len(c) == 1\n"
  2816. "func isalpha(c): return (c >= 'a' && c <= 'z') || (c >= 'A' && "
  2817. "c <= 'Z')\n"
  2818. "func isdigit(c): return c >= '0' && c <= '9'\n"
  2819. "func ispunct(c): return c in STR_PUNCTS\n"
  2820. "func isws(c): return c in STR_WS\n"},
  2821. {"time",
  2822. "include `time.h`\n"
  2823. "include `errno.h`\n"
  2824. "header `#ifdef _WIN32`\n"
  2825. "include `Windows.h`\n"
  2826. "header `#endif`\n"
  2827. "func time() {\n"
  2828. " inline `unsigned long long ts = time(NULL)`\n"
  2829. " inline `return qi_make_number(state, ts)`\n"
  2830. "}\n"
  2831. "func strftime(f, t=time()) {\n"
  2832. " if type(f) != \"string\"\n"
  2833. " throw \"expected first argument to be: string, but got: \" + "
  2834. "type(f)\n"
  2835. " if type(t) != \"number\"\n"
  2836. " throw \"expected second argument to be: number, but got: \" + "
  2837. "type(t)\n"
  2838. " inline `time_t ts = qi_get(state, \"t\")->value.number`\n"
  2839. " inline `struct tm lt`\n"
  2840. " inline `lt = *localtime(&ts)`\n"
  2841. " inline `char buffer[512]`\n"
  2842. " inline `strftime(buffer, sizeof(buffer), qi_get(state, "
  2843. "\"f\")->value.string, &lt)`\n"
  2844. " inline `return qi_make_string_copy(state, buffer)`\n"
  2845. "}\n"
  2846. "func usleep(t) {\n"
  2847. " if type(t) != \"number\"\n"
  2848. " throw \"expected first argument to be: number, but got: \" + "
  2849. "type(t)\n"
  2850. " \n"
  2851. " inline `#ifdef _WIN32`\n"
  2852. " inline `Sleep((unsigned long)(qi_get(state, \"t\")->value.number))`\n"
  2853. " inline `#else`\n"
  2854. " inline `unsigned long ms = (unsigned long)(qi_get(state, "
  2855. "\"t\")->value.number)`\n"
  2856. " inline `struct timespec ts`\n"
  2857. " inline `ts.tv_sec = ms / 1000`\n"
  2858. " inline `ts.tv_nsec = (ms % 1000) * 1000000`\n"
  2859. " inline `struct timespec r`\n"
  2860. " inline `while (nanosleep(&ts, &r) < 0) if (errno == EINTR) ts = r; "
  2861. "else break`\n"
  2862. " inline `#endif`\n"
  2863. "}\n"
  2864. "func sleep(t)\n"
  2865. " usleep(t * 1000)\n"},
  2866. {"random",
  2867. "func rand() {\n"
  2868. " inline `return qi_make_number(state, rand())`\n"
  2869. "}\n"
  2870. "func random_int(min, max): return rand() % (max + 1 - min) + min\n"
  2871. "func random_choice(l, k=1) {\n"
  2872. " l = list_copy(list(l))\n"
  2873. " var r = []\n"
  2874. " for var i = 0; i < k; i++\n"
  2875. " list_push(r, list_pop_at(l, random_int(0, len(l)-1)))\n"
  2876. " return r\n"
  2877. "}\n"
  2878. "func random_pick(l, k=1) {\n"
  2879. " var r = []\n"
  2880. " for var i = 0; i < k; i++\n"
  2881. " list_push(r, l[random_int(0, len(l)-1)])\n"
  2882. " return r\n"
  2883. "}\n"
  2884. "inline `srand(time(NULL))`\n"},
  2885. {"math", NULL},
  2886. {NULL, NULL}};
  2887. const struct {
  2888. const char *name;
  2889. const char *fname;
  2890. int arity;
  2891. } MATHFUNCS[] = {{"ceil", NULL, 1}, {"floor", NULL, 1}, {"trunc", NULL, 1},
  2892. {"round", NULL, 1}, {"abs", "fabs", 1}, {"exp", NULL, 1},
  2893. {"sqrt", NULL, 1}, {"sinh", NULL, 1}, {"cosh", NULL, 1},
  2894. {"tanh", NULL, 1}, {"asinh", NULL, 1}, {"acosh", NULL, 1},
  2895. {"atanh", NULL, 1}, {"sin", NULL, 1}, {"cos", NULL, 1},
  2896. {"tan", NULL, 1}, {"asin", NULL, 1}, {"acos", NULL, 1},
  2897. {"atan", NULL, 1}, {"atan2", NULL, 2}, {"hypot", NULL, 2},
  2898. {NULL, 0}};
  2899. void genmathlib(void) {
  2900. buffer_t *buffer = buffer_new();
  2901. buffer_appends(
  2902. buffer,
  2903. "let Math = {\"tau\": 6.283185307179586, \"pi\": 3.141592653589793, "
  2904. "\"e\": 2.718281828459045, \"inf\": INFINITY, \"nan\": NAN, ");
  2905. for (size_t i = 0; MATHFUNCS[i].name; i++) {
  2906. if (MATHFUNCS[i].arity == 0)
  2907. buffer_fmt(
  2908. buffer,
  2909. "\"%s\": func () { inline `return qi_make_number(state, %s())` }",
  2910. MATHFUNCS[i].name,
  2911. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  2912. else if (MATHFUNCS[i].arity == 1)
  2913. buffer_fmt(
  2914. buffer,
  2915. "\"%s\": func (x) { if type(x) != \"number\" { throw \"expected "
  2916. "first argument to be: number, but got: \" + type(x) } inline "
  2917. "`double n = %s(qi_get(state, \"x\")->value.number)`; inline `return "
  2918. "qi_make_number(state, n)` }",
  2919. MATHFUNCS[i].name,
  2920. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  2921. else
  2922. buffer_fmt(
  2923. buffer,
  2924. "\"%s\": func (x, y) { if type(x) != \"number\" { throw \"expected "
  2925. "first argument to be: number, but got: \" + type(x) } if type(y) != "
  2926. "\"number\" { throw \"expected second argument to be: number, but "
  2927. "got: \" + type(y) } inline `double n = %s(qi_get(state, "
  2928. "\"x\")->value.number, qi_get(state, \"y\")->value.number)`; inline "
  2929. "`return qi_make_number(state, n)` }",
  2930. MATHFUNCS[i].name,
  2931. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  2932. if (MATHFUNCS[i + 1].name)
  2933. buffer_append(buffer, ',');
  2934. }
  2935. buffer_append(buffer, '}');
  2936. size_t i;
  2937. for (i = 0; strcmp(STD[i][0], "math") != 0; i++)
  2938. ;
  2939. STD[i][1] = buffer_read(buffer);
  2940. }
  2941. char *unescape(char *s) {
  2942. buffer_t *buf = buffer_new();
  2943. for (size_t i = 0; i < strlen(s); i++) {
  2944. char c = s[i];
  2945. if (c == '\\') {
  2946. char nc = s[i + 1];
  2947. if (!nc)
  2948. continue;
  2949. switch (nc) {
  2950. case 'n':
  2951. buffer_append(buf, '\n');
  2952. break;
  2953. default:
  2954. buffer_append(buf, nc);
  2955. break;
  2956. }
  2957. i++;
  2958. } else
  2959. buffer_append(buf, c);
  2960. }
  2961. return buffer_read(buf);
  2962. }
  2963. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  2964. table_t *ltab, int_stack_t *lstk, int_stack_t *sstk,
  2965. list_t *lbl);
  2966. int require_once(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2967. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  2968. char *path) {
  2969. char *source = NULL;
  2970. for (size_t i = 0; STD[i][0]; i++) {
  2971. if (strcmp(path, STD[i][0]) == 0) {
  2972. source = (char *)STD[i][1];
  2973. break;
  2974. }
  2975. }
  2976. if (is_required(path))
  2977. return 1;
  2978. if (!source) {
  2979. FILE *fd = fopen(path, "rb");
  2980. if (!fd)
  2981. return -1;
  2982. buffer_t *fbuf = buffer_new();
  2983. for (;;) {
  2984. char line[512];
  2985. if (!fgets(line, sizeof(line), fd))
  2986. break;
  2987. buffer_appends(fbuf, line);
  2988. }
  2989. source = buffer_read(fbuf);
  2990. path = realpath(path, NULL);
  2991. }
  2992. list_t *pair = list_new();
  2993. list_push(pair, path);
  2994. list_push(pair, source);
  2995. list_push(FILES, pair);
  2996. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  2997. list_pop(FILES);
  2998. list_push(REQUIRED, path);
  2999. return 0;
  3000. }
  3001. buffer_t *HBUF;
  3002. list_t *MVARS;
  3003. node_t *YES;
  3004. #define IS_EXPR(n) \
  3005. ((n) && ((node_t *)(n))->tag > N_EXPRS_BEGIN && \
  3006. ((node_t *)(n))->tag < N_EXPRS_END)
  3007. #define IS_NUMBER(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_NUMBER)
  3008. #define TO_DOUBLE(n) (strtod((n)->t->text, NULL))
  3009. #define IS_STRING(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_STRING)
  3010. node_t *make_number(double v) {
  3011. char buf[64];
  3012. snprintf(buf, sizeof(buf), "%g", v);
  3013. return nodet(N_LITERAL, token(T_NUMBER, strdup(buf)));
  3014. }
  3015. node_t *mexpr_negate(node_t *a) {
  3016. if (!IS_NUMBER(a))
  3017. return NULL;
  3018. return make_number(-TO_DOUBLE(a));
  3019. }
  3020. node_t *mexpr_add(node_t *a, node_t *b) {
  3021. if (!IS_NUMBER(a))
  3022. return NULL;
  3023. if (!IS_NUMBER(b))
  3024. return NULL;
  3025. return make_number(TO_DOUBLE(a) + TO_DOUBLE(b));
  3026. }
  3027. node_t *mexpr_sub(node_t *a, node_t *b) {
  3028. if (!IS_NUMBER(a))
  3029. return NULL;
  3030. if (!IS_NUMBER(b))
  3031. return NULL;
  3032. return make_number(TO_DOUBLE(a) - TO_DOUBLE(b));
  3033. }
  3034. node_t *mexpr_mul(node_t *a, node_t *b) {
  3035. if (!IS_NUMBER(a))
  3036. return NULL;
  3037. if (!IS_NUMBER(b))
  3038. return NULL;
  3039. return make_number(TO_DOUBLE(a) * TO_DOUBLE(b));
  3040. }
  3041. node_t *mexpr_div(node_t *a, node_t *b) {
  3042. if (!IS_NUMBER(a))
  3043. return NULL;
  3044. if (!IS_NUMBER(b))
  3045. return NULL;
  3046. double x = TO_DOUBLE(b);
  3047. if (x == 0)
  3048. return make_number(0);
  3049. return make_number(TO_DOUBLE(a) * x);
  3050. }
  3051. int mexpr_equals(node_t *a, node_t *b) {
  3052. if (!a && !b)
  3053. return 1;
  3054. if (!a && b)
  3055. return 0;
  3056. if (a && !b)
  3057. return 0;
  3058. if (a->tag != b->tag)
  3059. return 0;
  3060. switch (a->tag) {
  3061. case N_LITERAL:
  3062. return a->t->tag == b->t->tag && strcmp(a->t->text, b->t->text) == 0;
  3063. default:
  3064. break;
  3065. }
  3066. return 0;
  3067. }
  3068. int mexpr_less(node_t *a, node_t *b) {
  3069. if (!IS_NUMBER(a))
  3070. return 0;
  3071. if (!IS_NUMBER(b))
  3072. return 0;
  3073. return TO_DOUBLE(a) < TO_DOUBLE(b);
  3074. }
  3075. int mexpr_greater(node_t *a, node_t *b) {
  3076. if (!IS_NUMBER(a))
  3077. return 0;
  3078. if (!IS_NUMBER(b))
  3079. return 0;
  3080. return TO_DOUBLE(a) > TO_DOUBLE(b);
  3081. }
  3082. node_t *mexpr_eval(node_t *n) {
  3083. if (n)
  3084. switch (n->tag) {
  3085. case N_LITERAL:
  3086. if (n->t->tag == T_NAME) {
  3087. node_t *v = const_get(n->t->text);
  3088. if (v)
  3089. return mexpr_eval(v);
  3090. }
  3091. break;
  3092. case N_UNARY_PLUS:
  3093. return mexpr_eval(n->a);
  3094. break;
  3095. case N_NEGATE: {
  3096. node_t *a = mexpr_eval(n->a);
  3097. return mexpr_negate(a);
  3098. }
  3099. case N_ADD: {
  3100. node_t *a = mexpr_eval(n->a);
  3101. node_t *b = mexpr_eval(n->b);
  3102. if (!IS_NUMBER(a) && IS_NUMBER(b))
  3103. return node2(N_ADD, n->a, b);
  3104. if (IS_NUMBER(a) && !IS_NUMBER(b))
  3105. return node2(N_ADD, a, n->b);
  3106. return mexpr_add(a, b);
  3107. }
  3108. case N_SUB: {
  3109. node_t *a = mexpr_eval(n->a);
  3110. node_t *b = mexpr_eval(n->b);
  3111. if (!IS_NUMBER(a) && IS_NUMBER(b))
  3112. return node2(N_SUB, n->a, b);
  3113. if (IS_NUMBER(a) && !IS_NUMBER(b))
  3114. return node2(N_SUB, a, n->b);
  3115. return mexpr_sub(a, b);
  3116. }
  3117. case N_MUL: {
  3118. node_t *a = mexpr_eval(n->a);
  3119. node_t *b = mexpr_eval(n->b);
  3120. if (!IS_NUMBER(a) && IS_NUMBER(b))
  3121. return node2(N_MUL, n->a, b);
  3122. if (IS_NUMBER(a) && !IS_NUMBER(b))
  3123. return node2(N_MUL, a, n->b);
  3124. return mexpr_mul(a, b);
  3125. }
  3126. case N_DIV: {
  3127. node_t *a = mexpr_eval(n->a);
  3128. node_t *b = mexpr_eval(n->b);
  3129. if (!IS_NUMBER(a) && IS_NUMBER(b))
  3130. return node2(N_DIV, n->a, b);
  3131. if (IS_NUMBER(a) && !IS_NUMBER(b))
  3132. return node2(N_DIV, a, n->b);
  3133. return mexpr_div(a, b);
  3134. }
  3135. case N_IFEXPR: {
  3136. node_t *a = mexpr_eval(n->a);
  3137. if (a)
  3138. return mexpr_eval(n->b);
  3139. return mexpr_eval(n->c);
  3140. }
  3141. case N_TUPLE: case N_LIST: {
  3142. list_t *l = list_new();
  3143. for (size_t i = 0; i < n->l->length; i++) {
  3144. node_t *a = mexpr_eval(n->l->data[i]);
  3145. if (!IS_EXPR(a)) return NULL;
  3146. list_push(l, a);
  3147. }
  3148. return nodel(n->tag, l);
  3149. }
  3150. case N_COMMA:
  3151. return mexpr_eval(list_index(n->l, -1));
  3152. default:
  3153. break;
  3154. }
  3155. return n;
  3156. }
  3157. node_t *mf_isExpr(list_t *t) {
  3158. if (t->length != 1)
  3159. return NULL;
  3160. return IS_EXPR(t->data[0]) ? YES : NULL;
  3161. }
  3162. node_t *mf_isList(list_t *t) {
  3163. if (t->length != 1)
  3164. return NULL;
  3165. node_t *a = t->data[0];
  3166. if (!a)
  3167. return NULL;
  3168. return a->tag == N_LIST ? YES : NULL;
  3169. }
  3170. node_t *mf_newList(list_t *t) {
  3171. for (size_t i = 0; i < t->length; i++)
  3172. if (!IS_EXPR(t->data[i]))
  3173. return NULL;
  3174. return nodel(N_LIST, t);
  3175. }
  3176. node_t *mf_newBlock(list_t *t) {
  3177. for (size_t i = 0; i < t->length; i++)
  3178. if (!t->data[i])
  3179. return NULL;
  3180. else if (IS_EXPR(t->data[i]))
  3181. t->data[i] = node1(N_EXPRSTMT, t->data[i]);
  3182. return nodel(N_PROGRAM, t);
  3183. }
  3184. node_t *mf_newName(list_t *t) {
  3185. if (t->length != 1)
  3186. return NULL;
  3187. node_t *a = t->data[0];
  3188. if (!IS_STRING(a))
  3189. return NULL;
  3190. char *text = a->t->text;
  3191. if (*text != '_' && !isalpha(*text))
  3192. return NULL;
  3193. for (size_t i = 0; i < strlen(text); i++)
  3194. if (text[i] != '_' && !isdigit(text[i]) && !isalpha(text[i]))
  3195. return NULL;
  3196. return nodet(N_LITERAL, token(T_NAME, text));
  3197. }
  3198. node_t *mf_newVar(list_t *t) {
  3199. if (t->length != 1 && t->length != 2)
  3200. return NULL;
  3201. node_t *a = t->data[0];
  3202. if (!a || a->tag != N_LITERAL || a->t->tag != T_NAME)
  3203. return NULL;
  3204. node_t *b = NULL;
  3205. if (t->length == 2) {
  3206. b = t->data[1];
  3207. if (!IS_EXPR(b))
  3208. return NULL;
  3209. }
  3210. table_t *h = table_new();
  3211. table_set(h, a->t->text, b);
  3212. return nodeh(N_VAR, h);
  3213. }
  3214. node_t *mf_len(list_t *t) {
  3215. if (t->length != 1)
  3216. return NULL;
  3217. node_t *a = t->data[0];
  3218. if (!a)
  3219. return NULL;
  3220. if (a->tag == N_LIST || a->tag == N_TUPLE)
  3221. return make_number(a->l->length);
  3222. return NULL;
  3223. }
  3224. node_t *mf_nth(list_t *t) {
  3225. if (t->length != 2)
  3226. return NULL;
  3227. node_t *a = t->data[0];
  3228. if (!a)
  3229. return NULL;
  3230. node_t *b = t->data[1];
  3231. if (!IS_NUMBER(b))
  3232. return NULL;
  3233. if (a->tag == N_LIST || a->tag == N_TUPLE)
  3234. return list_index(a->l, TO_DOUBLE(b));
  3235. return NULL;
  3236. }
  3237. node_t *mf_E(list_t *t) {
  3238. if (t->length != 1)
  3239. return NULL;
  3240. node_t *a = t->data[0];
  3241. return mexpr_eval(a);
  3242. }
  3243. node_t *mf_C(list_t *t) {
  3244. if (t->length != 1)
  3245. return NULL;
  3246. node_t *a = t->data[0];
  3247. if (!IS_STRING(a))
  3248. return NULL;
  3249. return const_get(a->t->text);
  3250. }
  3251. struct {
  3252. char *name;
  3253. node_t *(*handler)(list_t *);
  3254. } METAFUNCS[] = {{"isExpr", mf_isExpr},
  3255. {"isList", mf_isList},
  3256. {"newName", mf_newName},
  3257. {"newList", mf_newList},
  3258. {"newBlock", mf_newBlock},
  3259. {"newVar", mf_newVar},
  3260. {"len", mf_len},
  3261. {"nth", mf_nth},
  3262. {"E", mf_E},
  3263. {"C", mf_C},
  3264. {NULL, NULL}};
  3265. macro_t *find_macro(char *name, size_t argc, int *res) {
  3266. list_t *ms = macros_get(name);
  3267. if (!ms) {
  3268. if (res)
  3269. *res = 1;
  3270. return NULL;
  3271. }
  3272. macro_t *m = NULL;
  3273. for (size_t i = 0; i < ms->length; i++) {
  3274. macro_t *t = ms->data[i];
  3275. if (t->variable || t->params->length == argc) {
  3276. m = t;
  3277. break;
  3278. }
  3279. }
  3280. if (!m) {
  3281. if (res)
  3282. *res = 2;
  3283. return NULL;
  3284. }
  3285. if (res)
  3286. *res = 0;
  3287. return m;
  3288. }
  3289. typedef struct {
  3290. node_t *mvar;
  3291. int code;
  3292. } mvar_expand_err_t;
  3293. node_t *_expand_mvars(node_t *node, int expr, mvar_expand_err_t *err);
  3294. node_t *run_macro(macro_t *macro, list_t *args);
  3295. node_t *run_mexpr(node_t *node) {
  3296. switch (node->tag) {
  3297. case N_LITERAL:
  3298. switch (node->t->tag) {
  3299. case T_NAME:
  3300. return table_get(list_index(MVARS, -1), node->t->text);
  3301. case T_NUMBER:
  3302. case T_STRING:
  3303. return node;
  3304. default:
  3305. COMPILE_ERROR("not yet implemented");
  3306. }
  3307. break;
  3308. case N_MSTMT: {
  3309. mvar_expand_err_t err = {NULL, 0};
  3310. node_t *n = _expand_mvars(node->a, 1, &err);
  3311. if (!n || err.code != 0)
  3312. return NULL;
  3313. return n;
  3314. } break;
  3315. case N_CALL:
  3316. case N_MACRO_CALL: {
  3317. list_t *args = list_new();
  3318. for (size_t i = 0; i < node->l->length; i++)
  3319. list_push(args, run_mexpr(node->l->data[i]));
  3320. if (node->tag == N_MACRO_CALL) {
  3321. macro_t *m = find_macro(node->t->text, args->length, NULL);
  3322. if (!m)
  3323. return NULL;
  3324. return run_macro(m, args);
  3325. }
  3326. for (size_t i = 0; METAFUNCS[i].name; i++)
  3327. if (strcmp(METAFUNCS[i].name, node->t->text) == 0)
  3328. return METAFUNCS[i].handler(args);
  3329. } break;
  3330. case N_LOGOR:
  3331. if (run_mexpr(node->a) || run_mexpr(node->b))
  3332. return YES;
  3333. case N_LOGAND:
  3334. if (run_mexpr(node->a) && run_mexpr(node->b))
  3335. return YES;
  3336. case N_NEGATE: {
  3337. node_t *a = run_mexpr(node->a);
  3338. return mexpr_negate(a);
  3339. }
  3340. case N_ADD: {
  3341. node_t *a = run_mexpr(node->a);
  3342. node_t *b = run_mexpr(node->b);
  3343. return mexpr_add(a, b);
  3344. }
  3345. case N_SUB: {
  3346. node_t *a = run_mexpr(node->a);
  3347. node_t *b = run_mexpr(node->b);
  3348. return mexpr_sub(a, b);
  3349. }
  3350. case N_MUL: {
  3351. node_t *a = run_mexpr(node->a);
  3352. node_t *b = run_mexpr(node->b);
  3353. return mexpr_mul(a, b);
  3354. }
  3355. case N_DIV: {
  3356. node_t *a = run_mexpr(node->a);
  3357. node_t *b = run_mexpr(node->b);
  3358. return mexpr_div(a, b);
  3359. }
  3360. case N_EQUALS: {
  3361. node_t *a = run_mexpr(node->a);
  3362. node_t *b = run_mexpr(node->b);
  3363. return mexpr_equals(a, b) ? YES : NULL;
  3364. }
  3365. case N_LT: {
  3366. node_t *a = run_mexpr(node->a);
  3367. node_t *b = run_mexpr(node->b);
  3368. return mexpr_less(a, b) ? YES : NULL;
  3369. }
  3370. case N_GT: {
  3371. node_t *a = run_mexpr(node->a);
  3372. node_t *b = run_mexpr(node->b);
  3373. return mexpr_greater(a, b) ? YES : NULL;
  3374. }
  3375. default:
  3376. COMPILE_ERROR("not yet implemented");
  3377. }
  3378. return NULL;
  3379. }
  3380. node_t *run_mnode(node_t *node);
  3381. node_t *run_mnodes(list_t *l) {
  3382. node_t *r = NULL;
  3383. for (size_t i = 0; i < l->length; i++)
  3384. if ((r = run_mnode(l->data[i])))
  3385. break;
  3386. return r;
  3387. }
  3388. node_t *run_mnode(node_t *node) {
  3389. node_t *r = NULL;
  3390. switch (node->tag) {
  3391. case N_MIF:
  3392. if (run_mexpr(node->a))
  3393. r = run_mnodes(node->l);
  3394. else if (node->l2)
  3395. r = run_mnodes(node->l2);
  3396. break;
  3397. case N_MFOR:
  3398. while (run_mexpr(node->a))
  3399. if ((r = run_mnodes(node->l)))
  3400. break;
  3401. break;
  3402. case N_MREPEAT: {
  3403. list_t *l = list_new();
  3404. while (run_mexpr(node->a)) {
  3405. node_t *n = run_mnodes(node->l);
  3406. if (!n)
  3407. return NULL;
  3408. if (IS_EXPR(n))
  3409. n = node1(N_EXPRSTMT, n);
  3410. list_push(l, n);
  3411. }
  3412. r = nodel(N_PROGRAM, l);
  3413. } break;
  3414. case N_MSET:
  3415. table_set(list_index(MVARS, -1), node->t->text, run_mexpr(node->a));
  3416. break;
  3417. case N_MPUSH: {
  3418. node_t *l = table_get(list_index(MVARS, -1), node->t->text);
  3419. if (l && (l->tag == N_LIST || l->tag == N_PROGRAM)) {
  3420. node_t *n = run_mexpr(node->a);
  3421. if (!n)
  3422. break;
  3423. if (IS_EXPR(n)) {
  3424. if (l->tag == N_PROGRAM)
  3425. n = node1(N_EXPRSTMT, n);
  3426. else
  3427. break;
  3428. }
  3429. list_push(l->l, n);
  3430. }
  3431. } break;
  3432. case N_MSTMT:
  3433. r = node->a;
  3434. break;
  3435. case N_MEXPR:
  3436. r = run_mexpr(node->a);
  3437. break;
  3438. default:
  3439. r = node;
  3440. }
  3441. return r;
  3442. }
  3443. list_t *macro_stk;
  3444. size_t expand_depth = 0;
  3445. size_t macro_rlimit = 100;
  3446. node_t *run_macro(macro_t *macro, list_t *args) {
  3447. if (macro_stk->length >= macro_rlimit)
  3448. return NULL;
  3449. list_push(macro_stk, macro);
  3450. table_t *mvars = list_index(MVARS, -1);
  3451. table_set(mvars, "nil", NULL);
  3452. table_set(mvars, "*", nodel(N_LIST, args));
  3453. if (!macro->variable)
  3454. for (size_t i = 0; i < args->length; i++)
  3455. table_set(mvars, ((token_t *)macro->params->data[i])->text,
  3456. args->data[i]);
  3457. node_t *r = NULL;
  3458. for (size_t i = 0; i < macro->body->length; i++) {
  3459. r = run_mnode(macro->body->data[i]);
  3460. if (r)
  3461. break;
  3462. }
  3463. list_pop(macro_stk);
  3464. return r;
  3465. }
  3466. node_t *_expand_mvars(node_t *node, int expr, mvar_expand_err_t *err) {
  3467. if (node->tag == N_LITERAL)
  3468. return node;
  3469. if (node->tag == N_MVAR) {
  3470. char *name = node->t->text;
  3471. err->mvar = node;
  3472. table_t *mvars = list_index(MVARS, -1);
  3473. if (!table_has(mvars, name)) {
  3474. err->code = 1;
  3475. return NULL;
  3476. }
  3477. node_t *n = table_get(mvars, name);
  3478. if (n) {
  3479. if (expr && !IS_EXPR(n)) {
  3480. err->code = 2;
  3481. return NULL;
  3482. }
  3483. if (!expr && IS_EXPR(n))
  3484. n = node1(N_EXPRSTMT, n);
  3485. } else {
  3486. err->code = 3;
  3487. return NULL;
  3488. }
  3489. return n;
  3490. }
  3491. if (node->tag == N_EXPRSTMT) {
  3492. node_t *n = _expand_mvars(node->a, 0, err);
  3493. if (err->code != 0)
  3494. return NULL;
  3495. if (!IS_EXPR(n))
  3496. return n;
  3497. node = node_copy(node);
  3498. node->a = n;
  3499. return node;
  3500. } else if ((node->tag >= N_ADD && node->tag <= N_BAND) ||
  3501. (node->tag >= N_ASSIGN && node->tag <= N_ASSIGN_SHR)) {
  3502. node = node_copy(node);
  3503. node->a = _expand_mvars(node->a, 1, err);
  3504. if (err->code != 0)
  3505. return NULL;
  3506. node->b = _expand_mvars(node->b, 1, err);
  3507. if (err->code != 0)
  3508. return NULL;
  3509. return node;
  3510. } else if (node->tag == N_PROGRAM || node->tag == N_BLOCK ||
  3511. node->tag == N_LIST || node->tag == N_TUPLE || node->tag == N_COMMA) {
  3512. node = node_copy(node);
  3513. node->l = list_copy(node->l);
  3514. for (size_t i = 0; i < node->l->length; i++) {
  3515. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  3516. if (err->code != 0)
  3517. return NULL;
  3518. node->l->data[i] = n;
  3519. }
  3520. return node;
  3521. } else if (node->tag == N_IF || node->tag == N_IFEXPR) {
  3522. node = node_copy(node);
  3523. node->a = _expand_mvars(node->a, 1, err);
  3524. if (err->code != 0)
  3525. return NULL;
  3526. node->b = _expand_mvars(node->b, 1, err);
  3527. if (err->code != 0)
  3528. return NULL;
  3529. if (node->c) {
  3530. node->c = _expand_mvars(node->c, 1, err);
  3531. if (err->code != 0)
  3532. return NULL;
  3533. }
  3534. return node;
  3535. } else if (node->tag == N_CALL) {
  3536. node = node_copy(node);
  3537. node->a = _expand_mvars(node->a, 1, err);
  3538. if (err->code != 0)
  3539. return NULL;
  3540. node->l = list_copy(node->l);
  3541. for (size_t i = 0; i < node->l->length; i++) {
  3542. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  3543. if (err->code != 0)
  3544. return NULL;
  3545. node->l->data[i] = n;
  3546. }
  3547. return node;
  3548. } else if (node->tag == N_MACRO_CALL) {
  3549. node = node_copy(node);
  3550. node->l = list_copy(node->l);
  3551. for (size_t i = 0; i < node->l->length; i++) {
  3552. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  3553. if (err->code != 0)
  3554. return NULL;
  3555. node->l->data[i] = n;
  3556. }
  3557. return node;
  3558. } else if (node->tag == N_INC || node->tag == N_DEC || node->tag == N_PINC || node->tag == N_PDEC) {
  3559. node = node_copy(node);
  3560. node->a = _expand_mvars(node->a, 1, err);
  3561. if (err->code != 0)
  3562. return NULL;
  3563. return node;
  3564. }
  3565. err->code = 4;
  3566. return NULL;
  3567. }
  3568. node_t *expand_mvars(node_t *node, node_t *_node, int expr) {
  3569. mvar_expand_err_t err = {NULL, 0};
  3570. node_t *r = _expand_mvars(_node, expr, &err);
  3571. if ((!r || err.code != 0) && err.mvar) {
  3572. COMPILE_NOTE("macro expansion failed");
  3573. node = err.mvar;
  3574. }
  3575. if (err.code == 1) {
  3576. COMPILE_ERROR("undefined macro variable: '%s'", err.mvar->t->text);
  3577. } else if (err.code == 2) {
  3578. COMPILE_ERROR(
  3579. "macro variable '%s' expanded to non-expression in expression context",
  3580. err.mvar->t->text);
  3581. } else if (err.code == 3) {
  3582. COMPILE_ERROR("macro variable '%s' expanded to nil", err.mvar->t->text);
  3583. } else if (err.code == 4) {
  3584. COMPILE_ERROR("macro variable expansion failed because it is not yet "
  3585. "implemented for this context");
  3586. }
  3587. if (!r)
  3588. COMPILE_ERROR("macro variable expansion failed");
  3589. return r;
  3590. }
  3591. void compile_macro_call(buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  3592. table_t *ltab, int_stack_t *lstk, int_stack_t *sstk,
  3593. list_t *lbl, node_t *node, int expr) {
  3594. size_t argc = node->l->length;
  3595. char *name = node->t->text;
  3596. int res = 0;
  3597. macro_t *m = find_macro(name, argc, &res);
  3598. if (!m) {
  3599. if (res == 1) {
  3600. COMPILE_ERROR("undefined macro: '%s'", name);
  3601. } else {
  3602. COMPILE_ERROR("no %d-param candidate found for macro: '%s'", argc, name);
  3603. }
  3604. }
  3605. list_push(MVARS, table_new());
  3606. if (macro_stk->length >= macro_rlimit)
  3607. COMPILE_ERROR("recursion depth limit exceeded while expanding macro: '%s'",
  3608. name);
  3609. node_t *r = run_macro(m, node->l);
  3610. if (r) {
  3611. r = expand_mvars(node, r, expr);
  3612. if (r->tag == N_MACRO_CALL) {
  3613. list_pop(MVARS);
  3614. if (expand_depth >= macro_rlimit)
  3615. COMPILE_ERROR(
  3616. "recursion depth limit exceeded while expanding macro: '%s'", name);
  3617. expand_depth++;
  3618. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, r, expr);
  3619. expand_depth--;
  3620. return;
  3621. }
  3622. if (expr && !IS_EXPR(r))
  3623. COMPILE_ERROR(
  3624. "macro '%s' expanded to non-expression in expression context", name);
  3625. if (!expr && IS_EXPR(r))
  3626. r = node1(N_EXPRSTMT, r);
  3627. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, r);
  3628. } else
  3629. COMPILE_ERROR("macro '%s' expanded to nil", name);
  3630. list_pop(MVARS);
  3631. }
  3632. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3633. int_stack_t *lstk, int_stack_t *sstk, list_t *lbl,
  3634. node_t *node) {
  3635. switch (node->tag) {
  3636. case N_TOPLEVEL:
  3637. case N_PROGRAM:
  3638. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3639. break;
  3640. case N_EXPRSTMT:
  3641. if (node->a->tag == N_LITERAL && node->a->t->tag != T_NAME)
  3642. break;
  3643. else if (node->a->tag == N_MACRO_CALL) {
  3644. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a, 0);
  3645. break;
  3646. }
  3647. EMIT("(void)(");
  3648. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3649. EMIT(");");
  3650. break;
  3651. case N_BLOCK:
  3652. LBPUSH();
  3653. CTXPUSH("scope");
  3654. list_push(CONSTANTS, table_new());
  3655. list_push(MACROS, table_new());
  3656. EMIT("qi_new_sticky_scope(state);\n");
  3657. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3658. EMIT("qi_old_scope(state);");
  3659. list_pop(MACROS);
  3660. list_pop(CONSTANTS);
  3661. CTXPOP();
  3662. LBPOP();
  3663. break;
  3664. case N_LITERAL:
  3665. switch (node->t->tag) {
  3666. case T_NUMBER: {
  3667. char *number = node->t->text;
  3668. if (strncmp(number, "0o", 2) == 0 || strncmp(number, "0b", 2) == 0) {
  3669. buffer_t *buf = buffer_new();
  3670. if (number[1] == 'o')
  3671. buffer_fmt(buf, "0%s", number + 2);
  3672. else
  3673. buffer_fmt(buf, "%d", strtol(number + 2, NULL, 2));
  3674. number = buffer_read(buf);
  3675. } else if (number[0] == '0' && number[1] && isdigit(number[1])) {
  3676. size_t i;
  3677. for (i = 0; i < strlen(number); i++)
  3678. if (number[i] != '0' || number[i + 1] == '.')
  3679. break;
  3680. number += i;
  3681. }
  3682. EMIT("qi_make_number(state, %s)", number);
  3683. } break;
  3684. case T_STRING:
  3685. if (!*(node->t->text)) {
  3686. EMIT("state->empty_string");
  3687. } else {
  3688. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  3689. }
  3690. break;
  3691. case T_FSTRING: {
  3692. char *text = node->t->text;
  3693. if (!*text) {
  3694. EMIT("state->empty_string");
  3695. break;
  3696. }
  3697. list_t *parts = list_new();
  3698. buffer_t *tbuf = buffer_new();
  3699. for (size_t i = 0; i < strlen(text); i++) {
  3700. char c = text[i];
  3701. if (c == '$' && text[i + 1] == '$') {
  3702. buffer_append(tbuf, '$');
  3703. i++;
  3704. continue;
  3705. } else if (c == '$' && text[i + 1] == '{') {
  3706. i += 2;
  3707. buffer_t *tbuf2 = buffer_new();
  3708. while (text[i] && text[i] != '}')
  3709. buffer_append(tbuf2, text[i++]);
  3710. if (text[i] != '}') {
  3711. i--;
  3712. buffer_appends(tbuf, "${");
  3713. buffer_appendb(tbuf, tbuf2);
  3714. continue;
  3715. }
  3716. if (tbuf->size > 0)
  3717. list_push(parts, nodeb(tbuf));
  3718. tbuf = buffer_new();
  3719. char *source = buffer_read(tbuf2);
  3720. list_t *pair = list_new();
  3721. buffer_t *fname = buffer_new();
  3722. size_t line, col;
  3723. (void)traverse(GETSRC(node->fi), node->pos, &line, &col);
  3724. buffer_fmt(fname, "<fstring at %s:%zu:%zu>", GETFNAME(node->fi), line,
  3725. col);
  3726. list_push(pair, buffer_read(fname));
  3727. list_push(pair, source);
  3728. list_push(FILES, pair);
  3729. list_t *tokens = tokenize(source);
  3730. size_t pos = 0;
  3731. node_t *n = parse_expr(tokens, &pos);
  3732. if (pos != tokens->length - 1)
  3733. COMPILE_ERROR("unconsumed input in f-expr");
  3734. list_push(parts, n);
  3735. } else
  3736. buffer_append(tbuf, c);
  3737. }
  3738. if (tbuf->size > 0)
  3739. list_push(parts, nodeb(tbuf));
  3740. tbuf = buffer_new();
  3741. NEWGID();
  3742. buffer_fmt(tbuf,
  3743. "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  3744. PREFIX, gid);
  3745. buffer_fmt(tbuf, "qi_value_t *str = state->empty_string;\n");
  3746. for (size_t i = 0; i < parts->length; i++) {
  3747. node_t *part = parts->data[i];
  3748. buffer_fmt(tbuf, "str = qi_add(state, str, ");
  3749. if (part->tag == N_BUFFER)
  3750. buffer_fmt(tbuf, "qi_make_string(state, \"%s\")",
  3751. buffer_read(part->buf));
  3752. else {
  3753. buffer_fmt(tbuf, "qi_to_string(state, ");
  3754. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, part);
  3755. buffer_fmt(tbuf, ")");
  3756. }
  3757. buffer_fmt(tbuf, ");\n");
  3758. }
  3759. buffer_fmt(tbuf, "return str;\n}\n");
  3760. buffer_appendb(gbuf, tbuf);
  3761. EMIT("__%s%d(state)", PREFIX, gid);
  3762. } break;
  3763. case T_USTRING:
  3764. EMIT("qi_call(state, qi_get(state, \"ustr\"), qi_list_push(qi_list_make(), qi_make_string(state, \"%s\")))", node->t->text);
  3765. break;
  3766. case T_NAME: {
  3767. char *name = node->t->text;
  3768. node_t *n = const_get(name);
  3769. if (n)
  3770. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  3771. else
  3772. EMIT("qi_get(state, \"%s\")", name);
  3773. } break;
  3774. case T_TRUE: EMIT("state->_true"); break;
  3775. case T_FALSE: EMIT("state->_false"); break;
  3776. case T_NIL: EMIT("state->nil"); break;
  3777. default:
  3778. COMPILE_ERROR("not yet implemented");
  3779. }
  3780. break;
  3781. case N_COMMA:
  3782. EMIT("(");
  3783. for (size_t i = 0; i < node->l->length; i++) {
  3784. if (i != 0)
  3785. EMIT(", ");
  3786. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l->data[i]);
  3787. }
  3788. EMIT(")");
  3789. break;
  3790. case N_LIST:
  3791. EMIT("qi_make_list(state, ");
  3792. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3793. EMIT(")");
  3794. break;
  3795. case N_LISTGEN: {
  3796. NEWGID();
  3797. buffer_t *tbuf = buffer_new();
  3798. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  3799. PREFIX, gid);
  3800. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  3801. buffer_t *bbuf = buffer_new();
  3802. if (node->b) {
  3803. buffer_fmt(bbuf, "if (_qi_truthy(state, ");
  3804. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3805. buffer_fmt(bbuf, ")) {\n");
  3806. }
  3807. for (size_t i = 0; i < node->a->b->l->length; i++) {
  3808. buffer_fmt(bbuf, "qi_list_push(list, ");
  3809. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl,
  3810. node->a->b->l->data[i]);
  3811. buffer_fmt(bbuf, ");\n");
  3812. }
  3813. if (node->b)
  3814. buffer_fmt(bbuf, "}\n");
  3815. node->a->b = nodeb(bbuf);
  3816. node->a->t2 = NULL;
  3817. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3818. buffer_fmt(tbuf, "return qi_make_list(state, list);\n}\n");
  3819. buffer_appendb(gbuf, tbuf);
  3820. EMIT("__%s%d(state)", PREFIX, gid);
  3821. } break;
  3822. case N_TUPLE:
  3823. EMIT("qi_make_tuple(state, ");
  3824. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3825. EMIT(")");
  3826. break;
  3827. case N_NILTUPLE:
  3828. EMIT("state->empty_tuple");
  3829. break;
  3830. case N_TABLE:
  3831. EMIT("qi_make_table(state, ");
  3832. compile_table(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->h);
  3833. EMIT(")");
  3834. break;
  3835. case N_CALL:
  3836. if (DEBUG) {
  3837. EMIT("qi_call_debug(state, ");
  3838. } else {
  3839. EMIT("qi_call(state, ");
  3840. }
  3841. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3842. EMIT(", ");
  3843. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3844. if (DEBUG)
  3845. buffer_fmt(buf, ", __debugData[%d]", insert_debug(node));
  3846. EMIT(")");
  3847. break;
  3848. case N_MEMBER:
  3849. EMIT("qi_index(state, ");
  3850. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3851. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  3852. break;
  3853. case N_INDEX:
  3854. EMIT("qi_index(state, ");
  3855. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3856. EMIT(", ");
  3857. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3858. EMIT(")");
  3859. break;
  3860. case N_SLICE: {
  3861. NEWGID();
  3862. buffer_t *tbuf = buffer_new();
  3863. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  3864. PREFIX, gid);
  3865. if (node->b && node->c) {
  3866. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  3867. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3868. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3869. buffer_fmt(tbuf, ";\n");
  3870. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  3871. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3872. buffer_fmt(tbuf, ";\n");
  3873. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  3874. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  3875. buffer_fmt(tbuf, ";\n");
  3876. } else if (node->b) {
  3877. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(2);\n");
  3878. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3879. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3880. buffer_fmt(tbuf, ";\n");
  3881. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  3882. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3883. buffer_fmt(tbuf, ";\n");
  3884. } else {
  3885. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  3886. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3887. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3888. buffer_fmt(tbuf, ";\n");
  3889. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = state->zero;\n");
  3890. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  3891. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  3892. buffer_fmt(tbuf, ";\n");
  3893. }
  3894. buffer_fmt(tbuf,
  3895. "return qi_call(state, qi_get(state, \"__slice\"), pargs);\n");
  3896. buffer_fmt(tbuf, "}\n");
  3897. buffer_appendb(gbuf, tbuf);
  3898. EMIT("__%s%d(state)", PREFIX, gid);
  3899. } break;
  3900. case N_ASSIGN:
  3901. if (node->a->tag == N_LIST) {
  3902. if (node->a->l->length < 2)
  3903. COMPILE_ERROR("illegal unpack assignment left-hand side");
  3904. NEWGID();
  3905. buffer_t *tbuf = buffer_new();
  3906. buffer_fmt(tbuf,
  3907. "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  3908. PREFIX, gid);
  3909. char *varname = tempvar();
  3910. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  3911. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3912. buffer_fmt(tbuf, ";\n");
  3913. for (size_t i = 0; i < node->a->l->length; i++) {
  3914. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i],
  3915. buffer_fmt(tbuf,
  3916. "qi_index(state, %s, qi_make_number(state, %d))",
  3917. varname, i), falss);
  3918. buffer_fmt(tbuf, ";\n");
  3919. }
  3920. buffer_fmt(tbuf, "return %s;\n}\n", varname);
  3921. buffer_appendb(gbuf, tbuf);
  3922. EMIT("__%s%d(state)", PREFIX, gid);
  3923. break;
  3924. } else if (node->a->tag == N_TUPLE) {
  3925. if (node->a->l->length < 2)
  3926. COMPILE_ERROR("illegal multiple assignment left-hand side");
  3927. if (node->b->tag != N_TUPLE || node->b->l->length < 2 ||
  3928. node->a->l->length != node->b->l->length)
  3929. COMPILE_ERROR("illegal multiple assignment right-hand side");
  3930. NEWGID();
  3931. buffer_t *tbuf = buffer_new();
  3932. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX,
  3933. gid);
  3934. list_t *vals = list_new();
  3935. for (size_t i = 0; i < node->b->l->length; i++) {
  3936. char *varname = tempvar();
  3937. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  3938. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  3939. node->b->l->data[i]);
  3940. buffer_fmt(tbuf, ";\n");
  3941. list_push(vals, varname);
  3942. }
  3943. for (size_t i = 0; i < node->a->l->length; i++) {
  3944. char *varname = vals->data[i];
  3945. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i],
  3946. buffer_fmt(tbuf, "%s", varname), false);
  3947. buffer_fmt(tbuf, ";\n");
  3948. }
  3949. buffer_fmt(tbuf, "return %s;\n}\n", vals->data[vals->length - 1]);
  3950. buffer_appendb(gbuf, tbuf);
  3951. EMIT("__%s%d(state)", PREFIX, gid);
  3952. break;
  3953. }
  3954. ASSIGN(node->a,
  3955. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3956. break;
  3957. case N_ASSIGN_ADD:
  3958. COMPASSIGN(node->a, "add",
  3959. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3960. break;
  3961. case N_ASSIGN_SUB:
  3962. COMPASSIGN(node->a, "sub",
  3963. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3964. break;
  3965. case N_ASSIGN_MUL:
  3966. COMPASSIGN(node->a, "mul",
  3967. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3968. break;
  3969. case N_ASSIGN_DIV:
  3970. COMPASSIGN(node->a, "div",
  3971. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3972. break;
  3973. case N_ASSIGN_IDIV:
  3974. COMPASSIGN(node->a, "idiv",
  3975. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3976. break;
  3977. case N_ASSIGN_MOD:
  3978. COMPASSIGN(node->a, "mod",
  3979. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3980. break;
  3981. case N_ASSIGN_POW:
  3982. COMPASSIGN(node->a, "pow",
  3983. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3984. break;
  3985. case N_ASSIGN_BOR:
  3986. COMPASSIGN(node->a, "bor",
  3987. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3988. break;
  3989. case N_ASSIGN_BAND:
  3990. COMPASSIGN(node->a, "band",
  3991. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3992. break;
  3993. case N_ASSIGN_XOR:
  3994. COMPASSIGN(node->a, "xor",
  3995. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3996. break;
  3997. case N_ASSIGN_SHL:
  3998. COMPASSIGN(node->a, "shl",
  3999. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  4000. break;
  4001. case N_ASSIGN_SHR:
  4002. COMPASSIGN(node->a, "shr",
  4003. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  4004. break;
  4005. case N_INC:
  4006. COMPASSIGN(node->a, "add", EMIT("state->one"));
  4007. break;
  4008. case N_DEC:
  4009. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  4010. break;
  4011. case N_PINC:
  4012. COMPASSIGNP(node->a, "add", EMIT("state->one"));
  4013. break;
  4014. case N_PDEC:
  4015. COMPASSIGNP(node->a, "sub", EMIT("state->one"));
  4016. break;
  4017. case N_VAR:
  4018. case N_LET:
  4019. table_iterate(node->h, {
  4020. EMIT("qi_%s(state, \"%s\", ", node->tag == N_LET ? "decl_const" : "decl",
  4021. entry.key);
  4022. if (entry.value)
  4023. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, entry.value);
  4024. else
  4025. EMIT("state->nil");
  4026. EMIT(");\n");
  4027. });
  4028. break;
  4029. case N_VARUNPACK:
  4030. case N_LETUNPACK: {
  4031. char *varname = tempvar();
  4032. EMIT("qi_value_t *%s = ", varname);
  4033. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4034. EMIT(";\n");
  4035. for (size_t i = 0; i < node->l->length; i++)
  4036. EMIT("%s(state, \"%s\", qi_index(state, %s, qi_make_number(state, "
  4037. "%d)));\n",
  4038. node->tag == N_VARUNPACK ? "qi_decl" : "qi_decl_const",
  4039. node->l->data[i], varname, i);
  4040. } break;
  4041. case N_CONST:
  4042. break;
  4043. case N_IF:
  4044. CTXPUSH("scope");
  4045. EMIT("qi_new_scope(state);\n");
  4046. EMIT("if (_qi_truthy(state, ");
  4047. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4048. EMIT(")) {\n");
  4049. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  4050. if (node->c) {
  4051. EMIT("} else {\n");
  4052. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  4053. }
  4054. EMIT("}\n");
  4055. CTXPOP();
  4056. EMIT("qi_old_scope(state);\n");
  4057. break;
  4058. case N_SWITCH: {
  4059. NEWGID();
  4060. if (node->t2) {
  4061. if (table_get(ltab, node->t2->text))
  4062. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  4063. int_stack_t *pair = stack_new();
  4064. stack_push(pair, 1);
  4065. stack_push(pair, gid);
  4066. table_set(ltab, node->t2->text, pair);
  4067. }
  4068. char *varname = tempvar();
  4069. EMIT("qi_value_t *%s = ", varname);
  4070. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4071. EMIT(";\n");
  4072. for (size_t i = 0; i < node->l->length; i++) {
  4073. list_t *pair = node->l->data[i];
  4074. if (!pair->data[0])
  4075. continue;
  4076. char *label = tempvar();
  4077. EMIT("if (_qi_equals(state, %s, ", varname);
  4078. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  4079. EMIT(")) goto %s;\n", label);
  4080. pair->data[0] = label;
  4081. }
  4082. EMIT("goto __default%d;\n", gid);
  4083. SPUSH(gid);
  4084. CTXPUSH("switch");
  4085. for (size_t i = 0; i < node->l->length; i++) {
  4086. list_t *pair = node->l->data[i];
  4087. char *label = pair->data[0];
  4088. node_t *block = pair->data[1];
  4089. if (!label) {
  4090. EMIT("__default%d:;\n", gid);
  4091. } else {
  4092. EMIT("%s:;\n", label);
  4093. }
  4094. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, block);
  4095. }
  4096. CTXPOP();
  4097. SPOP();
  4098. EMIT("__break%d:;\n", gid);
  4099. } break;
  4100. case N_FOR: {
  4101. NEWGID();
  4102. if (node->t2) {
  4103. if (table_get(ltab, node->t2->text))
  4104. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  4105. int_stack_t *pair = stack_new();
  4106. stack_push(pair, 0);
  4107. stack_push(pair, gid);
  4108. table_set(ltab, node->t2->text, pair);
  4109. }
  4110. CTXPUSH("scope");
  4111. EMIT("qi_new_scope(state);\n");
  4112. if (!node->a) {
  4113. EMIT("for (;;) {\n");
  4114. } else if (node->a && !node->b) {
  4115. EMIT("while (_qi_truthy(state, ");
  4116. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4117. EMIT(")) {\n");
  4118. } else {
  4119. node_t *a = node->a;
  4120. if (IS_EXPR(a))
  4121. a = node1(N_EXPRSTMT, a);
  4122. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, a);
  4123. EMIT("while (_qi_truthy(state, ");
  4124. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  4125. EMIT(")) {\n");
  4126. }
  4127. CTXPUSH("scope");
  4128. EMIT("qi_new_scope(state);\n");
  4129. LPUSH(gid);
  4130. CTXPUSH("for");
  4131. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->d);
  4132. EMIT("__continue%d:;\n", gid);
  4133. if (node->c) {
  4134. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  4135. EMIT(";\n");
  4136. }
  4137. CTXPOP();
  4138. LPOP();
  4139. CTXPOP();
  4140. EMIT("qi_old_scope(state);\n");
  4141. EMIT("}\n");
  4142. EMIT("goto __exit%d;\n", gid);
  4143. EMIT("__break%d:;\n", gid);
  4144. EMIT("qi_old_scope(state);\n");
  4145. EMIT("__exit%d:;\n", gid);
  4146. CTXPOP();
  4147. EMIT("qi_old_scope(state);\n");
  4148. } break;
  4149. case N_FOROF:
  4150. case N_FOROFVAR:
  4151. case N_FOROFUNPACK:
  4152. case N_FOROFVARUNPACK: {
  4153. NEWGID();
  4154. if (node->t2) {
  4155. if (table_get(ltab, node->t2->text))
  4156. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  4157. int_stack_t *pair = stack_new();
  4158. stack_push(pair, 0);
  4159. stack_push(pair, gid);
  4160. table_set(ltab, node->t2->text, pair);
  4161. }
  4162. CTXPUSH("scope");
  4163. EMIT("qi_new_scope(state);\n");
  4164. char *varname = tempvar();
  4165. EMIT("qi_value_t *%s = qi_iter(state, ", varname);
  4166. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4167. EMIT(");\n");
  4168. if (node->tag == N_FOROFVAR) {
  4169. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->t->text);
  4170. } else if (node->tag == N_FOROFVARUNPACK) {
  4171. for (size_t i = 0; i < node->l->length; i++)
  4172. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->l->data[i]);
  4173. }
  4174. EMIT("for (qi_size_t length = _qi_length(state, %s), i = 0; i < length; "
  4175. "i++) {\n",
  4176. varname);
  4177. if (node->tag == N_FOROFUNPACK || node->tag == N_FOROFVARUNPACK) {
  4178. for (size_t i = 0; i < node->l->length; i++)
  4179. EMIT("qi_set(state, false, \"%s\", qi_index(state, qi_index(state, %s, "
  4180. "qi_make_number(state, i)), qi_make_number(state, %d)));\n",
  4181. node->l->data[i], varname, i);
  4182. } else
  4183. EMIT("qi_set(state, false, \"%s\", qi_index(state, %s, "
  4184. "qi_make_number(state, i)));\n",
  4185. node->t->text, varname);
  4186. CTXPUSH("scope");
  4187. EMIT("qi_new_scope(state);\n");
  4188. LPUSH(gid);
  4189. CTXPUSH("for");
  4190. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  4191. CTXPOP();
  4192. LPOP();
  4193. EMIT("__continue%d:;\n", gid);
  4194. CTXPOP();
  4195. EMIT("qi_old_scope(state);\n");
  4196. EMIT("}\n");
  4197. EMIT("goto __exit%d;\n", gid);
  4198. EMIT("__break%d:;\n", gid);
  4199. EMIT("qi_old_scope(state);\n");
  4200. EMIT("__exit%d:;\n", gid);
  4201. CTXPOP();
  4202. EMIT("qi_old_scope(state);\n");
  4203. } break;
  4204. case N_BREAK:
  4205. if (!INCTX("for") && !INCTX("switch"))
  4206. COMPILE_ERROR("break outside of a loop or a switch");
  4207. if (node->t) {
  4208. if (node->t->tag == T_NUMBER) {
  4209. unsigned int offset = abs(atoi(node->t->text)) + 1;
  4210. if (offset < 2 || offset > lstk->length)
  4211. COMPILE_ERROR("%d is not a valid break loop offset", offset - 1);
  4212. EMIT("goto __break%d;", lstk->data[lstk->length - offset]);
  4213. } else {
  4214. char *label = node->t->text;
  4215. int_stack_t *pair = table_get(ltab, label);
  4216. if (!pair)
  4217. COMPILE_ERROR("undefined loop label: '%s'", label);
  4218. EMIT("goto __break%d;", pair->data[1]);
  4219. }
  4220. break;
  4221. }
  4222. EMIT("goto __break%d;", in_switch(ctx) ? SID : LID);
  4223. break;
  4224. case N_CONTINUE:
  4225. if (!INCTX("for"))
  4226. COMPILE_ERROR("continue outside of a loop");
  4227. if (node->t) {
  4228. if (node->t->tag == T_NUMBER) {
  4229. unsigned int offset = abs(atoi(node->t->text)) + 1;
  4230. if (offset < 2 || offset > lstk->length)
  4231. COMPILE_ERROR("%d is not a valid break loop offset", offset - 1);
  4232. EMIT("goto __continue%d;", lstk->data[lstk->length - offset]);
  4233. } else {
  4234. char *label = node->t->text;
  4235. int_stack_t *pair = table_get(ltab, label);
  4236. if (pair->data[1])
  4237. COMPILE_ERROR("continue on a switch loop label: '%s'", label);
  4238. if (!pair)
  4239. COMPILE_ERROR("undefined loop label: '%s'", label);
  4240. EMIT("goto __continue%d;", pair->data[1]);
  4241. }
  4242. break;
  4243. }
  4244. EMIT("goto __continue%d;", LID);
  4245. break;
  4246. case N_DEFER: {
  4247. NEWGID();
  4248. buffer_t *tbuf = buffer_new();
  4249. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  4250. LBPUSH();
  4251. CTXPUSH("gap");
  4252. list_push(CONSTANTS, table_new());
  4253. list_push(MACROS, table_new());
  4254. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl,
  4255. node->a);
  4256. list_pop(MACROS);
  4257. list_pop(CONSTANTS);
  4258. CTXPOP();
  4259. LBPOP();
  4260. buffer_fmt(tbuf, "\n}\n");
  4261. buffer_appendb(gbuf, tbuf);
  4262. EMIT("qi_add_defer(state, -1, __%s%d);", PREFIX, gid);
  4263. } break;
  4264. case N_RETURN:
  4265. if (!INCTX("func"))
  4266. COMPILE_ERROR("return outside of a function");
  4267. for (size_t i = 0; i < SCOPESK; i++)
  4268. EMIT("qi_old_scope(state);\n");
  4269. for (size_t i = 0; i < TRAPSK; i++)
  4270. EMIT("qi_unset_trap(state, trap);\n");
  4271. EMIT("return ");
  4272. if (node->a)
  4273. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4274. else
  4275. EMIT("state->nil");
  4276. EMIT(";");
  4277. break;
  4278. case N_FUNCDEF:
  4279. break;
  4280. case N_CLASS:
  4281. break;
  4282. case N_PASS:
  4283. break;
  4284. case N_DEL:
  4285. EMIT("qi_del(state, ");
  4286. if (node->a->tag == N_INDEX) {
  4287. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  4288. EMIT(", ");
  4289. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->b);
  4290. } else if (node->a->tag == N_MEMBER) {
  4291. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  4292. EMIT(", qi_make_string(state, \"%s\")", node->a->t->text);
  4293. } else
  4294. COMPILE_ERROR("not a index/member expression");
  4295. EMIT(");");
  4296. break;
  4297. case N_TRY:
  4298. EMIT("qi_try(state, {\n");
  4299. LBPUSH();
  4300. CTXPUSH("gap");
  4301. CTXPUSH("trap");
  4302. compile_node(gbuf, buf, ctx, table_new(), stack_new(), stack_new(), lbl,
  4303. node->a);
  4304. CTXPOP();
  4305. CTXPOP();
  4306. LBPOP();
  4307. EMIT("}, {\n");
  4308. if (node->t)
  4309. EMIT("qi_decl(state, \"%s\", trap->value);\n", node->t->text);
  4310. LBPUSH();
  4311. CTXPUSH("gap");
  4312. compile_node(gbuf, buf, ctx, table_new(), stack_new(), stack_new(), lbl,
  4313. node->b);
  4314. CTXPOP();
  4315. LBPOP();
  4316. if (node->c) {
  4317. NEWGID();
  4318. buffer_t *tbuf = buffer_new();
  4319. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  4320. LBPUSH();
  4321. CTXPUSH("gap");
  4322. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl,
  4323. node->c);
  4324. CTXPOP();
  4325. LBPOP();
  4326. buffer_fmt(tbuf, "\n}\n");
  4327. buffer_appendb(gbuf, tbuf);
  4328. EMIT("}, __%s%d);\n", PREFIX, gid);
  4329. } else {
  4330. EMIT("}, NULL);\n");
  4331. }
  4332. break;
  4333. case N_THROW:
  4334. if (!node->a) {
  4335. EMIT("qi_throw(state, state->nil);");
  4336. } else if (DEBUG) {
  4337. char *varname = tempvar();
  4338. EMIT("qi_value_t *%s = ", varname);
  4339. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4340. EMIT(";\n");
  4341. emit_debug(buf, node);
  4342. EMIT("qi_throw(state, %s);", varname);
  4343. } else {
  4344. EMIT("qi_throw(state, ");
  4345. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4346. EMIT(");");
  4347. }
  4348. break;
  4349. case N_LABEL: {
  4350. size_t *gid = table_get(list_index(lbl, -1), node->t->text);
  4351. EMIT("__label%d:;", *gid);
  4352. } break;
  4353. case N_GOTO: {
  4354. char *label = node->t->text;
  4355. size_t *gid = table_get(list_index(lbl, -1), label);
  4356. if (!gid)
  4357. COMPILE_ERROR("undefined label: '%s'", label);
  4358. EMIT("goto __label%d;", *gid);
  4359. } break;
  4360. case N_REQUIRE:
  4361. for (size_t i = 0; i < node->l->length; i++) {
  4362. token_t *t = node->l->data[i];
  4363. char *path = unescape(t->text);
  4364. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, path) < 0)
  4365. COMPILE_ERROR("'%s' is not a valid file path or a builtin library name",
  4366. path);
  4367. }
  4368. break;
  4369. case N_IFEXPR:
  4370. EMIT("(_qi_truthy(state, ");
  4371. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4372. EMIT(")? ");
  4373. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  4374. EMIT(": ");
  4375. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  4376. EMIT(")");
  4377. break;
  4378. case N_FUNCEXPR:
  4379. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  4380. break;
  4381. case N_EQUALS:
  4382. BINOP("equals");
  4383. break;
  4384. case N_NOTEQUALS:
  4385. BINOP("not_equals");
  4386. break;
  4387. case N_IS:
  4388. BINOP("is");
  4389. break;
  4390. case N_NOTIS:
  4391. BINOP("not_is");
  4392. break;
  4393. case N_IN:
  4394. BINOP("in");
  4395. break;
  4396. case N_NOTIN:
  4397. BINOP("not_in");
  4398. break;
  4399. case N_LT:
  4400. BINOP("lt");
  4401. break;
  4402. case N_GT:
  4403. BINOP("gt");
  4404. break;
  4405. case N_LE:
  4406. BINOP("le");
  4407. break;
  4408. case N_GE:
  4409. BINOP("ge");
  4410. break;
  4411. case N_ADD:
  4412. BINOP("add");
  4413. break;
  4414. case N_SUB:
  4415. BINOP("sub");
  4416. break;
  4417. case N_MUL:
  4418. BINOP("mul");
  4419. break;
  4420. case N_DIV:
  4421. BINOP("div");
  4422. break;
  4423. case N_IDIV:
  4424. BINOP("idiv");
  4425. break;
  4426. case N_MOD:
  4427. BINOP("mod");
  4428. break;
  4429. case N_POW:
  4430. BINOP("pow");
  4431. break;
  4432. case N_SHL:
  4433. BINOP("shl");
  4434. break;
  4435. case N_SHR:
  4436. BINOP("shr");
  4437. break;
  4438. case N_XOR:
  4439. BINOP("xor");
  4440. break;
  4441. case N_BOR:
  4442. BINOP("bor");
  4443. break;
  4444. case N_BAND:
  4445. BINOP("band");
  4446. break;
  4447. case N_LOGOR:
  4448. BINOP("or");
  4449. break;
  4450. case N_LOGAND:
  4451. BINOP("and");
  4452. break;
  4453. case N_NEGATE:
  4454. UNOP("negate");
  4455. break;
  4456. case N_UNARY_PLUS:
  4457. UNOP("unary_plus");
  4458. break;
  4459. case N_NOT:
  4460. UNOP("not");
  4461. break;
  4462. case N_BNOT:
  4463. UNOP("bnot");
  4464. break;
  4465. case N_MACRO_CALL:
  4466. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, 1);
  4467. break;
  4468. case N_MVAR:
  4469. COMPILE_ERROR("macro variable outside of a macro");
  4470. case N_INLINE: {
  4471. char *text = unescape(node->t->text);
  4472. if (text[0] == '#') {
  4473. EMIT("%s", text);
  4474. } else {
  4475. EMIT("%s;", text);
  4476. }
  4477. } break;
  4478. case N_HEADER:
  4479. buffer_fmt(HBUF, "%s\n", unescape(node->t->text));
  4480. break;
  4481. case N_INCLUDE:
  4482. buffer_fmt(HBUF, "#include <%s>\n", unescape(node->t->text));
  4483. break;
  4484. case N_BUFFER:
  4485. buffer_appendb(buf, node->buf);
  4486. break;
  4487. default:
  4488. COMPILE_ERROR("not yet implemented");
  4489. }
  4490. }
  4491. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  4492. table_t *ltab, int_stack_t *lstk, int_stack_t *sstk,
  4493. list_t *lbl) {
  4494. node_t *n = parse(source);
  4495. if (NEEDS_UTF8) {
  4496. NEEDS_UTF8 = 0;
  4497. require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, "utf8");
  4498. }
  4499. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  4500. }
  4501. char *escape(char *s) {
  4502. buffer_t *buf = buffer_new();
  4503. while (*s) {
  4504. if (*s == '\\' || *s == '"')
  4505. buffer_append(buf, '\\');
  4506. buffer_append(buf, *s++);
  4507. }
  4508. return buffer_read(buf);
  4509. }
  4510. char *compile(char *source, list_t *required) {
  4511. list_t *ctx = list_new();
  4512. table_t *ltab = table_new();
  4513. int_stack_t *lstk = stack_new();
  4514. int_stack_t *sstk = stack_new();
  4515. list_t *lbl = list_new();
  4516. LBPUSH();
  4517. buffer_t *gbuf = buffer_new();
  4518. buffer_t *buf = buffer_new();
  4519. compile_into("const __QIC = \"" QIC_VERSION "\"", gbuf, buf, ctx, ltab, lstk,
  4520. sstk, lbl);
  4521. compile_into("macro E(x) {\n$set r E(x)\n$if r = nil\n$x\n$else\n$r\n$endif}",
  4522. gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  4523. if (required && required->length)
  4524. for (size_t i = 0; i < required->length; i++)
  4525. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl,
  4526. required->data[i]) < 0) {
  4527. fprintf(
  4528. stderr,
  4529. "fatal: '%s' is not a valid file path or a builtin library name\n",
  4530. (char *)required->data[i]);
  4531. exit(1);
  4532. }
  4533. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  4534. buffer_t *rbuf = buffer_new();
  4535. buffer_appends(rbuf, "#include <qirt.h>\n");
  4536. if (DEBUG && DEBUGDATA->length) {
  4537. buffer_fmt(rbuf, "static const char *__debugData[%d] = {\n",
  4538. DEBUGDATA->length);
  4539. for (size_t i = 0; i < DEBUGDATA->length; i++)
  4540. buffer_fmt(rbuf, "\"%s\",\n", escape(DEBUGDATA->data[i]));
  4541. buffer_fmt(rbuf, "};\n");
  4542. }
  4543. buffer_appendb(rbuf, HBUF);
  4544. buffer_appendb(rbuf, gbuf);
  4545. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  4546. buffer_appends(rbuf, "qi_state_t *state;\n");
  4547. if (DEBUG)
  4548. buffer_appends(rbuf, "qi_state_init_debug(&state);\n");
  4549. else
  4550. buffer_appends(rbuf, "qi_state_init(&state);\n");
  4551. buffer_appends(rbuf, "qi_list_t *args = qi_list_make();\n");
  4552. buffer_appends(rbuf, "for (int i = 0; i < argc; i++)\n");
  4553. buffer_appends(rbuf,
  4554. " qi_list_push(args, qi_make_string(state, argv[i]));\n");
  4555. buffer_appends(
  4556. rbuf, "qi_decl_const(state, \"ARGS\", qi_make_list(state, args));\n");
  4557. buffer_appendb(rbuf, buf);
  4558. buffer_appends(rbuf, "qi_old_scope(state);\n");
  4559. buffer_appends(rbuf, "qi_finalize();\n");
  4560. buffer_appends(rbuf, "return 0;\n");
  4561. buffer_appends(rbuf, "}\n");
  4562. return buffer_read(rbuf);
  4563. }
  4564. char *compile_file(char *filename, FILE *fd, list_t *required) {
  4565. buffer_t *buf = buffer_new();
  4566. for (;;) {
  4567. char line[512];
  4568. if (!fgets(line, sizeof(line), fd))
  4569. break;
  4570. buffer_appends(buf, line);
  4571. }
  4572. char *source = buffer_read(buf);
  4573. list_t *pair = list_new();
  4574. list_push(pair, filename);
  4575. list_push(pair, source);
  4576. list_push(FILES, pair);
  4577. char *out = compile(source, required);
  4578. list_pop(FILES);
  4579. return out;
  4580. }
  4581. int main(int argc, char **argv) {
  4582. YES = nodet(N_LITERAL, token(T_STRING, "yes"));
  4583. DEBUGDATA = list_new();
  4584. FUNCNAMES = list_new();
  4585. FILES = list_new();
  4586. REQUIRED = list_new();
  4587. CONSTANTS = list_new();
  4588. list_push(CONSTANTS, table_new());
  4589. MACROS = list_new();
  4590. list_push(MACROS, table_new());
  4591. macro_stk = list_new();
  4592. HBUF = buffer_new();
  4593. MVARS = list_new();
  4594. genmathlib();
  4595. char *out;
  4596. char *main = NULL;
  4597. char *outf = NULL;
  4598. list_t *required = NULL;
  4599. int readstdin = 0;
  4600. for (size_t i = 1; i < argc; i++) {
  4601. if (*argv[i] == '-') {
  4602. if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--debug") == 0)
  4603. DEBUG = 1;
  4604. else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--stdin") == 0)
  4605. readstdin = 1;
  4606. else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--prefix") == 0) {
  4607. if (i + 1 >= argc) {
  4608. fprintf(stderr,
  4609. "fatal: missing argument after '-p/--prefix' parameter\n");
  4610. return 1;
  4611. }
  4612. PREFIX = argv[++i];
  4613. } else if (strcmp(argv[i], "-o") == 0 ||
  4614. strcmp(argv[i], "--output") == 0) {
  4615. if (i + 1 >= argc) {
  4616. fprintf(stderr,
  4617. "fatal: missing argument after '-o/--output' parameter\n");
  4618. return 1;
  4619. }
  4620. outf = argv[++i];
  4621. } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0 ||
  4622. strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-v") == 0 ||
  4623. strcmp(argv[i], "--version") == 0) {
  4624. fprintf(stderr, "qilang compiler, " QIC_VERSION "\n");
  4625. fprintf(
  4626. stderr,
  4627. "usage: %s [-dsh] [-o out.c] [input0.qi input1.qi ... inputN.qi]\n",
  4628. argv[0]);
  4629. fprintf(stderr, "-h --help\tprint this message and exit\n");
  4630. fprintf(stderr, "-d --debug\tenable debug mode\n");
  4631. fprintf(stderr, "-s --stdin\tread stdin as input\n");
  4632. fprintf(stderr,
  4633. "-o --output\toutput generated C code to the specified file\n");
  4634. return 0;
  4635. } else {
  4636. fprintf(stderr, "fatal: unknown commandline argument: '%s'\n", argv[i]);
  4637. return 1;
  4638. }
  4639. continue;
  4640. }
  4641. if (!readstdin && !main)
  4642. main = argv[i];
  4643. else {
  4644. if (!required)
  4645. required = list_new();
  4646. list_push(required, argv[i]);
  4647. }
  4648. }
  4649. if (!PREFIX) {
  4650. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  4651. srand(time(NULL));
  4652. PREFIX = malloc_checked(sizeof(char) * 9);
  4653. PREFIX[8] = 0;
  4654. for (size_t i = 0; i < 8; i++)
  4655. PREFIX[i] =
  4656. chars[(size_t)((double)rand() / RAND_MAX * (sizeof(chars) - 1))];
  4657. }
  4658. if (readstdin || !main)
  4659. out = compile_file("<stdin>", stdin, required);
  4660. else {
  4661. FILE *fd = fopen(main, "rb");
  4662. if (!fd) {
  4663. fprintf(stderr, "fatal: unable to open file: '%s'\n", main);
  4664. return 1;
  4665. }
  4666. list_push(REQUIRED, main);
  4667. out = compile_file(main, fd, required);
  4668. fclose(fd);
  4669. }
  4670. if (outf && strcmp(outf, "-") != 0) {
  4671. FILE *fd = fopen(outf, "wb");
  4672. if (!fd) {
  4673. fprintf(stderr, "fatal: unable to open output file: '%s'\n", outf);
  4674. return 1;
  4675. }
  4676. fwrite(out, sizeof(char), strlen(out), fd);
  4677. fclose(fd);
  4678. } else
  4679. fwrite(out, sizeof(char), strlen(out), stdout);
  4680. return 0;
  4681. }