qic.c 132 KB

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