qic.c 142 KB

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