qic.c 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204
  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_MSET,
  839. N_MSTMT,
  840. N_MEXPR
  841. } tag;
  842. struct _node_t *a;
  843. struct _node_t *b;
  844. struct _node_t *c;
  845. struct _node_t *d;
  846. list_t *l;
  847. list_t *l2;
  848. table_t *h;
  849. table_t *h2;
  850. token_t *t;
  851. token_t *t2;
  852. buffer_t *buf;
  853. size_t fi;
  854. size_t pos;
  855. };
  856. typedef struct _node_t node_t;
  857. node_t *node_pos(node_t *node, size_t fi, size_t pos) {
  858. node->fi = fi;
  859. node->pos = pos;
  860. return node;
  861. }
  862. node_t *node_copy(node_t *node) {
  863. node_t *nnode = malloc_checked(sizeof(node_t));
  864. memcpy(nnode, node, sizeof(node_t));
  865. return nnode;
  866. }
  867. node_t *nodet(int tag, token_t *t) {
  868. node_t *node = malloc_checked(sizeof(node_t));
  869. node->tag = tag;
  870. node->t = t;
  871. return node;
  872. }
  873. #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))
  874. node_t *nodel(int tag, list_t *l) {
  875. node_t *node = malloc_checked(sizeof(node_t));
  876. node->tag = tag;
  877. node->l = l;
  878. return node;
  879. }
  880. #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))
  881. node_t *nodetl(int tag, token_t *t, list_t *l) {
  882. node_t *node = malloc_checked(sizeof(node_t));
  883. node->tag = tag;
  884. node->t = t;
  885. node->l = l;
  886. return node;
  887. }
  888. #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))
  889. node_t *nodeh(int tag, table_t *h) {
  890. node_t *node = malloc_checked(sizeof(node_t));
  891. node->tag = tag;
  892. node->h = h;
  893. return node;
  894. }
  895. #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))
  896. node_t *node0(int tag) {
  897. node_t *node = malloc_checked(sizeof(node_t));
  898. node->tag = tag;
  899. return node;
  900. }
  901. #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))
  902. node_t *node1(int tag, node_t *a) {
  903. node_t *node = malloc_checked(sizeof(node_t));
  904. node->tag = tag;
  905. node->a = a;
  906. return node;
  907. }
  908. #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))
  909. node_t *node1l(int tag, node_t *a, list_t *l) {
  910. node_t *node = malloc_checked(sizeof(node_t));
  911. node->tag = tag;
  912. node->a = a;
  913. node->l = l;
  914. return node;
  915. }
  916. #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))
  917. node_t *node1l2(int tag, node_t *a, list_t *l, list_t *l2) {
  918. node_t *node = malloc_checked(sizeof(node_t));
  919. node->tag = tag;
  920. node->a = a;
  921. node->l = l;
  922. node->l2 = l2;
  923. return node;
  924. }
  925. #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))
  926. node_t *node1t(int tag, node_t *a, token_t *t) {
  927. node_t *node = malloc_checked(sizeof(node_t));
  928. node->tag = tag;
  929. node->a = a;
  930. node->t = t;
  931. return node;
  932. }
  933. #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))
  934. node_t *node2(int tag, node_t *a, node_t *b) {
  935. node_t *node = malloc_checked(sizeof(node_t));
  936. node->tag = tag;
  937. node->a = a;
  938. node->b = b;
  939. return node;
  940. }
  941. #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))
  942. node_t *node2l(int tag, node_t *a, node_t *b, list_t *l) {
  943. node_t *node = malloc_checked(sizeof(node_t));
  944. node->tag = tag;
  945. node->a = a;
  946. node->b = b;
  947. node->l = l;
  948. return node;
  949. }
  950. #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))
  951. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t) {
  952. node_t *node = malloc_checked(sizeof(node_t));
  953. node->tag = tag;
  954. node->a = a;
  955. node->b = b;
  956. node->t = t;
  957. return node;
  958. }
  959. #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))
  960. node_t *node3(int tag, node_t *a, node_t *b, node_t *c) {
  961. node_t *node = malloc_checked(sizeof(node_t));
  962. node->tag = tag;
  963. node->a = a;
  964. node->b = b;
  965. node->c = c;
  966. return node;
  967. }
  968. #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))
  969. node_t *node3t(int tag, node_t *a, node_t *b, node_t *c, token_t *t) {
  970. node_t *node = malloc_checked(sizeof(node_t));
  971. node->tag = tag;
  972. node->a = a;
  973. node->b = b;
  974. node->c = c;
  975. node->t = t;
  976. return node;
  977. }
  978. #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))
  979. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d) {
  980. node_t *node = malloc_checked(sizeof(node_t));
  981. node->tag = tag;
  982. node->a = a;
  983. node->b = b;
  984. node->c = c;
  985. node->d = d;
  986. return node;
  987. }
  988. #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))
  989. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured, node_t *body) {
  990. node_t *node = malloc_checked(sizeof(node_t));
  991. node->tag = tag;
  992. node->t = name;
  993. node->h = params;
  994. node->h2 = captured;
  995. node->a = body;
  996. return node;
  997. }
  998. #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))
  999. node_t *nodeb(buffer_t *buf) {
  1000. node_t *node = malloc_checked(sizeof(node_t));
  1001. node->tag = N_BUFFER;
  1002. node->buf = buf;
  1003. return node;
  1004. }
  1005. typedef struct {
  1006. list_t *params;
  1007. list_t *body;
  1008. int variable;
  1009. } macro_t;
  1010. table_t *MACROS;
  1011. #define LABELLOOP(n)\
  1012. node_t *ln = (n);\
  1013. ln->t2 = label;
  1014. #define AT(tk) (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  1015. #define ATP(tk, p) ((*pos)+p < tokens->length && ((token_t *)tokens->data[(*pos)+p])->tag == T_##tk)
  1016. #define MATCH(tk) (AT(tk) && ++(*pos))
  1017. #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); }
  1018. #define EXPECT(tk, s) { if (!MATCH(tk)) PARSE_ERROR("expected %s", (s)); }
  1019. node_t *parse_expr(list_t *tokens, size_t *pos);
  1020. list_t *parse_sequence(list_t *tokens, size_t *pos, int term) {
  1021. list_t *seq = list_new();
  1022. do {
  1023. if (term != -1 && *pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == term)
  1024. break;
  1025. if (MATCH(STAR))
  1026. list_push(seq, NODE1(STAR, parse_expr(tokens, pos)));
  1027. else
  1028. list_push(seq, parse_expr(tokens, pos));
  1029. } while (MATCH(COMMA));
  1030. return seq;
  1031. }
  1032. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  1033. char *unescape(char *s);
  1034. node_t *parse_primary(list_t *tokens, size_t *pos) {
  1035. if (MATCH(MVAR))
  1036. return NODET(MVAR, tokens->data[(*pos)-1]);
  1037. else if (MATCH(FUNC))
  1038. return parse_func(tokens, pos, 1);
  1039. else if (MATCH(LPAR)) {
  1040. if (MATCH(RPAR))
  1041. return NODE0(NILTUPLE);
  1042. node_t *a = parse_expr(tokens, pos);
  1043. if (MATCH(COMMA)) {
  1044. list_t *l = list_new();
  1045. list_push(l, a);
  1046. if (!AT(RPAR))
  1047. do {
  1048. node_t *n = parse_expr(tokens, pos);
  1049. list_push(l, n);
  1050. } while (MATCH(COMMA));
  1051. a = NODEL(TUPLE, l);
  1052. }
  1053. EXPECT(RPAR, ")");
  1054. return a;
  1055. } else if (MATCH(LSB)) {
  1056. list_t *a = parse_sequence(tokens, pos, T_RSB);
  1057. node_t *loop = NULL;
  1058. node_t *cond = NULL;
  1059. if (MATCH(FOR)) {
  1060. if (MATCH(LSB)) {
  1061. list_t *l = list_new();
  1062. do {
  1063. if(!AT(NAME))
  1064. PARSE_ERROR("expected identifier");
  1065. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1066. } while (MATCH(COMMA));
  1067. EXPECT(RSB, "]");
  1068. EXPECT(OF, "of");
  1069. loop = NODE2l(FOROFUNPACK, parse_expr(tokens, pos), NODEL(LIST, a), l);
  1070. } else {
  1071. if(!AT(NAME))
  1072. PARSE_ERROR("expected identifier");
  1073. token_t *t = tokens->data[(*pos)++];
  1074. EXPECT(OF, "of");
  1075. loop = NODE2t(FOROF, parse_expr(tokens, pos), NODEL(LIST, a), t);
  1076. }
  1077. if (MATCH(IF))
  1078. cond = parse_expr(tokens, pos);
  1079. }
  1080. EXPECT(RSB, "]");
  1081. if (loop)
  1082. return NODE2(LISTGEN, loop, cond);
  1083. return NODEL(LIST, a);
  1084. } else if (MATCH(LCB)) {
  1085. table_t *table = table_new();
  1086. do {
  1087. if (AT(RCB))
  1088. break;
  1089. if (!AT(NAME) && !AT(STRING))
  1090. PARSE_ERROR("expected identifier or string");
  1091. int is_str = AT(STRING);
  1092. char *key = ((token_t *)tokens->data[(*pos)++])->text;
  1093. EXPECT(COLON, ":");
  1094. node_t *val = parse_expr(tokens, pos);
  1095. table_set(table, is_str? unescape(key): key, val);
  1096. } while (MATCH(COMMA));
  1097. EXPECT(RCB, "}");
  1098. return NODEH(TABLE, table);
  1099. } else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(FSTRING) || MATCH(NAME))
  1100. return NODET(LITERAL, tokens->data[(*pos)-1]);
  1101. if (MATCH(RPAR)) {
  1102. PARSE_ERROR("extraneous )");
  1103. } else if (MATCH(RSB)) {
  1104. PARSE_ERROR("extraneous ]");
  1105. } else if (MATCH(RCB)) {
  1106. PARSE_ERROR("extraneous }");
  1107. } else {
  1108. PARSE_ERROR("expected expression");
  1109. }
  1110. return NULL;
  1111. }
  1112. size_t get_lineno(token_t *tok) {
  1113. size_t line, col;
  1114. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  1115. return line;
  1116. }
  1117. #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)])))
  1118. #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])))
  1119. node_t *parse_stmt(list_t *tokens, size_t *pos);
  1120. node_t *parse_call(list_t *tokens, size_t *pos) {
  1121. node_t *a = parse_primary(tokens, pos);
  1122. if (a->tag == N_LITERAL && a->t->tag == T_NAME && !CLIFF && !CLIFF_AHEAD && AT(BANG) && ATP(LPAR, 1)) {
  1123. MATCH(BANG);
  1124. MATCH(LPAR);
  1125. list_t *args = list_new();
  1126. if (!AT(RPAR))
  1127. do {
  1128. node_t *n = parse_stmt(tokens, pos);
  1129. if (n->tag == N_BLOCK)
  1130. n->tag = N_PROGRAM;
  1131. else if (n->tag == N_EXPRSTMT)
  1132. n = n->a;
  1133. list_push(args, n);
  1134. } while(MATCH(COMMA));
  1135. EXPECT(RPAR, ")");
  1136. return NODETL(MACRO_CALL, a->t, args);
  1137. }
  1138. do {
  1139. if (!CLIFF && MATCH(LPAR)) {
  1140. list_t *b = NULL;
  1141. if (!AT(RPAR))
  1142. b = parse_sequence(tokens, pos, -1);
  1143. EXPECT(RPAR, ")");
  1144. a = NODE1l(CALL, a, b);
  1145. continue;
  1146. } else if (!CLIFF && MATCH(LSB)) {
  1147. if (MATCH(COLON)) {
  1148. a = NODE3(SLICE, a, NULL, parse_expr(tokens, pos));
  1149. EXPECT(RSB, "]");
  1150. continue;
  1151. }
  1152. node_t *b = parse_expr(tokens, pos);
  1153. if (MATCH(COLON)) {
  1154. node_t *c = NULL;
  1155. if (!AT(RSB))
  1156. c = parse_expr(tokens, pos);
  1157. EXPECT(RSB, "]");
  1158. a = NODE3(SLICE, a, b, c);
  1159. continue;
  1160. }
  1161. EXPECT(RSB, "]");
  1162. a = NODE2(INDEX, a, b);
  1163. continue;
  1164. } else if (!CLIFF && MATCH(DOT)) {
  1165. if (!AT(NAME))
  1166. PARSE_ERROR("expected identifier after .");
  1167. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  1168. continue;
  1169. }
  1170. break;
  1171. } while (1);
  1172. return a;
  1173. }
  1174. node_t *parse_postfix(list_t *tokens, size_t *pos) {
  1175. node_t *a = parse_call(tokens, pos);
  1176. if (CLIFF)
  1177. return a;
  1178. if (MATCH(PLUSPLUS))
  1179. return NODE1(INC, a);
  1180. else if (MATCH(MINUSMINUS))
  1181. return NODE1(DEC, a);
  1182. return a;
  1183. }
  1184. node_t *parse_unary(list_t *tokens, size_t *pos) {
  1185. if (MATCH(MINUS)) {
  1186. node_t *a = parse_unary(tokens, pos);
  1187. return NODE1(NEGATE, a);
  1188. } else if (MATCH(PLUS)) {
  1189. node_t *a = parse_unary(tokens, pos);
  1190. return NODE1(UNARY_PLUS, a);
  1191. } else if (MATCH(BANG)) {
  1192. node_t *a = parse_unary(tokens, pos);
  1193. return NODE1(NOT, a);
  1194. } else if (MATCH(TILDE)) {
  1195. node_t *a = parse_unary(tokens, pos);
  1196. return NODE1(BNOT, a);
  1197. }
  1198. return parse_postfix(tokens, pos);
  1199. }
  1200. node_t *parse_pow(list_t *tokens, size_t *pos) {
  1201. node_t *a = parse_unary(tokens, pos);
  1202. do {
  1203. if (MATCH(STARSTAR)) {
  1204. node_t *b = parse_unary(tokens, pos);
  1205. a = NODE2(POW, a, b);
  1206. continue;
  1207. }
  1208. break;
  1209. } while (1);
  1210. return a;
  1211. }
  1212. node_t *parse_mul(list_t *tokens, size_t *pos) {
  1213. node_t *a = parse_pow(tokens, pos);
  1214. do {
  1215. if (MATCH(STAR)) {
  1216. node_t *b = parse_pow(tokens, pos);
  1217. a = NODE2(MUL, a, b);
  1218. continue;
  1219. } else if (MATCH(SLASH)) {
  1220. node_t *b = parse_pow(tokens, pos);
  1221. a = NODE2(DIV, a, b);
  1222. continue;
  1223. } else if (MATCH(SLASHSLASH)) {
  1224. node_t *b = parse_pow(tokens, pos);
  1225. a = NODE2(IDIV, a, b);
  1226. continue;
  1227. } else if (MATCH(PERCENT)) {
  1228. node_t *b = parse_pow(tokens, pos);
  1229. a = NODE2(MOD, a, b);
  1230. continue;
  1231. }
  1232. break;
  1233. } while (1);
  1234. return a;
  1235. }
  1236. node_t *parse_add(list_t *tokens, size_t *pos) {
  1237. node_t *a = parse_mul(tokens, pos);
  1238. do {
  1239. if (MATCH(PLUS)) {
  1240. node_t *b = parse_mul(tokens, pos);
  1241. a = NODE2(ADD, a, b);
  1242. continue;
  1243. } else if (MATCH(MINUS)) {
  1244. node_t *b = parse_mul(tokens, pos);
  1245. a = NODE2(SUB, a, b);
  1246. continue;
  1247. }
  1248. break;
  1249. } while (1);
  1250. return a;
  1251. }
  1252. node_t *parse_shift(list_t *tokens, size_t *pos) {
  1253. node_t *a = parse_add(tokens, pos);
  1254. do {
  1255. if (MATCH(LTLT)) {
  1256. node_t *b = parse_add(tokens, pos);
  1257. a = NODE2(SHL, a, b);
  1258. continue;
  1259. } else if (MATCH(GTGT)) {
  1260. node_t *b = parse_add(tokens, pos);
  1261. a = NODE2(SHR, a, b);
  1262. continue;
  1263. }
  1264. break;
  1265. } while (1);
  1266. return a;
  1267. }
  1268. node_t *parse_relation(list_t *tokens, size_t *pos) {
  1269. node_t *a = parse_shift(tokens, pos);
  1270. do {
  1271. if (MATCH(LT)) {
  1272. node_t *b = parse_shift(tokens, pos);
  1273. a = NODE2(LT, a, b);
  1274. continue;
  1275. } else if (MATCH(GT)) {
  1276. node_t *b = parse_shift(tokens, pos);
  1277. a = NODE2(GT, a, b);
  1278. continue;
  1279. } else if (MATCH(LE)) {
  1280. node_t *b = parse_shift(tokens, pos);
  1281. a = NODE2(LE, a, b);
  1282. continue;
  1283. } else if (MATCH(GE)) {
  1284. node_t *b = parse_shift(tokens, pos);
  1285. a = NODE2(GE, a, b);
  1286. continue;
  1287. }
  1288. break;
  1289. } while (1);
  1290. return a;
  1291. }
  1292. node_t *parse_equality(list_t *tokens, size_t *pos) {
  1293. node_t *a = parse_relation(tokens, pos);
  1294. do {
  1295. if (MATCH(EQUALS)) {
  1296. node_t *b = parse_relation(tokens, pos);
  1297. a = NODE2(EQUALS, a, b);
  1298. continue;
  1299. } else if (MATCH(NOTEQUALS)) {
  1300. node_t *b = parse_relation(tokens, pos);
  1301. a = NODE2(NOTEQUALS, a, b);
  1302. continue;
  1303. } else if (MATCH(IS)) {
  1304. node_t *b = parse_relation(tokens, pos);
  1305. a = NODE2(IS, a, b);
  1306. continue;
  1307. } else if (AT(BANG) && ATP(IS, 1)) {
  1308. EXPECT(BANG, "!");
  1309. EXPECT(IS, "is");
  1310. node_t *b = parse_relation(tokens, pos);
  1311. a = NODE2(NOTIS, a, b);
  1312. continue;
  1313. } else if (MATCH(IN)) {
  1314. node_t *b = parse_relation(tokens, pos);
  1315. a = NODE2(IN, a, b);
  1316. continue;
  1317. } else if (AT(BANG) && ATP(IN, 1)) {
  1318. EXPECT(BANG, "!");
  1319. EXPECT(IN, "in");
  1320. node_t *b = parse_relation(tokens, pos);
  1321. a = NODE2(NOTIN, a, b);
  1322. continue;
  1323. }
  1324. break;
  1325. } while (1);
  1326. return a;
  1327. }
  1328. node_t *parse_bitand(list_t *tokens, size_t *pos) {
  1329. node_t *a = parse_equality(tokens, pos);
  1330. while (MATCH(AND)) {
  1331. node_t *b = parse_equality(tokens, pos);
  1332. a = NODE2(BAND, a, b);
  1333. }
  1334. return a;
  1335. }
  1336. node_t *parse_bitxor(list_t *tokens, size_t *pos) {
  1337. node_t *a = parse_bitand(tokens, pos);
  1338. while (MATCH(RAISE)) {
  1339. node_t *b = parse_bitand(tokens, pos);
  1340. a = NODE2(XOR, a, b);
  1341. }
  1342. return a;
  1343. }
  1344. node_t *parse_bitor(list_t *tokens, size_t *pos) {
  1345. node_t *a = parse_bitxor(tokens, pos);
  1346. while (MATCH(BAR)) {
  1347. node_t *b = parse_bitxor(tokens, pos);
  1348. a = NODE2(BOR, a, b);
  1349. }
  1350. return a;
  1351. }
  1352. node_t *parse_logand(list_t *tokens, size_t *pos) {
  1353. node_t *a = parse_bitor(tokens, pos);
  1354. if (MATCH(ANDAND)) {
  1355. node_t *b = parse_logand(tokens, pos);
  1356. return NODE2(LOGAND, a, b);
  1357. }
  1358. return a;
  1359. }
  1360. node_t *parse_logor(list_t *tokens, size_t *pos) {
  1361. node_t *a = parse_logand(tokens, pos);
  1362. if (MATCH(BARBAR)) {
  1363. node_t *b = parse_logor(tokens, pos);
  1364. return NODE2(LOGOR, a, b);
  1365. }
  1366. return a;
  1367. }
  1368. node_t *parse_assignment(list_t *tokens, size_t *pos);
  1369. node_t *parse_conditional(list_t *tokens, size_t *pos) {
  1370. node_t *a = parse_logor(tokens, pos);
  1371. if (MATCH(QM)) {
  1372. node_t *b = parse_assignment(tokens, pos);
  1373. EXPECT(COLON, ":");
  1374. node_t *c = parse_assignment(tokens, pos);
  1375. return NODE3(IFEXPR, a, b, c);
  1376. }
  1377. return a;
  1378. }
  1379. node_t *parse_assignment(list_t *tokens, size_t *pos) {
  1380. node_t *a = parse_conditional(tokens, pos);
  1381. if (MATCH(ASSIGN)) {
  1382. node_t *b = parse_assignment(tokens, pos);
  1383. return NODE2(ASSIGN, a, b);
  1384. } else if (MATCH(PLUSASSIGN)) {
  1385. node_t *b = parse_assignment(tokens, pos);
  1386. return NODE2(ASSIGN_ADD, a, b);
  1387. } else if (MATCH(MINUSASSIGN)) {
  1388. node_t *b = parse_assignment(tokens, pos);
  1389. return NODE2(ASSIGN_SUB, a, b);
  1390. } else if (MATCH(STARASSIGN)) {
  1391. node_t *b = parse_assignment(tokens, pos);
  1392. return NODE2(ASSIGN_MUL, a, b);
  1393. } else if (MATCH(SLASHASSIGN)) {
  1394. node_t *b = parse_assignment(tokens, pos);
  1395. return NODE2(ASSIGN_DIV, a, b);
  1396. } else if (MATCH(SLASHSLASHASSIGN)) {
  1397. node_t *b = parse_assignment(tokens, pos);
  1398. return NODE2(ASSIGN_IDIV, a, b);
  1399. } else if (MATCH(PERCENTASSIGN)) {
  1400. node_t *b = parse_assignment(tokens, pos);
  1401. return NODE2(ASSIGN_MOD, a, b);
  1402. } else if (MATCH(STARSTARASSIGN)) {
  1403. node_t *b = parse_assignment(tokens, pos);
  1404. return NODE2(ASSIGN_POW, a, b);
  1405. } else if (MATCH(BARASSIGN)) {
  1406. node_t *b = parse_assignment(tokens, pos);
  1407. return NODE2(ASSIGN_BOR, a, b);
  1408. } else if (MATCH(ANDASSIGN)) {
  1409. node_t *b = parse_assignment(tokens, pos);
  1410. return NODE2(ASSIGN_BAND, a, b);
  1411. } else if (MATCH(RAISEASSIGN)) {
  1412. node_t *b = parse_assignment(tokens, pos);
  1413. return NODE2(ASSIGN_XOR, a, b);
  1414. } else if (MATCH(LTLTASSIGN)) {
  1415. node_t *b = parse_assignment(tokens, pos);
  1416. return NODE2(ASSIGN_SHL, a, b);
  1417. } else if (MATCH(GTGTASSIGN)) {
  1418. node_t *b = parse_assignment(tokens, pos);
  1419. return NODE2(ASSIGN_SHR, a, b);
  1420. }
  1421. return a;
  1422. }
  1423. node_t *parse_expr(list_t *tokens, size_t *pos) {
  1424. return parse_assignment(tokens, pos);
  1425. }
  1426. node_t *parse_block(list_t *tokens, size_t *pos) {
  1427. EXPECT(LCB, "{");
  1428. list_t *stmts = list_new();
  1429. while (!AT(EOF) && !AT(RCB)) {
  1430. list_push(stmts, parse_stmt(tokens, pos));
  1431. MATCH(SEMI);
  1432. }
  1433. EXPECT(RCB, "}");
  1434. return NODEL(PROGRAM, stmts);
  1435. }
  1436. #define BLOCK() (CLIFF||MATCH(COLON)?parse_stmt(tokens, pos):parse_block(tokens, pos))
  1437. #define STMT_OR_BLOCK() (MATCH(COLON)?parse_stmt(tokens, pos):AT(LCB)?parse_block(tokens, pos):parse_stmt(tokens, pos))
  1438. node_t *parse_if(list_t *tokens, size_t *pos) {
  1439. node_t *a = parse_expr(tokens, pos);
  1440. node_t *b = BLOCK();
  1441. node_t *c = NULL;
  1442. if (MATCH(ELSE))
  1443. c = STMT_OR_BLOCK();
  1444. else if (MATCH(ELIF))
  1445. c = parse_if(tokens, pos);
  1446. return NODE3(IF, a, b, c);
  1447. }
  1448. node_t *parse_var(list_t *tokens, size_t *pos, int is_let) {
  1449. table_t *h = table_new();
  1450. do {
  1451. if(!AT(NAME))
  1452. PARSE_ERROR("expected identifier");
  1453. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1454. node_t *v = NULL;
  1455. if (is_let) {
  1456. EXPECT(ASSIGN, "=");
  1457. v = parse_expr(tokens, pos);
  1458. } else if (MATCH(ASSIGN))
  1459. v = parse_expr(tokens, pos);
  1460. table_set(h, k, v);
  1461. } while (MATCH(COMMA));
  1462. if (is_let)
  1463. return NODEH(LET, h);
  1464. return NODEH(VAR, h);
  1465. }
  1466. node_t *parse_unpack(list_t *tokens, size_t *pos, int tag) {
  1467. EXPECT(LSB, "[");
  1468. list_t *l = list_new();
  1469. do {
  1470. if(!AT(NAME))
  1471. PARSE_ERROR("expected identifier");
  1472. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1473. } while (MATCH(COMMA));
  1474. EXPECT(RSB, "]");
  1475. EXPECT(ASSIGN, "=");
  1476. node_t *a = parse_expr(tokens, pos);
  1477. if (tag == N_LETUNPACK)
  1478. return NODE1l(LETUNPACK, a, l);
  1479. return NODE1l(VARUNPACK, a, l);
  1480. }
  1481. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr) {
  1482. token_t *name = NULL;
  1483. if (!is_expr) {
  1484. if(!AT(NAME))
  1485. PARSE_ERROR("expected identifier");
  1486. name = tokens->data[(*pos)++];
  1487. }
  1488. table_t *params = NULL;
  1489. if (MATCH(LPAR)) {
  1490. if (!AT(RPAR)) {
  1491. int flag = 0;
  1492. params = table_new();
  1493. size_t argc = 0;
  1494. do {
  1495. if(!AT(NAME))
  1496. PARSE_ERROR("expected identifier");
  1497. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  1498. node_t *r = NULL;
  1499. if (!flag && AT(ASSIGN))
  1500. flag = 1;
  1501. if (flag) {
  1502. EXPECT(ASSIGN, "=");
  1503. r = parse_expr(tokens, pos);
  1504. }
  1505. list_t *pair = list_new();
  1506. size_t *argcp = malloc_checked(sizeof(size_t));
  1507. memcpy(argcp, &argc, sizeof(size_t));
  1508. argc++;
  1509. list_push(pair, argcp);
  1510. list_push(pair, r);
  1511. table_set(params, l, pair);
  1512. } while (MATCH(COMMA));
  1513. }
  1514. EXPECT(RPAR, ")");
  1515. }
  1516. table_t *captured = NULL;
  1517. if (MATCH(USE)) {
  1518. EXPECT(LPAR, "(");
  1519. captured = table_new();
  1520. do {
  1521. if(!AT(NAME))
  1522. PARSE_ERROR("expected identifier");
  1523. token_t *name = tokens->data[(*pos)++];
  1524. table_set(captured, name->text, NODET(LITERAL, name));
  1525. } while (MATCH(COMMA));
  1526. EXPECT(RPAR, ")");
  1527. }
  1528. int colon = AT(COLON);
  1529. node_t *body = !colon && !AT(LCB)? parse_stmt(tokens, pos): BLOCK();
  1530. if (colon && body->tag == N_EXPRSTMT)
  1531. body = NODE1(RETURN, body->a);
  1532. if (is_expr)
  1533. return NODEF(FUNCEXPR, NULL, params, captured, body);
  1534. return NODEF(FUNCDEF, name, params, captured, body);
  1535. }
  1536. node_t *parse_stmt(list_t *tokens, size_t *pos) {
  1537. if (MATCH(LCB)) {
  1538. list_t *stmts = list_new();
  1539. while (!AT(EOF) && !AT(RCB)) {
  1540. node_t *n = parse_stmt(tokens, pos);
  1541. MATCH(SEMI);
  1542. list_push(stmts, n);
  1543. }
  1544. EXPECT(RCB, "}");
  1545. return NODEL(BLOCK, stmts);
  1546. } else if (MATCH(VAR)) {
  1547. if (AT(LSB))
  1548. return parse_unpack(tokens, pos, N_VARUNPACK);
  1549. return parse_var(tokens, pos, 0);
  1550. } else if (MATCH(LET)) {
  1551. if (AT(LSB))
  1552. return parse_unpack(tokens, pos, N_LETUNPACK);
  1553. return parse_var(tokens, pos, 1);
  1554. } else if (MATCH(CONST)) {
  1555. table_t *h = table_new();
  1556. do {
  1557. if(!AT(NAME))
  1558. PARSE_ERROR("expected identifier");
  1559. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1560. if (k[0] != '_' && !(k[0] >= 'A' && k[0] <= 'Z'))
  1561. PARSE_ERROR("compile-time constant identifiers must begin with an uppercase letter or with an underscore, but '%s' does not", k);
  1562. if (table_get(h, k))
  1563. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  1564. EXPECT(ASSIGN, "=");
  1565. node_t *v = parse_expr(tokens, pos);
  1566. table_set(h, k, v);
  1567. } while (MATCH(COMMA));
  1568. return NODEH(CONST, h);
  1569. } else if (MATCH(IF))
  1570. return parse_if(tokens, pos);
  1571. else if (MATCH(SWITCH)) {
  1572. token_t *label = NULL;
  1573. if (MATCH(AT)) {
  1574. if(!AT(NAME))
  1575. PARSE_ERROR("expected identifier");
  1576. label = tokens->data[(*pos)++];
  1577. }
  1578. node_t *a = parse_expr(tokens, pos);
  1579. EXPECT(LCB, "{");
  1580. list_t *cases = list_new();
  1581. int has_default = 0;
  1582. for (;;) {
  1583. if (AT(RCB)) break;
  1584. node_t *expr = NULL;
  1585. list_t *stmts = list_new();
  1586. if (MATCH(DEFAULT)) {
  1587. if (has_default)
  1588. PARSE_ERROR("duplicated default case in switch");
  1589. has_default = 1;
  1590. } else {
  1591. EXPECT(CASE, "case");
  1592. expr = parse_expr(tokens, pos);
  1593. }
  1594. MATCH(COLON);
  1595. while (!AT(CASE) && !AT(DEFAULT) && !AT(RCB))
  1596. list_push(stmts, parse_stmt(tokens, pos));
  1597. list_t *pair = list_new();
  1598. list_push(pair, expr);
  1599. list_push(pair, NODEL(PROGRAM, stmts));
  1600. list_push(cases, pair);
  1601. }
  1602. EXPECT(RCB, "}");
  1603. if (!cases->length)
  1604. PARSE_ERROR("empty switch statement");
  1605. LABELLOOP(NODE1l(SWITCH, a, cases));
  1606. return ln;
  1607. } else if (MATCH(FOR)) {
  1608. token_t *label = NULL;
  1609. if (MATCH(AT)) {
  1610. if(!AT(NAME))
  1611. PARSE_ERROR("expected identifier");
  1612. label = tokens->data[(*pos)++];
  1613. }
  1614. node_t *a = NULL;
  1615. node_t *b = NULL;
  1616. node_t *c = NULL;
  1617. if (!AT(LCB) && !AT(COLON) && !CLIFF) {
  1618. if (MATCH(LSB)) {
  1619. list_t *l = list_new();
  1620. do {
  1621. if(!AT(NAME))
  1622. PARSE_ERROR("expected identifier");
  1623. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1624. } while (MATCH(COMMA));
  1625. EXPECT(RSB, "]");
  1626. EXPECT(OF, "of");
  1627. a = parse_expr(tokens, pos);
  1628. b = BLOCK();
  1629. LABELLOOP(NODE2l(FOROFUNPACK, a, b, l));
  1630. return ln;
  1631. }
  1632. if (AT(NAME) && ATP(OF, 1)) {
  1633. token_t *t = tokens->data[(*pos)++];
  1634. EXPECT(OF, "of");
  1635. a = parse_expr(tokens, pos);
  1636. b = BLOCK();
  1637. LABELLOOP(NODE2t(FOROF, a, b, t));
  1638. return ln;
  1639. }
  1640. if (MATCH(VAR)) {
  1641. if (MATCH(LSB)) {
  1642. list_t *l = list_new();
  1643. do {
  1644. if(!AT(NAME))
  1645. PARSE_ERROR("expected identifier");
  1646. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1647. } while (MATCH(COMMA));
  1648. EXPECT(RSB, "]");
  1649. EXPECT(OF, "of");
  1650. a = parse_expr(tokens, pos);
  1651. b = BLOCK();
  1652. LABELLOOP(NODE2l(FOROFVARUNPACK, a, b, l));
  1653. return ln;
  1654. }
  1655. if (AT(NAME) && ATP(OF, 1)) {
  1656. token_t *t = tokens->data[(*pos)++];
  1657. EXPECT(OF, "of");
  1658. a = parse_expr(tokens, pos);
  1659. b = BLOCK();
  1660. LABELLOOP(NODE2t(FOROFVAR, a, b, t));
  1661. return ln;
  1662. }
  1663. a = parse_var(tokens, pos, 0);
  1664. EXPECT(SEMI, ";");
  1665. b = parse_expr(tokens, pos);
  1666. EXPECT(SEMI, ";");
  1667. c = parse_expr(tokens, pos);
  1668. } else a = parse_expr(tokens, pos);
  1669. }
  1670. node_t *d = BLOCK();
  1671. LABELLOOP(NODE4(FOR, a, b, c, d));
  1672. return ln;
  1673. } else if (MATCH(BREAK)) {
  1674. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1675. return NODET(BREAK, tokens->data[(*pos)++]);
  1676. return NODE0(BREAK);
  1677. } else if (MATCH(CONTINUE)) {
  1678. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1679. return NODET(CONTINUE, tokens->data[(*pos)++]);
  1680. return NODE0(CONTINUE);
  1681. } else if (MATCH(FUNC))
  1682. return parse_func(tokens, pos, 0);
  1683. else if (MATCH(RETURN)) {
  1684. node_t *a = NULL;
  1685. if (!AT(RCB) && !AT(EOF) && !CLIFF)
  1686. a = parse_expr(tokens, pos);
  1687. return NODE1(RETURN, a);
  1688. } else if (MATCH(DEFER)) {
  1689. node_t *a;
  1690. if (AT(LCB))
  1691. a = BLOCK();
  1692. else a = parse_stmt(tokens, pos);
  1693. return NODE1(DEFER, a);
  1694. } else if (MATCH(PASS)) return NODE0(PASS);
  1695. else if (MATCH(TRY)) {
  1696. node_t *a = BLOCK();
  1697. token_t *t = NULL;
  1698. EXPECT(CATCH, "catch");
  1699. if (!AT(COLON) && !AT(LCB) && !CLIFF) {
  1700. if (!AT(NAME))
  1701. PARSE_ERROR("expected identifier");
  1702. t = tokens->data[(*pos)++];
  1703. }
  1704. node_t *b = BLOCK();
  1705. node_t *c = NULL;
  1706. if (MATCH(FINALLY))
  1707. c = BLOCK();
  1708. return NODE3t(TRY, a, b, c, t);
  1709. } else if (MATCH(THROW)) {
  1710. node_t *a = NULL;
  1711. if (!CLIFF && !AT(COMMA) && !AT(RPAR) && !AT(RCB))
  1712. a = parse_expr(tokens, pos);
  1713. return NODE1(THROW, a);
  1714. } else if (MATCH(GOTO)) {
  1715. if(!AT(NAME))
  1716. PARSE_ERROR("expected identifier");
  1717. token_t *t = tokens->data[(*pos)++];
  1718. return NODET(GOTO, t);
  1719. } else if (AT(NAME) && ATP(COLON, 1) && !CLIFF_AHEAD) {
  1720. token_t *t = tokens->data[(*pos)++];
  1721. EXPECT(COLON, ":");
  1722. return NODET(LABEL, t);
  1723. } else if (MATCH(CLASS)) {
  1724. if(!AT(NAME))
  1725. PARSE_ERROR("expected identifier");
  1726. token_t *t = tokens->data[(*pos)++];
  1727. list_t *l = NULL;
  1728. if (MATCH(LPAR)) {
  1729. l = list_new();
  1730. do {
  1731. if(!AT(NAME))
  1732. PARSE_ERROR("expected identifier");
  1733. token_t *t = tokens->data[(*pos)++];
  1734. list_push(l, t);
  1735. } while (MATCH(COMMA));
  1736. EXPECT(RPAR, ")");
  1737. }
  1738. EXPECT(LCB, "{");
  1739. list_t *triples = list_new();
  1740. for (;;) {
  1741. int is_out = 0;
  1742. int is_static = 0;
  1743. if (AT(RCB))
  1744. break;
  1745. if (MATCH(LET))
  1746. is_out = 1;
  1747. else if (MATCH(CONST))
  1748. is_static = 1;
  1749. if (!AT(NAME))
  1750. PARSE_ERROR("expected identifier");
  1751. list_t *triple = list_new();
  1752. token_t *t = tokens->data[(*pos)++];
  1753. list_push(triple, t);
  1754. int *flagp = malloc_checked(sizeof(int));
  1755. int flag = is_static? 2: is_out? 1: 0;
  1756. memcpy(flagp, &flag, sizeof(int));
  1757. if (MATCH(ASSIGN)) {
  1758. list_push(triple, flagp);
  1759. list_push(triple, parse_expr(tokens, pos));
  1760. } else {
  1761. list_push(triple, flagp);
  1762. list_push(triple, parse_func(tokens, pos, 1));
  1763. }
  1764. list_push(triples, triple);
  1765. }
  1766. EXPECT(RCB, "}");
  1767. list_t *pair = list_new();
  1768. list_push(pair, l);
  1769. list_push(pair, triples);
  1770. return NODETL(CLASS, t, pair);
  1771. } else if (MATCH(DEL)) {
  1772. node_t *a = parse_expr(tokens, pos);
  1773. return NODE1(DEL, a);
  1774. } else if (MATCH(INLINE)) {
  1775. if (!AT(STRING))
  1776. PARSE_ERROR("expected string");
  1777. token_t *t = tokens->data[(*pos)++];
  1778. return NODET(INLINE, t);
  1779. }
  1780. return NODE1(EXPRSTMT, parse_expr(tokens, pos));
  1781. }
  1782. #define ATM(t) (AT(MVAR) && strcmp(((token_t *)tokens->data[*pos])->text, t) == 0)
  1783. #define MATCHM(t) (ATM(t) && MATCH(MVAR))
  1784. node_t *parse_mexpr(list_t *tokens, size_t *pos);
  1785. node_t *parse_mprimary(list_t *tokens, size_t *pos) {
  1786. if (MATCH(STAR))
  1787. return NODET(LITERAL, token(T_NAME, strdup("*")));
  1788. else if (MATCH(LPAR)) {
  1789. node_t *a = parse_mexpr(tokens, pos);
  1790. EXPECT(RPAR, ")");
  1791. return a;
  1792. } else if (MATCH(NAME)) {
  1793. token_t *t = tokens->data[(*pos)-1];
  1794. int macro = 0;
  1795. if (!CLIFF && !CLIFF_AHEAD && AT(BANG) && ATP(LPAR, 1)) {
  1796. MATCH(BANG);
  1797. macro = 1;
  1798. }
  1799. if (!CLIFF && MATCH(LPAR)) {
  1800. list_t *args = list_new();
  1801. if (!AT(RPAR))
  1802. do {
  1803. list_push(args, parse_mexpr(tokens, pos));
  1804. } while (MATCH(COMMA));
  1805. EXPECT(RPAR, ")");
  1806. if (macro)
  1807. return NODETL(MACRO_CALL, t, args);
  1808. return NODETL(CALL, t, args);
  1809. }
  1810. return NODET(LITERAL, t);
  1811. } else if (MATCH(NUMBER) || MATCH(STRING))
  1812. return NODET(LITERAL, tokens->data[(*pos)-1]);
  1813. PARSE_ERROR("expected m-expression");
  1814. return NULL;
  1815. }
  1816. node_t *parse_mexpr(list_t *tokens, size_t *pos) {
  1817. if (MATCH(MINUS)) {
  1818. node_t *a = parse_mexpr(tokens, pos);
  1819. return NODE1(NEGATE, a);
  1820. }
  1821. node_t *a = parse_mprimary(tokens, pos);
  1822. do {
  1823. if (MATCH(BAR)) {
  1824. node_t *b = parse_mprimary(tokens, pos);
  1825. a = NODE2(LOGOR, a, b);
  1826. continue;
  1827. } else if (MATCH(AND)) {
  1828. node_t *b = parse_mprimary(tokens, pos);
  1829. a = NODE2(LOGAND, a, b);
  1830. continue;
  1831. } else if (MATCH(PLUS)) {
  1832. node_t *b = parse_mprimary(tokens, pos);
  1833. a = NODE2(ADD, a, b);
  1834. continue;
  1835. } else if (MATCH(MINUS)) {
  1836. node_t *b = parse_mprimary(tokens, pos);
  1837. a = NODE2(SUB, a, b);
  1838. continue;
  1839. } else if (MATCH(STAR)) {
  1840. node_t *b = parse_mprimary(tokens, pos);
  1841. a = NODE2(MUL, a, b);
  1842. continue;
  1843. } else if (MATCH(ASSIGN)) {
  1844. node_t *b = parse_mprimary(tokens, pos);
  1845. a = NODE2(EQUALS, a, b);
  1846. continue;
  1847. }
  1848. break;
  1849. } while (1);
  1850. return a;
  1851. }
  1852. node_t *parse_mstmt(list_t *tokens, size_t *pos);
  1853. node_t *parse_mif(list_t *tokens, size_t *pos, int sub) {
  1854. node_t *a = parse_mexpr(tokens, pos);
  1855. list_t *l = list_new();
  1856. list_t *l2 = NULL;
  1857. while (!AT(EOF) && !ATM("else") && !ATM("elif") && !ATM("endif"))
  1858. list_push(l, parse_mstmt(tokens, pos));
  1859. if (MATCHM("elif")) {
  1860. l2 = list_new();
  1861. list_push(l2, parse_mif(tokens, pos, 1));
  1862. } else if (MATCHM("else")) {
  1863. l2 = list_new();
  1864. while (!AT(EOF) && !ATM("endif"))
  1865. list_push(l2, parse_mstmt(tokens, pos));
  1866. }
  1867. if (!sub && !MATCHM("endif"))
  1868. PARSE_ERROR("expected $endif");
  1869. return NODE1l2(MIF, a, l, l2);
  1870. }
  1871. node_t *parse_mstmt(list_t *tokens, size_t *pos) {
  1872. if (MATCHM("if"))
  1873. return parse_mif(tokens, pos, 0);
  1874. else if (MATCHM("for")) {
  1875. node_t *a = parse_mexpr(tokens, pos);
  1876. list_t *l = list_new();
  1877. while (!AT(EOF) && !ATM("endfor"))
  1878. list_push(l, parse_mstmt(tokens, pos));
  1879. if (!MATCHM("endfor"))
  1880. PARSE_ERROR("expected $endfor");
  1881. return NODE1l(MFOR, a, l);
  1882. } else if (MATCHM("set")) {
  1883. if(!AT(NAME))
  1884. PARSE_ERROR("expected identifier");
  1885. token_t *t = tokens->data[(*pos)++];
  1886. node_t *a = parse_mexpr(tokens, pos);
  1887. return NODE1t(MSET, a, t);
  1888. } else if (MATCHM("$")) {
  1889. node_t *a = parse_stmt(tokens, pos);
  1890. if (a->tag == N_EXPRSTMT)
  1891. a = a->a;
  1892. return NODE1(MSTMT, a);
  1893. } else if (MATCHM("{")) {
  1894. list_t *stmts = list_new();
  1895. while (!AT(EOF) && !ATM("}")) {
  1896. list_push(stmts, parse_stmt(tokens, pos));
  1897. MATCH(SEMI);
  1898. }
  1899. if (!MATCHM("}"))
  1900. PARSE_ERROR("expected }$");
  1901. return NODE1(MSTMT, nodel(N_PROGRAM, stmts));
  1902. } else if (MATCHM(":"))
  1903. return NODE1(MEXPR, parse_mexpr(tokens, pos));
  1904. PARSE_ERROR("expected m-statement");
  1905. return NULL;
  1906. }
  1907. node_t *parse_program(list_t *tokens, size_t *pos) {
  1908. if (AT(EOF))
  1909. PARSE_ERROR("empty program");
  1910. list_t *stmts = list_new();
  1911. int flag = 0;
  1912. while (!AT(EOF) && *pos < tokens->length) {
  1913. node_t *n = NULL;
  1914. if (MATCH(REQUIRE)) {
  1915. if (flag)
  1916. PARSE_ERROR("misplaced require statement")
  1917. list_t *paths = list_new();
  1918. do {
  1919. if (!AT(STRING))
  1920. PARSE_ERROR("expected string");
  1921. list_push(paths, tokens->data[(*pos)++]);
  1922. } while (MATCH(COMMA));
  1923. n = NODEL(REQUIRE, paths);
  1924. } else if (MATCH(HEADER)) {
  1925. if (flag)
  1926. PARSE_ERROR("misplaced header statement")
  1927. if (!AT(STRING))
  1928. PARSE_ERROR("expected string");
  1929. token_t *text = tokens->data[(*pos)++];
  1930. n = NODET(HEADER, text);
  1931. } else if (MATCH(INCLUDE)) {
  1932. if (flag)
  1933. PARSE_ERROR("misplaced include statement")
  1934. if (!AT(STRING))
  1935. PARSE_ERROR("expected string");
  1936. token_t *text = tokens->data[(*pos)++];
  1937. n = NODET(INCLUDE, text);
  1938. } else if (MATCH(MACRO)) {
  1939. if(!AT(NAME))
  1940. PARSE_ERROR("expected identifier");
  1941. char *name = ((token_t *)tokens->data[(*pos)++])->text;
  1942. EXPECT(LPAR, "(");
  1943. int variable = 0;
  1944. list_t *params = list_new();
  1945. if (!AT(RPAR)) {
  1946. if (MATCH(STAR))
  1947. variable = 1;
  1948. else
  1949. do {
  1950. if(!AT(NAME))
  1951. PARSE_ERROR("expected identifier");
  1952. list_push(params, tokens->data[(*pos)++]);
  1953. } while (MATCH(COMMA));
  1954. }
  1955. EXPECT(RPAR, ")");
  1956. list_t *body = list_new();
  1957. if (MATCH(COLON) || !AT(LCB))
  1958. list_push(body, parse_mstmt(tokens, pos));
  1959. else {
  1960. EXPECT(LCB, "{");
  1961. while (!AT(EOF) && !AT(RCB))
  1962. list_push(body, parse_mstmt(tokens, pos));
  1963. EXPECT(RCB, "}");
  1964. }
  1965. list_t *ms = table_get(MACROS, name);
  1966. if (!ms) {
  1967. ms = list_new();
  1968. table_set(MACROS, name, ms);
  1969. }
  1970. macro_t *m = malloc_checked(sizeof(macro_t));
  1971. m->params = params;
  1972. m->body = body;
  1973. m->variable = variable;
  1974. list_push(ms, m);
  1975. } else { n = parse_stmt(tokens, pos); flag = 1; }
  1976. MATCH(SEMI);
  1977. if (n)
  1978. list_push(stmts, n);
  1979. }
  1980. return NODEL(TOPLEVEL, stmts);
  1981. }
  1982. node_t *parse(char *source) {
  1983. size_t pos = 0;
  1984. return parse_program(tokenize(source), &pos);
  1985. }
  1986. #define NEWGID() size_t gid = GID++
  1987. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  1988. #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(")"); }
  1989. #define UNOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); EMIT(")"); }
  1990. #define ASSIGNIN(buf, lhs, rhs) {\
  1991. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) {\
  1992. buffer_fmt(buf, "qi_set(state, false, \"%s\", ", (lhs)->t->text);\
  1993. rhs;\
  1994. buffer_fmt(buf, ")");\
  1995. } else if ((lhs)->tag == N_INDEX) {\
  1996. buffer_fmt(buf, "qi_index_set(state, false, ");\
  1997. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a);\
  1998. buffer_fmt(buf, ", ");\
  1999. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->b);\
  2000. buffer_fmt(buf, ", ");\
  2001. rhs;\
  2002. buffer_fmt(buf, ")");\
  2003. } else if ((lhs)->tag == N_MEMBER) {\
  2004. buffer_fmt(buf, "qi_index_set(state, false, ");\
  2005. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a);\
  2006. buffer_fmt(buf, ", qi_make_string(state, \"%s\"), ", (lhs)->t->text);\
  2007. rhs;\
  2008. buffer_fmt(buf, ")");\
  2009. } else COMPILE_ERROR("illegal assignment left-hand side");\
  2010. }
  2011. #define ASSIGN(lhs, rhs) ASSIGNIN(buf, lhs, rhs)
  2012. #define COMPASSIGN(lhs, s, rhs) {\
  2013. ASSIGN(node->a, {\
  2014. EMIT("qi_%s(state, ", s);\
  2015. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs));\
  2016. EMIT(", ");\
  2017. rhs;\
  2018. EMIT(")");\
  2019. });\
  2020. }
  2021. #define COMPILE_ERROR(fmt, ...) { format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, ##__VA_ARGS__); exit(1); }
  2022. 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);
  2023. char *tempvar() {
  2024. NEWGID();
  2025. char *s = malloc_checked(sizeof(char) * (64 + strlen(PREFIX)));
  2026. snprintf(s, 64 + strlen(PREFIX), "__%s%zu", PREFIX, gid);
  2027. return s;
  2028. }
  2029. 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) {
  2030. if (!seq || seq->length < 1) {
  2031. EMIT("NULL");
  2032. return;
  2033. }
  2034. int has_star = 0;
  2035. for (size_t i = 0; i < seq->length; i++)
  2036. if (((node_t *)seq->data[i])->tag == N_STAR) {
  2037. has_star = 1; break;
  2038. }
  2039. buffer_t *tbuf = buffer_new();
  2040. NEWGID();
  2041. buffer_fmt(tbuf, "inline static qi_list_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  2042. if (has_star)
  2043. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  2044. else
  2045. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make_n(%d);\n", seq->length);
  2046. for (size_t i = 0; i < seq->length; i++) {
  2047. node_t *node = seq->data[i];
  2048. if (!has_star) {
  2049. buffer_fmt(tbuf, "qi_list_data(list, %d) = ", i);
  2050. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  2051. buffer_fmt(tbuf, ";\n");
  2052. continue;
  2053. }
  2054. if (node->tag == N_STAR) {
  2055. char *varname = tempvar();
  2056. buffer_fmt(tbuf, "qi_value_t *%s = qi_iter(state, ", varname);
  2057. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2058. buffer_fmt(tbuf, ");\n");
  2059. buffer_fmt(tbuf, "for (qi_size_t i = 0; i < %s->value.list->length; i++)\n", varname);
  2060. buffer_fmt(tbuf, "qi_list_push(list, qi_index(state, %s, qi_make_number(state, i)));\n", varname);
  2061. } else {
  2062. buffer_fmt(tbuf, "qi_list_push(list, ");
  2063. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  2064. buffer_fmt(tbuf, ");\n");
  2065. }
  2066. }
  2067. buffer_fmt(tbuf, "return list;\n");
  2068. buffer_fmt(tbuf, "}\n");
  2069. buffer_appendb(gbuf, tbuf);
  2070. EMIT("__%s%d(state)", PREFIX, gid);
  2071. }
  2072. 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) {
  2073. if (!table || table->used < 1) {
  2074. EMIT("NULL");
  2075. return;
  2076. }
  2077. buffer_t *tbuf = buffer_new();
  2078. NEWGID();
  2079. buffer_fmt(tbuf, "inline static qi_table_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  2080. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  2081. table_iterate(table, {
  2082. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  2083. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, entry.value);
  2084. buffer_fmt(tbuf, ");\n");
  2085. });
  2086. buffer_fmt(tbuf, "return table;\n");
  2087. buffer_fmt(tbuf, "}\n");
  2088. buffer_appendb(gbuf, tbuf);
  2089. EMIT("__%s%d(state)", PREFIX, gid);
  2090. }
  2091. #define CTXPUSH(s) list_push(ctx, (s))
  2092. #define CTXPOP() list_pop(ctx)
  2093. int in_context(list_t *ctx, char *s) {
  2094. if (!ctx->length)
  2095. return 0;
  2096. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2097. if (strcmp(ctx->data[i], "gap") == 0)
  2098. break;
  2099. else if (strcmp(ctx->data[i], s) == 0)
  2100. return 1;
  2101. }
  2102. return 0;
  2103. }
  2104. int in_switch(list_t *ctx) {
  2105. if (!ctx->length)
  2106. return 0;
  2107. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2108. if (strcmp(ctx->data[i], "gap") == 0 || strcmp(ctx->data[i], "for") == 0)
  2109. break;
  2110. else if (strcmp(ctx->data[i], "switch") == 0)
  2111. return 1;
  2112. }
  2113. return 0;
  2114. }
  2115. size_t count_ctxs(list_t *ctx, char *s) {
  2116. if (!ctx->length)
  2117. return 0;
  2118. size_t k = 0;
  2119. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  2120. if (strcmp(ctx->data[i], "gap") == 0)
  2121. break;
  2122. else if (strcmp(ctx->data[i], s) == 0)
  2123. k++;
  2124. }
  2125. return k;
  2126. }
  2127. list_t *CONSTANTS;
  2128. #define INCTX(s) (in_context(ctx, (s)))
  2129. #define SCOPESK (count_ctxs(ctx, "scope"))
  2130. #define TRAPSK (count_ctxs(ctx, "trap"))
  2131. #define LPUSH(i) stack_push(lstk, (i))
  2132. #define LPOP() stack_pop(lstk)
  2133. #define LID (lstk->data[lstk->length-1])
  2134. #define SPUSH(i) stack_push(sstk, (i))
  2135. #define SPOP() stack_pop(sstk)
  2136. #define SID (sstk->data[sstk->length-1])
  2137. #define LBPUSH() list_push(lbl, table_new())
  2138. #define LBPOP() list_pop(lbl)
  2139. size_t insert_debug(node_t *node) {
  2140. size_t line;
  2141. (void)traverse(GETSRC(node->fi), node->pos, &line, NULL);
  2142. buffer_t *tbuf = buffer_new();
  2143. buffer_fmt(tbuf, "File \"%s\", line %d", GETFNAME(node->fi), line);
  2144. if (FUNCNAMES->length)
  2145. buffer_fmt(tbuf, ", in %s", list_index(FUNCNAMES, -1));
  2146. list_push(DEBUGDATA, buffer_read(tbuf));
  2147. return DEBUGDATA->length - 1;
  2148. }
  2149. void emit_debug(buffer_t *buf, node_t *node) {
  2150. buffer_fmt(buf, "state->_debug_data = __debugData[%d];\n", insert_debug(node));
  2151. }
  2152. 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) {
  2153. NEWGID();
  2154. char *funname = name? name: node->t? node->t->text: "<anon>";
  2155. buffer_t *tbuf = buffer_new();
  2156. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state, qi_size_t pargc, qi_list_t *pargs) {\n", PREFIX, gid);
  2157. LBPUSH();
  2158. CTXPUSH("gap");
  2159. CTXPUSH("func");
  2160. list_push(CONSTANTS, table_new());
  2161. list_push(FUNCNAMES, funname);
  2162. if (DEBUG) emit_debug(tbuf, node);
  2163. size_t optargc = 0;
  2164. if (node->h) {
  2165. table_iterate(node->h, {
  2166. list_t *pair = entry.value;
  2167. size_t argc = *(size_t *)pair->data[0];
  2168. if (pair->data[1]) {
  2169. optargc++;
  2170. buffer_fmt(tbuf, "qi_decl(state, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ", entry.key, argc+1, argc);
  2171. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  2172. buffer_fmt(tbuf, ");\n");
  2173. } else
  2174. buffer_fmt(tbuf, "qi_decl(state, \"%s\", qi_list_index(pargs, %d));\n", entry.key, argc);
  2175. argc++;
  2176. });
  2177. }
  2178. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl, node->a);
  2179. list_pop(FUNCNAMES);
  2180. list_pop(CONSTANTS);
  2181. CTXPOP();
  2182. CTXPOP();
  2183. LBPOP();
  2184. buffer_fmt(tbuf, "return state->nil;\n");
  2185. buffer_fmt(tbuf, "}\n");
  2186. buffer_appendb(gbuf, tbuf);
  2187. tbuf = buffer_new();
  2188. buffer_fmt(tbuf, "qi_make_function(state, \"%s\", %d, __%s%d, ", funname, !node->h? 0: (node->h->used - optargc), PREFIX, gid);
  2189. compile_table(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->h2);
  2190. buffer_fmt(tbuf, ")");
  2191. if (node->tag == N_FUNCEXPR) {
  2192. buffer_appendb(buf, tbuf);
  2193. return;
  2194. }
  2195. EMIT("qi_set(state, false, \"%s\", ", node->t->text);
  2196. buffer_appendb(buf, tbuf);
  2197. EMIT(");");
  2198. }
  2199. int const_set(char *name, node_t *val) {
  2200. table_t *table = list_index(CONSTANTS, -1);
  2201. if (table_get(table, name))
  2202. return 0;
  2203. table_set(table, name, val);
  2204. return 1;
  2205. }
  2206. node_t *const_get(char *name) {
  2207. node_t *val = NULL;
  2208. for (ssize_t i = CONSTANTS->length-1; i >= 0; i--)
  2209. if ((val = table_get(CONSTANTS->data[i], name)))
  2210. break;
  2211. return val;
  2212. }
  2213. 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) {
  2214. for (size_t i = 0; i < block->length; i++) {
  2215. node_t *node = block->data[i];
  2216. if (node->tag == N_CONST) {
  2217. table_iterate(node->h, {
  2218. char *name = entry.key;
  2219. if (!const_set(name, entry.value))
  2220. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  2221. });
  2222. } else if (node->tag == N_FUNCDEF) {
  2223. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  2224. EMIT("\n");
  2225. } else if (node->tag == N_CLASS) {
  2226. NEWGID();
  2227. char *name = node->t->text;
  2228. list_t *supers = list_index(node->l, 0);
  2229. list_t *triples = list_index(node->l, 1);
  2230. buffer_t *tbuf = buffer_new();
  2231. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  2232. buffer_fmt(tbuf, "qi_list_t *supers = qi_list_make_n(%d);\n", !supers? 0: supers->length);
  2233. if (supers)
  2234. for (size_t i = 0; i < supers->length; i++) {
  2235. token_t *t = supers->data[i];
  2236. buffer_fmt(tbuf, "qi_list_data(supers, %d) = qi_get(state, \"%s\");\n", i, t->text);
  2237. }
  2238. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  2239. buffer_fmt(tbuf, "qi_table_t *metatable = qi_table_make();\n");
  2240. buffer_fmt(tbuf, "qi_table_t *statictable = qi_table_make();\n");
  2241. for (size_t i = 0; i < triples->length; i++) {
  2242. list_t *triple = triples->data[i];
  2243. token_t *t = triple->data[0];
  2244. int flag = *(int *)triple->data[1];
  2245. if (flag == 0) {
  2246. buffer_fmt(tbuf, "qi_table_set(metatable, \"%s\", ", t->text);
  2247. if (((node_t *)triple->data[2])->tag == N_FUNCEXPR) {
  2248. buffer_t *methodname = buffer_new();
  2249. buffer_fmt(methodname, "%s.%s", name, t->text);
  2250. compile_func(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2], buffer_read(methodname));
  2251. } else compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2]);
  2252. } else {
  2253. buffer_fmt(tbuf, "qi_table_set(%s, \"%s\", ", flag == 1? "table": "statictable", t->text);
  2254. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2]);
  2255. }
  2256. buffer_fmt(tbuf, ");\n");
  2257. }
  2258. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(5);\n");
  2259. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = qi_make_string(state, \"%s\");\n", name);
  2260. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = qi_make_list(state, supers);\n");
  2261. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = qi_make_table(state, table);\n");
  2262. buffer_fmt(tbuf, "qi_list_data(pargs, 3) = qi_make_table(state, metatable);\n");
  2263. buffer_fmt(tbuf, "qi_list_data(pargs, 4) = qi_make_table(state, statictable);\n");
  2264. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, \"__class_wrapper\"), pargs);\n");
  2265. buffer_fmt(tbuf, "}\n");
  2266. buffer_appendb(gbuf, tbuf);
  2267. EMIT("qi_set(state, false, \"%s\", __%s%d(state));", name, PREFIX, gid);
  2268. } else if (node->tag == N_LABEL) {
  2269. char *label = node->t->text;
  2270. if (table_get(list_index(lbl, -1), label))
  2271. COMPILE_ERROR("duplicated label: '%s'", label);
  2272. NEWGID();
  2273. size_t *n = malloc_checked(sizeof(size_t));
  2274. memcpy(n, &gid, sizeof(size_t));
  2275. table_set(list_index(lbl, -1), label, n);
  2276. }
  2277. }
  2278. for (size_t i = 0; i < block->length; i++) {
  2279. node_t *n = block->data[i];
  2280. if (n->tag == N_CONST || n->tag == N_FUNCDEF || n->tag == N_CLASS || n->tag == N_PASS)
  2281. continue;
  2282. if (DEBUG) emit_debug(buf, n);
  2283. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  2284. EMIT("\n");
  2285. }
  2286. }
  2287. const char *STD[][2] = {
  2288. {"utf8",
  2289. "func utf8_chrlen(s) {\n"
  2290. " s = bytes(s)\n"
  2291. " var z = len(s)\n"
  2292. " if z < 2\n"
  2293. " return z\n"
  2294. " var l = 1\n"
  2295. " for var i = 1; i < z && (s[i] & 0xc0) == 0x80; i++\n"
  2296. " l++\n"
  2297. " return l\n"
  2298. "}\n"
  2299. "func utf8_decode(s) {\n"
  2300. " s = bytes(s)\n"
  2301. " var l = utf8_chrlen(s)\n"
  2302. " if !l\n"
  2303. " throw \"malformed sequence\"\n"
  2304. " var c = (s[0] & ((1 << (8 - l)) - 1)) << (l - 1) * 6\n"
  2305. " for var i = 1; i < l; i++\n"
  2306. " c |= (s[i] & 0x3f) << (l - i - 1) * 6\n"
  2307. " return (c, l)\n"
  2308. "}\n"
  2309. "func utf8_encode(c) {\n"
  2310. " if c <= 0x7f\n"
  2311. " return bytes([c & 0xFF])\n"
  2312. " elif c >= 0x80 && c <= 0x7ff\n"
  2313. " return bytes([0xC0 | ((c >> 6) & 0x1f), 0x80 | (c & 0x3f)])\n"
  2314. " elif c >= 0x800 && c <= 0xfff\n"
  2315. " return bytes([0xe0 | ((c >> 12) & 0xf), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  2316. " elif c >= 0x10000 && c <= 0x10ffff\n"
  2317. " return bytes([0xf0 | ((c >> 18) & 0x7), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  2318. " throw \"malformed codepoint\"\n"
  2319. "}\n"
  2320. },
  2321. {"thread",
  2322. "include `pthread.h`\n"
  2323. "func thread_create(fn, args=[]) {\n"
  2324. " if type(fn) != \"function\"\n"
  2325. " throw \"expected first argument to be: function, but got: \" + type(fn)\n"
  2326. " if type(args) != \"list\"\n"
  2327. " throw \"expected second argument to be: list, but got: \" + type(args)\n"
  2328. " inline `qi_value_t *args = qi_get(state, \"args\")`\n"
  2329. " inline `qi_list_t *list`\n"
  2330. " inline `LOCKED(args, {list = qi_list_copy(args->value.list);})`\n"
  2331. " inline `void *td = qi_thread_create(state, qi_get(state, \"fn\"), list)`\n"
  2332. " inline `qi_decl(state, \"td\", qi_make_data(state, 'T', td))`\n"
  2333. " return Object({\n"
  2334. " __str: func (this): \"<Thread>\",\n"
  2335. " _td: td,\n"
  2336. " joined: false,\n"
  2337. " join: func (this) {\n"
  2338. " if this.joined\n"
  2339. " return\n"
  2340. " var td = this._td\n"
  2341. " inline `qi_value_t *ret = qi_thread_join(state, qi_get_data(state, 'T', qi_get(state, \"td\")))`\n"
  2342. " this.joined = true\n"
  2343. " inline `return ret`\n"
  2344. " }\n"
  2345. " })\n"
  2346. "}\n"
  2347. "func Thread(fn, args=[]): Object({\n"
  2348. " __str: func (this) use (fn, args): format(\"<Thread _ _>\", fn, args),\n"
  2349. " _thread: nil,\n"
  2350. " start: func (this) use (fn, args) {\n"
  2351. " if this._thread !is nil\n"
  2352. " return\n"
  2353. " this._thread = thread_create(fn, args)\n"
  2354. " return this\n"
  2355. " },\n"
  2356. " join: func (this) {\n"
  2357. " if this._thread !is nil\n"
  2358. " return this._thread.join()\n"
  2359. " },\n"
  2360. " is_joined: func (this): this._thread.joined\n"
  2361. "})\n"
  2362. "func Mutex() {\n"
  2363. " inline `void *mutex = qi_mutex_create()`\n"
  2364. " inline `if (!mutex) qi_throw_format(state, \"mutex init failed\")`\n"
  2365. " inline `qi_decl(state, \"mutex\", qi_make_data(state, 'M', mutex))`\n"
  2366. " return Object({\n"
  2367. " __fin: func (this) {\n"
  2368. " mutex = this._mutex\n"
  2369. " this._mutex = nil\n"
  2370. " inline `qi_mutex_destroy(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2371. " },\n"
  2372. " __str: func (this): \"<Mutex>\",\n"
  2373. " _mutex: mutex,\n"
  2374. " lock: func (this) {\n"
  2375. " var mutex = this._mutex\n"
  2376. " inline `qi_mutex_lock(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2377. " },\n"
  2378. " trylock: func (this) {\n"
  2379. " var mutex = this._mutex\n"
  2380. " inline `return qi_make_boolean(state, qi_mutex_trylock(qi_get_data(state, 'M', qi_get(state, \"mutex\"))))`\n"
  2381. " },\n"
  2382. " unlock: func (this) {\n"
  2383. " var mutex = this._mutex\n"
  2384. " inline `qi_mutex_unlock(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2385. " }\n"
  2386. " })\n"
  2387. "}\n"
  2388. "func Cond() {\n"
  2389. " inline `void *cond = qi_cond_create()`\n"
  2390. " inline `if (!cond) qi_throw_format(state, \"cond init failed\")`\n"
  2391. " inline `qi_decl(state, \"cond\", qi_make_data(state, 'C', cond))`\n"
  2392. " return Object({\n"
  2393. " __fin: func (this) {\n"
  2394. " cond = this._cond\n"
  2395. " this._cond = nil\n"
  2396. " inline `qi_cond_destroy(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2397. " },\n"
  2398. " __str: func (this): \"<Cond>\",\n"
  2399. " _cond: cond,\n"
  2400. " wait: func (this, mutex) {\n"
  2401. " var cond = this._cond\n"
  2402. " mutex = mutex._mutex\n"
  2403. " inline `qi_cond_wait(qi_get_data(state, 'C', qi_get(state, \"cond\")), qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2404. " },\n"
  2405. " signal: func (this) {\n"
  2406. " var cond = this._cond\n"
  2407. " inline `qi_cond_signal(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2408. " },\n"
  2409. " broadcast: func (this) {\n"
  2410. " var cond = this._cond\n"
  2411. " inline `qi_cond_broadcast(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2412. " }\n"
  2413. " })\n"
  2414. "}\n"
  2415. "func thread_exit(ret=nil)\n"
  2416. " inline `qi_thread_exit(state, qi_get(state, \"ret\"))`\n"
  2417. "func is_main_thread()\n"
  2418. " inline `return qi_make_boolean(state, qi_thread_main())`\n"
  2419. },
  2420. {"os",
  2421. "header `#ifdef _WIN32`\n"
  2422. "include `Windows.h`\n"
  2423. "header `#endif`\n"
  2424. "func getenv(n) {\n"
  2425. " if type(n) != \"string\"\n"
  2426. " throw \"expected first argument to be: string, but got: \" + type(n)\n"
  2427. " inline `char *value = getenv(qi_get(state, \"n\")->value.string)`\n"
  2428. " inline `return value? qi_make_string_copy(state, value): state->nil`\n"
  2429. "}\n"
  2430. "func setenv(n, v) {\n"
  2431. " if type(n) != \"string\"\n"
  2432. " throw \"expected first argument to be: string, but got: \" + type(n)\n"
  2433. " v = str(v)\n"
  2434. " inline \"#ifdef _WIN32\"\n"
  2435. " var s = n + \"=\" + v\n"
  2436. " inline `_putenv(qi_get(state, \"s\")->value.string)`\n"
  2437. " inline \"#else\"\n"
  2438. " inline `setenv(qi_get(state, \"n\")->value.string, qi_get(state, \"v\")->value.string, 1)`\n"
  2439. " inline \"#endif\"\n"
  2440. "}\n"
  2441. "func exit(c) {\n"
  2442. " if type(c) != \"number\"\n"
  2443. " throw \"expected first argument to be: number, but got: \" + type(c)\n"
  2444. " inline `qi_exit(state, qi_get(state, \"c\")->value.number)`\n"
  2445. "}\n"
  2446. "func die(msg, c=1) {\n"
  2447. " fputs(STDERR, str(msg) + \"\\n\")\n"
  2448. " exit(c)\n"
  2449. "}\n"
  2450. },
  2451. {"string",
  2452. "let STR_LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2453. "let STR_ASCII_LC = \"abcdefghijklmnopqrstuvwxyz\"\n"
  2454. "let STR_ASCII_UC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2455. "let STR_DIGITS = \"0123456789\"\n"
  2456. "let STR_WS = \" \\t\\n\\r\\x0b\\x0c\"\n"
  2457. "let STR_PUNCTS = \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"\n"
  2458. "func is_char(c): return type(c) == \"string\" && len(c) == 1\n"
  2459. "func isalpha(c): return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')\n"
  2460. "func isdigit(c): return c >= '0' && c <= '9'\n"
  2461. "func ispunct(c): return c in STR_PUNCTS\n"
  2462. "func isws(c): return c in STR_WS\n"
  2463. },
  2464. {"time",
  2465. "include `time.h`\n"
  2466. "include `errno.h`\n"
  2467. "header `#ifdef _WIN32`\n"
  2468. "include `Windows.h`\n"
  2469. "header `#endif`\n"
  2470. "func time() {\n"
  2471. " inline `unsigned long long ts = time(NULL)`\n"
  2472. " inline `return qi_make_number(state, ts)`\n"
  2473. "}\n"
  2474. "func strftime(f, t=time()) {\n"
  2475. " if type(f) != \"string\"\n"
  2476. " throw \"expected first argument to be: string, but got: \" + type(f)\n"
  2477. " if type(t) != \"number\"\n"
  2478. " throw \"expected second argument to be: number, but got: \" + type(t)\n"
  2479. " inline `time_t ts = qi_get(state, \"t\")->value.number`\n"
  2480. " inline `struct tm lt`\n"
  2481. " inline `lt = *localtime(&ts)`\n"
  2482. " inline `char buffer[512]`\n"
  2483. " inline `strftime(buffer, sizeof(buffer), qi_get(state, \"f\")->value.string, &lt)`\n"
  2484. " inline `return qi_make_string_copy(state, buffer)`\n"
  2485. "}\n"
  2486. "func usleep(t) {\n"
  2487. " if type(t) != \"number\"\n"
  2488. " throw \"expected first argument to be: number, but got: \" + type(t)\n"
  2489. " \n"
  2490. " inline `#ifdef _WIN32`\n"
  2491. " inline `Sleep((unsigned long)(qi_get(state, \"t\")->value.number))`\n"
  2492. " inline `#else`\n"
  2493. " inline `unsigned long ms = (unsigned long)(qi_get(state, \"t\")->value.number)`\n"
  2494. " inline `struct timespec ts`\n"
  2495. " inline `ts.tv_sec = ms / 1000`\n"
  2496. " inline `ts.tv_nsec = (ms % 1000) * 1000000`\n"
  2497. " inline `struct timespec r`\n"
  2498. " inline `while (nanosleep(&ts, &r) < 0) if (errno == EINTR) ts = r; else break`\n"
  2499. " inline `#endif`\n"
  2500. "}\n"
  2501. "func sleep(t)\n"
  2502. " usleep(t * 1000)\n"
  2503. },
  2504. {"random",
  2505. "func rand() {\n"
  2506. " inline `return qi_make_number(state, rand())`\n"
  2507. "}\n"
  2508. "func random_int(min, max): return rand() % (max + 1 - min) + min\n"
  2509. "func random_choice(l, k=1) {\n"
  2510. " l = list_copy(list(l))\n"
  2511. " var r = []\n"
  2512. " for var i = 0; i < k; i++\n"
  2513. " list_push(r, list_pop_at(l, random_int(0, len(l)-1)))\n"
  2514. " return r\n"
  2515. "}\n"
  2516. "func random_pick(l, k=1) {\n"
  2517. " var r = []\n"
  2518. " for var i = 0; i < k; i++\n"
  2519. " list_push(r, l[random_int(0, len(l)-1)])\n"
  2520. " return r\n"
  2521. "}\n"
  2522. "inline `srand(time(NULL))`\n"
  2523. },
  2524. {"math", NULL},
  2525. {NULL, NULL}
  2526. };
  2527. const struct {
  2528. const char *name;
  2529. const char *fname;
  2530. int arity;
  2531. } MATHFUNCS[] = {
  2532. { "ceil", NULL, 1 },
  2533. { "floor", NULL, 1 },
  2534. { "trunc", NULL, 1 },
  2535. { "round", NULL, 1 },
  2536. { "abs", "fabs", 1 },
  2537. { "exp", NULL, 1 },
  2538. { "sqrt", NULL, 1 },
  2539. { "sinh", NULL, 1 },
  2540. { "cosh", NULL, 1 },
  2541. { "tanh", NULL, 1 },
  2542. { "asinh", NULL, 1 },
  2543. { "acosh", NULL, 1 },
  2544. { "atanh", NULL, 1 },
  2545. { "sin", NULL, 1 },
  2546. { "cos", NULL, 1 },
  2547. { "tan", NULL, 1 },
  2548. { "asin", NULL, 1 },
  2549. { "acos", NULL, 1 },
  2550. { "atan", NULL, 1 },
  2551. { "atan2", NULL, 2 },
  2552. { "hypot", NULL, 2 },
  2553. { NULL, 0 }
  2554. };
  2555. void genmathlib(void) {
  2556. buffer_t *buffer = buffer_new();
  2557. buffer_appends(buffer, "let Math = {\"tau\": 6.283185307179586, \"pi\": 3.141592653589793, \"e\": 2.718281828459045, \"inf\": INFINITY, \"nan\": NAN, ");
  2558. for (size_t i = 0; MATHFUNCS[i].name; i++) {
  2559. if (MATHFUNCS[i].arity == 0)
  2560. buffer_fmt(buffer, "\"%s\": func () { inline `return qi_make_number(state, %s())` }", MATHFUNCS[i].name, MATHFUNCS[i].fname? MATHFUNCS[i].fname: MATHFUNCS[i].name);
  2561. else if (MATHFUNCS[i].arity == 1)
  2562. 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);
  2563. else
  2564. 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);
  2565. if (MATHFUNCS[i + 1].name)
  2566. buffer_append(buffer, ',');
  2567. }
  2568. buffer_append(buffer, '}');
  2569. size_t i;
  2570. for (i = 0; strcmp(STD[i][0], "math") != 0; i++) ;
  2571. STD[i][1] = buffer_read(buffer);
  2572. }
  2573. char *unescape(char *s) {
  2574. buffer_t *buf = buffer_new();
  2575. for (size_t i = 0; i < strlen(s); i++) {
  2576. char c = s[i];
  2577. if (c == '\\') {
  2578. char nc = s[i+1];
  2579. if (!nc)
  2580. continue;
  2581. switch (nc) {
  2582. case 'n':
  2583. buffer_append(buf, '\n');
  2584. break;
  2585. default:
  2586. buffer_append(buf, nc);
  2587. break;
  2588. }
  2589. i++;
  2590. } else buffer_append(buf, c);
  2591. }
  2592. return buffer_read(buf);
  2593. }
  2594. 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);
  2595. 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) {
  2596. char *source = NULL;
  2597. for (size_t i = 0; STD[i][0]; i++) {
  2598. if (strcmp(path, STD[i][0]) == 0) {
  2599. source = (char *)STD[i][1];
  2600. break;
  2601. }
  2602. }
  2603. if (is_required(path))
  2604. return 1;
  2605. if (!source) {
  2606. FILE *fd = fopen(path, "rb");
  2607. if (!fd)
  2608. return -1;
  2609. buffer_t *fbuf = buffer_new();
  2610. for (;;) {
  2611. char line[512];
  2612. if (!fgets(line, sizeof(line), fd))
  2613. break;
  2614. buffer_appends(fbuf, line);
  2615. }
  2616. source = buffer_read(fbuf);
  2617. path = realpath(path, NULL);
  2618. }
  2619. list_t *pair = list_new();
  2620. list_push(pair, path);
  2621. list_push(pair, source);
  2622. list_push(FILES, pair);
  2623. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  2624. list_pop(FILES);
  2625. list_push(REQUIRED, path);
  2626. return 0;
  2627. }
  2628. buffer_t *HBUF;
  2629. list_t *MVARS;
  2630. node_t *YES;
  2631. #define IS_EXPR(n) ((n) && ((node_t *)(n))->tag > N_EXPRS_BEGIN && ((node_t *)(n))->tag < N_EXPRS_END)
  2632. #define IS_NUMBER(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_NUMBER)
  2633. #define TO_DOUBLE(n) (strtod((n)->t->text, NULL))
  2634. #define IS_STRING(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_STRING)
  2635. node_t *make_number(double v) {
  2636. char buf[64];
  2637. snprintf(buf, sizeof(buf), "%g", v);
  2638. return nodet(N_LITERAL, token(T_NUMBER, strdup(buf)));
  2639. }
  2640. node_t *mexpr_negate(node_t *a) {
  2641. if (!IS_NUMBER(a))
  2642. return NULL;
  2643. return make_number(-TO_DOUBLE(a));
  2644. }
  2645. node_t *mexpr_add(node_t *a, node_t *b) {
  2646. if (!IS_NUMBER(a))
  2647. return NULL;
  2648. if (!IS_NUMBER(b))
  2649. return NULL;
  2650. return make_number(TO_DOUBLE(a) + TO_DOUBLE(b));
  2651. }
  2652. node_t *mexpr_sub(node_t *a, node_t *b) {
  2653. if (!IS_NUMBER(a))
  2654. return NULL;
  2655. if (!IS_NUMBER(b))
  2656. return NULL;
  2657. return make_number(TO_DOUBLE(a) - TO_DOUBLE(b));
  2658. }
  2659. node_t *mexpr_mul(node_t *a, node_t *b) {
  2660. if (!IS_NUMBER(a))
  2661. return NULL;
  2662. if (!IS_NUMBER(b))
  2663. return NULL;
  2664. return make_number(TO_DOUBLE(a) * TO_DOUBLE(b));
  2665. }
  2666. node_t *mf_isExpr(list_t *t) {
  2667. if (t->length != 1)
  2668. return NULL;
  2669. node_t *a = t->data[0];
  2670. if (!a)
  2671. return NULL;
  2672. return a->tag > N_EXPRS_BEGIN && a->tag < N_EXPRS_END? YES: NULL;
  2673. }
  2674. node_t *mf_isList(list_t *t) {
  2675. if (t->length != 1)
  2676. return NULL;
  2677. node_t *a = t->data[0];
  2678. if (!a)
  2679. return NULL;
  2680. return a->tag == N_LIST? YES: NULL;
  2681. }
  2682. node_t *mf_newList(list_t *t) {
  2683. for (size_t i = 0; i < t->length; i++)
  2684. if (!IS_EXPR(t->data[i]))
  2685. return NULL;
  2686. return nodel(N_LIST, t);
  2687. }
  2688. node_t *mf_newName(list_t *t) {
  2689. if (t->length != 1)
  2690. return NULL;
  2691. node_t *a = t->data[0];
  2692. if (!IS_STRING(a))
  2693. return NULL;
  2694. char *text = a->t->text;
  2695. if (*text != '_' && !isalpha(*text))
  2696. return NULL;
  2697. for (size_t i = 0; i < strlen(text); i++)
  2698. if (text[i] != '_' && !isdigit(text[i]) && !isalpha(text[i]))
  2699. return NULL;
  2700. return nodet(N_LITERAL, token(T_NAME, text));
  2701. }
  2702. node_t *mf_newVar(list_t *t) {
  2703. if (t->length != 1 && t->length != 2)
  2704. return NULL;
  2705. node_t *a = t->data[0];
  2706. if (!a || a->tag != N_LITERAL || a->t->tag != T_NAME)
  2707. return NULL;
  2708. node_t *b = NULL;
  2709. if (t->length == 2) {
  2710. b = t->data[1];
  2711. if (!IS_EXPR(b))
  2712. return NULL;
  2713. }
  2714. table_t *h = table_new();
  2715. table_set(h, a->t->text, b);
  2716. return nodeh(N_VAR, h);
  2717. }
  2718. node_t *mf_len(list_t *t) {
  2719. if (t->length != 1)
  2720. return NULL;
  2721. node_t *a = t->data[0];
  2722. if (!a)
  2723. return NULL;
  2724. if (a->tag == N_LIST || a->tag == N_TUPLE)
  2725. return make_number(a->l->length);
  2726. return NULL;
  2727. }
  2728. node_t *mf_nth(list_t *t) {
  2729. if (t->length != 2)
  2730. return NULL;
  2731. node_t *a = t->data[0];
  2732. if (!a)
  2733. return NULL;
  2734. node_t *b = t->data[1];
  2735. if (!IS_NUMBER(b))
  2736. return NULL;
  2737. if (a->tag == N_LIST || a->tag == N_TUPLE)
  2738. return list_index(a->l, TO_DOUBLE(b));
  2739. return NULL;
  2740. }
  2741. struct {
  2742. char *name;
  2743. node_t *(*handler)(list_t *);
  2744. } METAFUNCS[] = {
  2745. { "isExpr", mf_isExpr },
  2746. { "isList", mf_isList },
  2747. { "newName", mf_newName },
  2748. { "newList", mf_newList },
  2749. { "newVar", mf_newVar },
  2750. { "len", mf_len },
  2751. { "nth", mf_nth },
  2752. { NULL, NULL }
  2753. };
  2754. macro_t *find_macro(char *name, size_t argc, int *res) {
  2755. list_t *ms = table_get(MACROS, name);
  2756. if (!ms) {
  2757. if (res) *res = 1;
  2758. return NULL;
  2759. }
  2760. macro_t *m = NULL;
  2761. for (size_t i = 0; i < ms->length; i++) {
  2762. macro_t *t = ms->data[i];
  2763. if (t->variable || t->params->length == argc) {
  2764. m = t;
  2765. break;
  2766. }
  2767. }
  2768. if (!m) {
  2769. if (res) *res = 2;
  2770. return NULL;
  2771. }
  2772. if (res) *res = 0;
  2773. return m;
  2774. }
  2775. int mexpr_equals(node_t *a, node_t *b) {
  2776. if (!a && !b) return 1;
  2777. if (!a && b) return 0;
  2778. if (a && !b) return 0;
  2779. if (a->tag != b->tag) return 0;
  2780. switch (a->tag) {
  2781. case N_LITERAL:
  2782. return a->t->tag == b->t->tag && strcmp(a->t->text, b->t->text) == 0;
  2783. default: break;
  2784. }
  2785. return 0;
  2786. }
  2787. node_t *run_macro(macro_t *macro, list_t *args);
  2788. node_t *run_mexpr(node_t *node) {
  2789. switch (node->tag) {
  2790. case N_LITERAL:
  2791. switch (node->t->tag) {
  2792. case T_NAME:
  2793. return table_get(list_index(MVARS, -1), node->t->text);
  2794. case T_NUMBER: case T_STRING:
  2795. return node;
  2796. default:
  2797. COMPILE_ERROR("not yet implemented");
  2798. }
  2799. break;
  2800. case N_CALL: case N_MACRO_CALL: {
  2801. list_t *args = list_new();
  2802. for (size_t i = 0; i < node->l->length; i++)
  2803. list_push(args, run_mexpr(node->l->data[i]));
  2804. if (node->tag == N_MACRO_CALL) {
  2805. macro_t *m = find_macro(node->t->text, args->length, NULL);
  2806. if (!m)
  2807. return NULL;
  2808. return run_macro(m, args);
  2809. }
  2810. for (size_t i = 0; METAFUNCS[i].name; i++)
  2811. if (strcmp(METAFUNCS[i].name, node->t->text) == 0)
  2812. return METAFUNCS[i].handler(args);
  2813. } break;
  2814. case N_LOGOR:
  2815. if (run_mexpr(node->a) || run_mexpr(node->b))
  2816. return YES;
  2817. case N_LOGAND:
  2818. if (run_mexpr(node->a) && run_mexpr(node->b))
  2819. return YES;
  2820. case N_NEGATE: {
  2821. node_t *a = run_mexpr(node->a);
  2822. return mexpr_negate(a);
  2823. }
  2824. case N_ADD: {
  2825. node_t *a = run_mexpr(node->a);
  2826. node_t *b = run_mexpr(node->b);
  2827. return mexpr_add(a, b);
  2828. }
  2829. case N_SUB: {
  2830. node_t *a = run_mexpr(node->a);
  2831. node_t *b = run_mexpr(node->b);
  2832. return mexpr_sub(a, b);
  2833. }
  2834. case N_MUL: {
  2835. node_t *a = run_mexpr(node->a);
  2836. node_t *b = run_mexpr(node->b);
  2837. return mexpr_mul(a, b);
  2838. }
  2839. case N_EQUALS: {
  2840. node_t *a = run_mexpr(node->a);
  2841. node_t *b = run_mexpr(node->b);
  2842. return mexpr_equals(a, b)? YES: NULL;
  2843. }
  2844. default:
  2845. COMPILE_ERROR("not yet implemented");
  2846. }
  2847. return NULL;
  2848. }
  2849. node_t *run_mnode(node_t *node);
  2850. node_t *run_mnodes(list_t *l) {
  2851. node_t *r = NULL;
  2852. for (size_t i = 0; i < l->length; i++)
  2853. if ((r = run_mnode(l->data[i])))
  2854. break;
  2855. return r;
  2856. }
  2857. node_t *run_mnode(node_t *node) {
  2858. node_t *r = NULL;
  2859. switch (node->tag) {
  2860. case N_MIF:
  2861. if (run_mexpr(node->a))
  2862. r = run_mnodes(node->l);
  2863. else if (node->l2)
  2864. r = run_mnodes(node->l2);
  2865. break;
  2866. case N_MFOR:
  2867. while (run_mexpr(node->a))
  2868. if ((r = run_mnodes(node->l))) break;
  2869. break;
  2870. case N_MSET:
  2871. table_set(list_index(MVARS, -1), node->t->text, run_mexpr(node->a));
  2872. break;
  2873. case N_MSTMT:
  2874. r = node->a;
  2875. break;
  2876. case N_MEXPR:
  2877. r = run_mexpr(node->a);
  2878. break;
  2879. default:
  2880. COMPILE_ERROR("not yet implemented");
  2881. }
  2882. return r;
  2883. }
  2884. node_t *run_macro(macro_t *macro, list_t *args) {
  2885. table_t *mvars = list_index(MVARS, -1);
  2886. table_set(mvars, "nil", NULL);
  2887. if (macro->variable)
  2888. table_set(mvars, "*", nodel(N_LIST, args));
  2889. else
  2890. for (size_t i = 0; i < args->length; i++)
  2891. table_set(mvars, ((token_t *)macro->params->data[i])->text, args->data[i]);
  2892. node_t *r = NULL;
  2893. for (size_t i = 0; i < macro->body->length; i++) {
  2894. r = run_mnode(macro->body->data[i]);
  2895. if (r) break;
  2896. }
  2897. return r;
  2898. }
  2899. typedef struct {
  2900. char *mvar;
  2901. int code;
  2902. } mvar_expand_err_t;
  2903. node_t *_expand_mvars(node_t *node, int expr, mvar_expand_err_t *err) {
  2904. if (node->tag == N_LITERAL) return node;
  2905. if (node->tag == N_MVAR) {
  2906. char *name = node->t->text;
  2907. err->mvar = name;
  2908. table_t *mvars = list_index(MVARS, -1);
  2909. if (!table_has(mvars, name)) {
  2910. err->code = 1; return NULL;
  2911. }
  2912. node_t *n = table_get(mvars, name);
  2913. if (n) {
  2914. if (expr && !IS_EXPR(n)) {
  2915. err->code = 2; return NULL;
  2916. }
  2917. if (!expr && IS_EXPR(n))
  2918. n = node1(N_EXPRSTMT, n);
  2919. } else { err->code = 3; return NULL; }
  2920. return n;
  2921. }
  2922. if (node->tag == N_EXPRSTMT) {
  2923. node_t *n = _expand_mvars(node->a, 0, err);
  2924. if (err->code != 0) return NULL;
  2925. if (!IS_EXPR(n))
  2926. return n;
  2927. node = node_copy(node);
  2928. node->a = n;
  2929. return node;
  2930. } else if (node->tag >= N_ADD && node->tag <= N_BAND) {
  2931. node = node_copy(node);
  2932. node->a = _expand_mvars(node->a, 1, err);
  2933. if (err->code != 0) return NULL;
  2934. node->b = _expand_mvars(node->b, 1, err);
  2935. if (err->code != 0) return NULL;
  2936. return node;
  2937. } else if (node->tag == N_PROGRAM || node->tag == N_LIST) {
  2938. node = node_copy(node);
  2939. node->l = list_copy(node->l);
  2940. for (size_t i = 0; i < node->l->length; i++) {
  2941. node_t *n = _expand_mvars(node->l->data[i], node->tag == N_LIST, err);
  2942. if (err->code != 0) return NULL;
  2943. node->l->data[i] = n;
  2944. }
  2945. return node;
  2946. }
  2947. err->code = 4;
  2948. return NULL;
  2949. }
  2950. node_t *expand_mvars(node_t *node, node_t *_node, int expr) {
  2951. mvar_expand_err_t err = {NULL, 0};
  2952. node_t *r = _expand_mvars(node_copy(_node), expr, &err);
  2953. if (err.code == 1) {
  2954. COMPILE_ERROR("undefined macro variable: '%s'", err.mvar);
  2955. } else if (err.code == 2) {
  2956. COMPILE_ERROR("macro variable '%s' expanded to non-expression in expression context", err.mvar);
  2957. } else if (err.code == 3) {
  2958. COMPILE_ERROR("macro variable '%s' expanded to nil", err.mvar);
  2959. } else if (err.code == 4) {
  2960. COMPILE_ERROR("macro variable expansion failed because it is not yet implemented for this context");
  2961. }
  2962. if (!r)
  2963. COMPILE_ERROR("macro variable expansion failed");
  2964. return r;
  2965. }
  2966. 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) {
  2967. size_t argc = node->l->length;
  2968. char *name = node->t->text;
  2969. int res = 0;
  2970. macro_t *m = find_macro(name, argc, &res);
  2971. if (!m) {
  2972. if (res == 1) {
  2973. COMPILE_ERROR("undefined macro: '%s'", name);
  2974. } else {
  2975. COMPILE_ERROR("no %d-param candidate found for macro: '%s'", argc, name);
  2976. }
  2977. }
  2978. list_push(MVARS, table_new());
  2979. node_t *r = run_macro(m, node->l);
  2980. if (r) {
  2981. r = expand_mvars(node, r, expr);
  2982. if (expr && !IS_EXPR(r))
  2983. COMPILE_ERROR("macro '%s' expanded to non-expression in expression context", name);
  2984. if (!expr && IS_EXPR(r))
  2985. r = node1(N_EXPRSTMT, r);
  2986. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, r);
  2987. } else COMPILE_ERROR("macro '%s' expanded to nil", name);
  2988. list_pop(MVARS);
  2989. }
  2990. 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) {
  2991. switch (node->tag) {
  2992. case N_TOPLEVEL: case N_PROGRAM:
  2993. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  2994. break;
  2995. case N_EXPRSTMT:
  2996. if (node->a->tag == N_LITERAL && node->a->t->tag != T_NAME) break;
  2997. else if (node->a->tag == N_MACRO_CALL) {
  2998. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a, 0);
  2999. break;
  3000. }
  3001. EMIT("(void)(");
  3002. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3003. EMIT(");");
  3004. break;
  3005. case N_BLOCK:
  3006. LBPUSH();
  3007. CTXPUSH("scope");
  3008. list_push(CONSTANTS, table_new());
  3009. EMIT("qi_new_scope(state);\n");
  3010. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3011. EMIT("qi_old_scope(state);");
  3012. list_pop(CONSTANTS);
  3013. CTXPOP();
  3014. LBPOP();
  3015. break;
  3016. case N_LITERAL:
  3017. switch (node->t->tag) {
  3018. case T_NUMBER: {
  3019. char *number = node->t->text;
  3020. if (strncmp(number, "0o", 2) == 0 || strncmp(number, "0b", 2) == 0) {
  3021. buffer_t *buf = buffer_new();
  3022. if (number[1] == 'o')
  3023. buffer_fmt(buf, "0%s", number + 2);
  3024. else
  3025. buffer_fmt(buf, "%d", strtol(number + 2, NULL, 2));
  3026. number = buffer_read(buf);
  3027. } else if (number[0] == '0' && number[1] && isdigit(number[1])) {
  3028. size_t i;
  3029. for (i = 0; i < strlen(number); i++)
  3030. if (number[i] != '0' || number[i+1] == '.')
  3031. break;
  3032. number += i;
  3033. }
  3034. EMIT("qi_make_number(state, %s)", number);
  3035. } break;
  3036. case T_STRING:
  3037. if (!*(node->t->text)) {
  3038. EMIT("state->empty_string");
  3039. } else {
  3040. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  3041. }
  3042. break;
  3043. case T_FSTRING: {
  3044. char *text = node->t->text;
  3045. if (!*text) {
  3046. EMIT("state->empty_string");
  3047. break;
  3048. }
  3049. list_t *parts = list_new();
  3050. buffer_t *tbuf = buffer_new();
  3051. for (size_t i = 0; i < strlen(text); i++) {
  3052. char c = text[i];
  3053. if (c == '$' && text[i+1] == '$') {
  3054. buffer_append(tbuf, '$');
  3055. i++;
  3056. continue;
  3057. } else if (c == '$' && text[i+1] == '{') {
  3058. i += 2;
  3059. buffer_t *tbuf2 = buffer_new();
  3060. while (text[i] && text[i] != '}')
  3061. buffer_append(tbuf2, text[i++]);
  3062. if (text[i] != '}') {
  3063. i--;
  3064. buffer_appends(tbuf, "${");
  3065. buffer_appendb(tbuf, tbuf2);
  3066. continue;
  3067. }
  3068. if (tbuf->size > 0)
  3069. list_push(parts, nodeb(tbuf));
  3070. tbuf = buffer_new();
  3071. char *source = buffer_read(tbuf2);
  3072. list_t *pair = list_new();
  3073. buffer_t *fname = buffer_new();
  3074. size_t line, col;
  3075. (void)traverse(GETSRC(node->fi), node->pos, &line, &col);
  3076. buffer_fmt(fname, "<fstring at %s:%zu:%zu>", GETFNAME(node->fi), line, col);
  3077. list_push(pair, buffer_read(fname));
  3078. list_push(pair, source);
  3079. list_push(FILES, pair);
  3080. list_t *tokens = tokenize(source);
  3081. size_t pos = 0;
  3082. node_t *n = parse_expr(tokens, &pos);
  3083. if (pos != tokens->length-1)
  3084. COMPILE_ERROR("unconsumed input in f-expr");
  3085. list_push(parts, n);
  3086. } else buffer_append(tbuf, c);
  3087. }
  3088. if (tbuf->size > 0)
  3089. list_push(parts, nodeb(tbuf));
  3090. tbuf = buffer_new();
  3091. NEWGID();
  3092. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3093. buffer_fmt(tbuf, "qi_value_t *str = state->empty_string;\n");
  3094. for (size_t i = 0; i < parts->length; i++) {
  3095. node_t *part = parts->data[i];
  3096. buffer_fmt(tbuf, "str = qi_add(state, str, ");
  3097. if (part->tag == N_BUFFER)
  3098. buffer_fmt(tbuf, "qi_make_string(state, \"%s\")", buffer_read(part->buf));
  3099. else {
  3100. buffer_fmt(tbuf, "qi_to_string(state, ");
  3101. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, part);
  3102. buffer_fmt(tbuf, ")");
  3103. }
  3104. buffer_fmt(tbuf, ");\n");
  3105. }
  3106. buffer_fmt(tbuf, "return str;\n}\n");
  3107. buffer_appendb(gbuf, tbuf);
  3108. EMIT("__%s%d(state)", PREFIX, gid);
  3109. } break;
  3110. case T_NAME: {
  3111. char *name = node->t->text;
  3112. node_t *n = const_get(name);
  3113. if (n)
  3114. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  3115. else
  3116. EMIT("qi_get(state, \"%s\")", name);
  3117. } break;
  3118. default:
  3119. COMPILE_ERROR("not yet implemented");
  3120. }
  3121. break;
  3122. case N_LIST:
  3123. EMIT("qi_make_list(state, ");
  3124. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3125. EMIT(")");
  3126. break;
  3127. case N_LISTGEN: {
  3128. NEWGID();
  3129. buffer_t *tbuf = buffer_new();
  3130. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3131. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  3132. buffer_t *bbuf = buffer_new();
  3133. if (node->b) {
  3134. buffer_fmt(bbuf, "if (_qi_truthy(state, ");
  3135. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3136. buffer_fmt(bbuf, ")) {\n");
  3137. }
  3138. for (size_t i = 0; i < node->a->b->l->length; i++) {
  3139. buffer_fmt(bbuf, "qi_list_push(list, ");
  3140. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->a->b->l->data[i]);
  3141. buffer_fmt(bbuf, ");\n");
  3142. }
  3143. if (node->b)
  3144. buffer_fmt(bbuf, "}\n");
  3145. node->a->b = nodeb(bbuf);
  3146. node->a->t2 = NULL;
  3147. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3148. buffer_fmt(tbuf, "return qi_make_list(state, list);\n}\n");
  3149. buffer_appendb(gbuf, tbuf);
  3150. EMIT("__%s%d(state)", PREFIX, gid);
  3151. } break;
  3152. case N_TUPLE:
  3153. EMIT("qi_make_tuple(state, ");
  3154. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3155. EMIT(")");
  3156. break;
  3157. case N_NILTUPLE: EMIT("state->empty_tuple"); break;
  3158. case N_TABLE:
  3159. EMIT("qi_make_table(state, ");
  3160. compile_table(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->h);
  3161. EMIT(")");
  3162. break;
  3163. case N_CALL:
  3164. if (DEBUG) {
  3165. EMIT("qi_call_debug(state, ");
  3166. } else {
  3167. EMIT("qi_call(state, ");
  3168. }
  3169. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3170. EMIT(", ");
  3171. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  3172. if (DEBUG)
  3173. buffer_fmt(buf, ", __debugData[%d]", insert_debug(node));
  3174. EMIT(")");
  3175. break;
  3176. case N_MEMBER:
  3177. EMIT("qi_index(state, ");
  3178. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3179. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  3180. break;
  3181. case N_INDEX:
  3182. EMIT("qi_index(state, ");
  3183. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3184. EMIT(", ");
  3185. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3186. EMIT(")");
  3187. break;
  3188. case N_SLICE: {
  3189. NEWGID();
  3190. buffer_t *tbuf = buffer_new();
  3191. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3192. if (node->b && node->c) {
  3193. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  3194. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3195. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3196. buffer_fmt(tbuf, ";\n");
  3197. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  3198. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3199. buffer_fmt(tbuf, ";\n");
  3200. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  3201. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  3202. buffer_fmt(tbuf, ";\n");
  3203. } else if (node->b) {
  3204. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(2);\n");
  3205. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3206. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3207. buffer_fmt(tbuf, ";\n");
  3208. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  3209. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3210. buffer_fmt(tbuf, ";\n");
  3211. } else {
  3212. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  3213. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  3214. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3215. buffer_fmt(tbuf, ";\n");
  3216. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = state->zero;\n");
  3217. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  3218. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  3219. buffer_fmt(tbuf, ";\n");
  3220. }
  3221. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, \"__slice\"), pargs);\n");
  3222. buffer_fmt(tbuf, "}\n");
  3223. buffer_appendb(gbuf, tbuf);
  3224. EMIT("__%s%d(state)", PREFIX, gid);
  3225. } break;
  3226. case N_ASSIGN:
  3227. if (node->a->tag == N_LIST) {
  3228. if (node->a->l->length < 2)
  3229. COMPILE_ERROR("illegal unpack assignment left-hand side");
  3230. NEWGID();
  3231. buffer_t *tbuf = buffer_new();
  3232. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3233. char *varname = tempvar();
  3234. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  3235. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  3236. buffer_fmt(tbuf, ";\n");
  3237. for (size_t i = 0; i < node->a->l->length; i++) {
  3238. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i], buffer_fmt(tbuf, "qi_index(state, %s, qi_make_number(state, %d))", varname, i));
  3239. buffer_fmt(tbuf, ";\n");
  3240. }
  3241. buffer_fmt(tbuf, "return %s;\n}\n", varname);
  3242. buffer_appendb(gbuf, tbuf);
  3243. EMIT("__%s%d(state)", PREFIX, gid);
  3244. break;
  3245. } else if (node->a->tag == N_TUPLE) {
  3246. if (node->a->l->length < 2)
  3247. COMPILE_ERROR("illegal multiple assignment left-hand side");
  3248. if (node->b->tag != N_TUPLE || node->b->l->length < 2 || node->a->l->length != node->b->l->length)
  3249. COMPILE_ERROR("illegal multiple assignment right-hand side");
  3250. NEWGID();
  3251. buffer_t *tbuf = buffer_new();
  3252. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3253. list_t *vals = list_new();
  3254. for (size_t i = 0; i < node->b->l->length; i++) {
  3255. char *varname = tempvar();
  3256. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  3257. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b->l->data[i]);
  3258. buffer_fmt(tbuf, ";\n");
  3259. list_push(vals, varname);
  3260. }
  3261. for (size_t i = 0; i < node->a->l->length; i++) {
  3262. char *varname = vals->data[i];
  3263. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i], buffer_fmt(tbuf, "%s", varname));
  3264. buffer_fmt(tbuf, ";\n");
  3265. }
  3266. buffer_fmt(tbuf, "return %s;\n}\n", vals->data[vals->length-1]);
  3267. buffer_appendb(gbuf, tbuf);
  3268. EMIT("__%s%d(state)", PREFIX, gid);
  3269. break;
  3270. }
  3271. ASSIGN(node->a, compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  3272. break;
  3273. case N_ASSIGN_ADD: COMPASSIGN(node->a, "add", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3274. case N_ASSIGN_SUB: COMPASSIGN(node->a, "sub", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3275. case N_ASSIGN_MUL: COMPASSIGN(node->a, "mul", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3276. case N_ASSIGN_DIV: COMPASSIGN(node->a, "div", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3277. case N_ASSIGN_IDIV: COMPASSIGN(node->a, "idiv", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3278. case N_ASSIGN_MOD: COMPASSIGN(node->a, "mod", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3279. case N_ASSIGN_POW: COMPASSIGN(node->a, "pow", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3280. case N_ASSIGN_BOR: COMPASSIGN(node->a, "bor", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3281. case N_ASSIGN_BAND: COMPASSIGN(node->a, "band", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3282. case N_ASSIGN_XOR: COMPASSIGN(node->a, "xor", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3283. case N_ASSIGN_SHL: COMPASSIGN(node->a, "shl", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3284. case N_ASSIGN_SHR: COMPASSIGN(node->a, "shr", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  3285. case N_INC:
  3286. COMPASSIGN(node->a, "add", EMIT("state->one"));
  3287. break;
  3288. case N_DEC:
  3289. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  3290. break;
  3291. case N_VAR: case N_LET:
  3292. table_iterate(node->h, {
  3293. EMIT("qi_%s(state, \"%s\", ", node->tag == N_LET? "decl_const": "decl", entry.key);
  3294. if (entry.value)
  3295. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, entry.value);
  3296. else EMIT("state->nil");
  3297. EMIT(");\n");
  3298. });
  3299. break;
  3300. case N_VARUNPACK: case N_LETUNPACK: {
  3301. char *varname = tempvar();
  3302. EMIT("qi_value_t *%s = ", varname);
  3303. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3304. EMIT(";\n");
  3305. for (size_t i = 0; i < node->l->length; i++)
  3306. 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);
  3307. } break;
  3308. case N_CONST:break;
  3309. case N_IF:
  3310. EMIT("if (_qi_truthy(state, ");
  3311. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3312. EMIT(")) {\n");
  3313. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3314. if (node->c) {
  3315. EMIT("} else {\n");
  3316. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  3317. }
  3318. EMIT("}");
  3319. break;
  3320. case N_SWITCH: {
  3321. NEWGID();
  3322. if (node->t2) {
  3323. if (table_get(ltab, node->t2->text))
  3324. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  3325. int_stack_t *pair = stack_new();
  3326. stack_push(pair, 1);
  3327. stack_push(pair, gid);
  3328. table_set(ltab, node->t2->text, pair);
  3329. }
  3330. char *varname = tempvar();
  3331. EMIT("qi_value_t *%s = ", varname);
  3332. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3333. EMIT(";\n");
  3334. for (size_t i = 0; i < node->l->length; i++) {
  3335. list_t *pair = node->l->data[i];
  3336. if (!pair->data[0])
  3337. continue;
  3338. char *label = tempvar();
  3339. EMIT("if (_qi_equals(state, %s, ", varname);
  3340. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  3341. EMIT(")) goto %s;\n", label);
  3342. pair->data[0] = label;
  3343. }
  3344. EMIT("goto __default%d;\n", gid);
  3345. SPUSH(gid);
  3346. CTXPUSH("switch");
  3347. for (size_t i = 0; i < node->l->length; i++) {
  3348. list_t *pair = node->l->data[i];
  3349. char *label = pair->data[0];
  3350. node_t *block = pair->data[1];
  3351. if (!label) {
  3352. EMIT("__default%d:;\n", gid);
  3353. } else {
  3354. EMIT("%s:;\n", label);
  3355. }
  3356. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, block);
  3357. }
  3358. CTXPOP();
  3359. SPOP();
  3360. EMIT("__break%d:;\n", gid);
  3361. } break;
  3362. case N_FOR: {
  3363. NEWGID();
  3364. if (node->t2) {
  3365. if (table_get(ltab, node->t2->text))
  3366. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  3367. int_stack_t *pair = stack_new();
  3368. stack_push(pair, 0);
  3369. stack_push(pair, gid);
  3370. table_set(ltab, node->t2->text, pair);
  3371. }
  3372. if (!node->a) {
  3373. EMIT("for (;;) {\n");
  3374. } else if (node->a && !node->b) {
  3375. EMIT("while (_qi_truthy(state, ");
  3376. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3377. EMIT(")) {\n");
  3378. } else {
  3379. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3380. EMIT("while (_qi_truthy(state, ");
  3381. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3382. EMIT(")) {\n");
  3383. }
  3384. LPUSH(gid);
  3385. CTXPUSH("for");
  3386. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->d);
  3387. EMIT("__continue%d:;\n", gid);
  3388. if (node->c) {
  3389. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  3390. EMIT(";\n");
  3391. }
  3392. CTXPOP();
  3393. LPOP();
  3394. EMIT("}\n");
  3395. EMIT("__break%d:;\n", gid);
  3396. } break;
  3397. case N_FOROF: case N_FOROFVAR: case N_FOROFUNPACK: case N_FOROFVARUNPACK: {
  3398. NEWGID();
  3399. if (node->t2) {
  3400. if (table_get(ltab, node->t2->text))
  3401. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  3402. int_stack_t *pair = stack_new();
  3403. stack_push(pair, 0);
  3404. stack_push(pair, gid);
  3405. table_set(ltab, node->t2->text, pair);
  3406. }
  3407. char *varname = tempvar();
  3408. EMIT("qi_value_t *%s = qi_iter(state, ", varname);
  3409. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3410. EMIT(");\n");
  3411. if (node->tag == N_FOROFVAR) {
  3412. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->t->text);
  3413. } else if (node->tag == N_FOROFVARUNPACK) {
  3414. for (size_t i = 0; i < node->l->length; i++)
  3415. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->l->data[i]);
  3416. }
  3417. EMIT("for (qi_size_t length = _qi_length(state, %s), i = 0; i < length; i++) {\n", varname);
  3418. if (node->tag == N_FOROFUNPACK || node->tag == N_FOROFVARUNPACK) {
  3419. for (size_t i = 0; i < node->l->length; i++)
  3420. 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);
  3421. } else
  3422. EMIT("qi_set(state, false, \"%s\", qi_index(state, %s, qi_make_number(state, i)));\n", node->t->text, varname);
  3423. LPUSH(gid);
  3424. CTXPUSH("for");
  3425. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3426. CTXPOP();
  3427. LPOP();
  3428. EMIT("__continue%d:;\n", gid);
  3429. EMIT("}\n");
  3430. EMIT("__break%d:;\n", gid);
  3431. } break;
  3432. case N_BREAK:
  3433. if (!INCTX("for") && !INCTX("switch"))
  3434. COMPILE_ERROR("break outside of a loop or a switch");
  3435. if (node->t) {
  3436. if (node->t->tag == T_NUMBER) {
  3437. unsigned int offset = abs(atoi(node->t->text)) + 1;
  3438. if (offset < 2 || offset > lstk->length)
  3439. COMPILE_ERROR("%d is not a valid break loop offset", offset-1);
  3440. EMIT("goto __break%d;", lstk->data[lstk->length-offset]);
  3441. } else {
  3442. char *label = node->t->text;
  3443. int_stack_t *pair = table_get(ltab, label);
  3444. if (!pair)
  3445. COMPILE_ERROR("undefined loop label: '%s'", label);
  3446. EMIT("goto __break%d;", pair->data[1]);
  3447. }
  3448. break;
  3449. }
  3450. EMIT("goto __break%d;", in_switch(ctx)? SID: LID);
  3451. break;
  3452. case N_CONTINUE:
  3453. if (!INCTX("for"))
  3454. COMPILE_ERROR("continue outside of a loop");
  3455. if (node->t) {
  3456. if (node->t->tag == T_NUMBER) {
  3457. unsigned int offset = abs(atoi(node->t->text)) + 1;
  3458. if (offset < 2 || offset > lstk->length)
  3459. COMPILE_ERROR("%d is not a valid break loop offset", offset-1);
  3460. EMIT("goto __continue%d;", lstk->data[lstk->length-offset]);
  3461. } else {
  3462. char *label = node->t->text;
  3463. int_stack_t *pair = table_get(ltab, label);
  3464. if (pair->data[1])
  3465. COMPILE_ERROR("continue on a switch loop label: '%s'", label);
  3466. if (!pair)
  3467. COMPILE_ERROR("undefined loop label: '%s'", label);
  3468. EMIT("goto __continue%d;", pair->data[1]);
  3469. }
  3470. break;
  3471. }
  3472. EMIT("goto __continue%d;", LID);
  3473. break;
  3474. case N_DEFER: {
  3475. NEWGID();
  3476. buffer_t *tbuf = buffer_new();
  3477. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3478. LBPUSH();
  3479. CTXPUSH("gap");
  3480. list_push(CONSTANTS, table_new());
  3481. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl, node->a);
  3482. list_pop(CONSTANTS);
  3483. CTXPOP();
  3484. LBPOP();
  3485. buffer_fmt(tbuf, "\n}\n");
  3486. buffer_appendb(gbuf, tbuf);
  3487. EMIT("qi_add_defer(state, -1, __%s%d);", PREFIX, gid);
  3488. } break;
  3489. case N_RETURN:
  3490. if (!INCTX("func"))
  3491. COMPILE_ERROR("return outside of a function");
  3492. for (size_t i = 0; i < SCOPESK; i++)
  3493. EMIT("qi_old_scope(state);\n");
  3494. for (size_t i = 0; i < TRAPSK; i++)
  3495. EMIT("qi_unset_trap(state, trap);\n");
  3496. EMIT("return ");
  3497. if (node->a)
  3498. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3499. else EMIT("state->nil");
  3500. EMIT(";");
  3501. break;
  3502. case N_FUNCDEF: break;
  3503. case N_CLASS: break;
  3504. case N_PASS: break;
  3505. case N_DEL:
  3506. EMIT("qi_del(state, ");
  3507. if (node->a->tag == N_INDEX) {
  3508. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  3509. EMIT(", ");
  3510. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->b);
  3511. } else if (node->a->tag == N_MEMBER) {
  3512. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  3513. EMIT(", qi_make_string(state, \"%s\")", node->a->t->text);
  3514. } else COMPILE_ERROR("not a index/member expression");
  3515. EMIT(");");
  3516. break;
  3517. case N_TRY:
  3518. EMIT("qi_try(state, {\n");
  3519. LBPUSH();
  3520. CTXPUSH("gap");
  3521. CTXPUSH("trap");
  3522. compile_node(gbuf, buf, ctx, table_new(), stack_new(), stack_new(), lbl, node->a);
  3523. CTXPOP();
  3524. CTXPOP();
  3525. LBPOP();
  3526. EMIT("}, {\n");
  3527. if (node->t)
  3528. EMIT("qi_decl(state, \"%s\", trap->value);\n", node->t->text);
  3529. LBPUSH();
  3530. CTXPUSH("gap");
  3531. compile_node(gbuf, buf, ctx, table_new(), stack_new(), stack_new(), lbl, node->b);
  3532. CTXPOP();
  3533. LBPOP();
  3534. if (node->c) {
  3535. NEWGID();
  3536. buffer_t *tbuf = buffer_new();
  3537. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  3538. LBPUSH();
  3539. CTXPUSH("gap");
  3540. compile_node(gbuf, tbuf, ctx, table_new(), stack_new(), stack_new(), lbl, node->c);
  3541. CTXPOP();
  3542. LBPOP();
  3543. buffer_fmt(tbuf, "\n}\n");
  3544. buffer_appendb(gbuf, tbuf);
  3545. EMIT("}, __%s%d);\n", PREFIX, gid);
  3546. } else {
  3547. EMIT("}, NULL);\n");
  3548. }
  3549. break;
  3550. case N_THROW:
  3551. EMIT("qi_throw(state, ");
  3552. if (node->a)
  3553. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3554. else {
  3555. EMIT("state->nil");
  3556. }
  3557. EMIT(");");
  3558. break;
  3559. case N_LABEL: {
  3560. size_t *gid = table_get(list_index(lbl, -1), node->t->text);
  3561. EMIT("__label%d:;", *gid);
  3562. } break;
  3563. case N_GOTO: {
  3564. char *label = node->t->text;
  3565. size_t *gid = table_get(list_index(lbl, -1), label);
  3566. if (!gid)
  3567. COMPILE_ERROR("undefined label: '%s'", label);
  3568. EMIT("goto __label%d;", *gid);
  3569. } break;
  3570. case N_REQUIRE:
  3571. for (size_t i = 0; i < node->l->length; i++) {
  3572. token_t *t = node->l->data[i];
  3573. char *path = unescape(t->text);
  3574. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, path) < 0)
  3575. COMPILE_ERROR("'%s' is not a valid file path or a builtin library name", path);
  3576. }
  3577. break;
  3578. case N_IFEXPR:
  3579. EMIT("(_qi_truthy(state, ");
  3580. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3581. EMIT(")? ");
  3582. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3583. EMIT(": ");
  3584. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  3585. EMIT(")");
  3586. break;
  3587. case N_FUNCEXPR:
  3588. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  3589. break;
  3590. case N_EQUALS:
  3591. BINOP("equals");
  3592. break;
  3593. case N_NOTEQUALS:
  3594. BINOP("not_equals");
  3595. break;
  3596. case N_IS:
  3597. BINOP("is");
  3598. break;
  3599. case N_NOTIS:
  3600. BINOP("not_is");
  3601. break;
  3602. case N_IN:
  3603. BINOP("in");
  3604. break;
  3605. case N_NOTIN:
  3606. BINOP("not_in");
  3607. break;
  3608. case N_LT:
  3609. BINOP("lt");
  3610. break;
  3611. case N_GT:
  3612. BINOP("gt");
  3613. break;
  3614. case N_LE:
  3615. BINOP("le");
  3616. break;
  3617. case N_GE:
  3618. BINOP("ge");
  3619. break;
  3620. case N_ADD:
  3621. BINOP("add");
  3622. break;
  3623. case N_SUB:
  3624. BINOP("sub");
  3625. break;
  3626. case N_MUL:
  3627. BINOP("mul");
  3628. break;
  3629. case N_DIV:
  3630. BINOP("div");
  3631. break;
  3632. case N_IDIV:
  3633. BINOP("idiv");
  3634. break;
  3635. case N_MOD:
  3636. BINOP("mod");
  3637. break;
  3638. case N_POW:
  3639. BINOP("pow");
  3640. break;
  3641. case N_SHL:
  3642. BINOP("shl");
  3643. break;
  3644. case N_SHR:
  3645. BINOP("shr");
  3646. break;
  3647. case N_XOR:
  3648. BINOP("xor");
  3649. break;
  3650. case N_BOR:
  3651. BINOP("bor");
  3652. break;
  3653. case N_BAND:
  3654. BINOP("band");
  3655. break;
  3656. case N_LOGOR:
  3657. BINOP("or");
  3658. break;
  3659. case N_LOGAND:
  3660. BINOP("and");
  3661. break;
  3662. case N_NEGATE:
  3663. UNOP("negate");
  3664. break;
  3665. case N_UNARY_PLUS:
  3666. UNOP("unary_plus");
  3667. break;
  3668. case N_NOT:
  3669. UNOP("not");
  3670. break;
  3671. case N_BNOT:
  3672. UNOP("bnot");
  3673. break;
  3674. case N_MACRO_CALL: compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, 1); break;
  3675. case N_MVAR: COMPILE_ERROR("macro variable outside of a macro");
  3676. case N_INLINE: {
  3677. char *text = unescape(node->t->text);
  3678. if (text[0] == '#') {
  3679. EMIT("%s", text);
  3680. } else {
  3681. EMIT("%s;", text);
  3682. }
  3683. } break;
  3684. case N_HEADER: buffer_fmt(HBUF, "%s\n", unescape(node->t->text)); break;
  3685. case N_INCLUDE: buffer_fmt(HBUF, "#include <%s>\n", unescape(node->t->text)); break;
  3686. case N_BUFFER: buffer_appendb(buf, node->buf); break;
  3687. default:
  3688. COMPILE_ERROR("not yet implemented");
  3689. }
  3690. }
  3691. 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) {
  3692. node_t *n = parse(source);
  3693. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  3694. }
  3695. char *escape(char *s) {
  3696. buffer_t *buf = buffer_new();
  3697. while (*s) {
  3698. if (*s == '\\' || *s == '"')
  3699. buffer_append(buf, '\\');
  3700. buffer_append(buf, *s++);
  3701. }
  3702. return buffer_read(buf);
  3703. }
  3704. char *compile(char *source, list_t *required) {
  3705. list_t *ctx = list_new();
  3706. table_t *ltab = table_new();
  3707. int_stack_t *lstk = stack_new();
  3708. int_stack_t *sstk = stack_new();
  3709. list_t *lbl = list_new();
  3710. LBPUSH();
  3711. buffer_t *gbuf = buffer_new();
  3712. buffer_t *buf = buffer_new();
  3713. compile_into("const __QIC = \"" QIC_VERSION "\"", gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  3714. if (required && required->length)
  3715. for (size_t i = 0; i < required->length; i++)
  3716. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, required->data[i]) < 0) {
  3717. fprintf(stderr, "fatal: '%s' is not a valid file path or a builtin library name\n", (char *)required->data[i]);
  3718. exit(1);
  3719. }
  3720. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  3721. buffer_t *rbuf = buffer_new();
  3722. buffer_appends(rbuf, "#include <qirt.h>\n");
  3723. if (DEBUG && DEBUGDATA->length) {
  3724. buffer_fmt(rbuf, "static const char *__debugData[%d] = {\n", DEBUGDATA->length);
  3725. for (size_t i = 0; i < DEBUGDATA->length; i++)
  3726. buffer_fmt(rbuf, "\"%s\",\n", escape(DEBUGDATA->data[i]));
  3727. buffer_fmt(rbuf, "};\n");
  3728. }
  3729. buffer_appendb(rbuf, HBUF);
  3730. buffer_appendb(rbuf, gbuf);
  3731. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  3732. buffer_appends(rbuf, "qi_state_t *state;\n");
  3733. if (DEBUG)
  3734. buffer_appends(rbuf, "qi_state_init_debug(&state);\n");
  3735. else
  3736. buffer_appends(rbuf, "qi_state_init(&state);\n");
  3737. buffer_appends(rbuf, "qi_list_t *args = qi_list_make();\n");
  3738. buffer_appends(rbuf, "for (int i = 0; i < argc; i++)\n");
  3739. buffer_appends(rbuf, " qi_list_push(args, qi_make_string(state, argv[i]));\n");
  3740. buffer_appends(rbuf, "qi_decl_const(state, \"ARGS\", qi_make_list(state, args));\n");
  3741. buffer_appendb(rbuf, buf);
  3742. buffer_appends(rbuf, "qi_old_scope(state);\n");
  3743. buffer_appends(rbuf, "qi_finalize();\n");
  3744. buffer_appends(rbuf, "return 0;\n");
  3745. buffer_appends(rbuf, "}\n");
  3746. return buffer_read(rbuf);
  3747. }
  3748. char *compile_file(char *filename, FILE *fd, list_t *required) {
  3749. buffer_t *buf = buffer_new();
  3750. for (;;) {
  3751. char line[512];
  3752. if (!fgets(line, sizeof(line), fd))
  3753. break;
  3754. buffer_appends(buf, line);
  3755. }
  3756. char *source = buffer_read(buf);
  3757. list_t *pair = list_new();
  3758. list_push(pair, filename);
  3759. list_push(pair, source);
  3760. list_push(FILES, pair);
  3761. char *out = compile(source, required);
  3762. list_pop(FILES);
  3763. return out;
  3764. }
  3765. int main(int argc, char **argv) {
  3766. YES = nodet(N_LITERAL, token(T_STRING, "yes"));
  3767. DEBUGDATA = list_new();
  3768. FUNCNAMES = list_new();
  3769. FILES = list_new();
  3770. REQUIRED = list_new();
  3771. CONSTANTS = list_new();
  3772. list_push(CONSTANTS, table_new());
  3773. HBUF = buffer_new();
  3774. MVARS = list_new();
  3775. MACROS = table_new();
  3776. genmathlib();
  3777. char *out;
  3778. char *main = NULL;
  3779. char *outf = NULL;
  3780. list_t *required = NULL;
  3781. int readstdin = 0;
  3782. for (size_t i = 1; i < argc; i++) {
  3783. if (*argv[i] == '-') {
  3784. if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--debug") == 0)
  3785. DEBUG = 1;
  3786. else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--stdin") == 0)
  3787. readstdin = 1;
  3788. else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--prefix") == 0) {
  3789. if (i+1 >= argc) {
  3790. fprintf(stderr, "fatal: missing argument after '-p/--prefix' parameter\n");
  3791. return 1;
  3792. }
  3793. PREFIX = argv[++i];
  3794. } else if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) {
  3795. if (i+1 >= argc) {
  3796. fprintf(stderr, "fatal: missing argument after '-o/--output' parameter\n");
  3797. return 1;
  3798. }
  3799. outf = argv[++i];
  3800. } 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) {
  3801. fprintf(stderr, "qilang compiler, " QIC_VERSION "\n");
  3802. fprintf(stderr, "usage: %s [-dsh] [-o out.c] [input0.qi input1.qi ... inputN.qi]\n", argv[0]);
  3803. fprintf(stderr, "-h --help\tprint this message and exit\n");
  3804. fprintf(stderr, "-d --debug\tenable debug mode\n");
  3805. fprintf(stderr, "-s --stdin\tread stdin as input\n");
  3806. fprintf(stderr, "-o --output\toutput generated C code to the specified file\n");
  3807. return 0;
  3808. } else {
  3809. fprintf(stderr, "fatal: unknown commandline argument: '%s'\n", argv[i]);
  3810. return 1;
  3811. }
  3812. continue;
  3813. }
  3814. if (!readstdin && !main) main = argv[i];
  3815. else {
  3816. if (!required)
  3817. required = list_new();
  3818. list_push(required, argv[i]);
  3819. }
  3820. }
  3821. if (!PREFIX) {
  3822. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  3823. srand(time(NULL));
  3824. PREFIX = malloc_checked(sizeof(char) * 9);
  3825. PREFIX[8] = 0;
  3826. for (size_t i = 0; i < 8; i++)
  3827. PREFIX[i] = chars[(size_t)((double) rand() / RAND_MAX * (sizeof(chars) - 1))];
  3828. }
  3829. if (readstdin || !main)
  3830. out = compile_file("<stdin>", stdin, required);
  3831. else {
  3832. FILE *fd = fopen(main, "rb");
  3833. if (!fd) {
  3834. fprintf(stderr, "fatal: unable to open file: '%s'\n", main);
  3835. return 1;
  3836. }
  3837. list_push(REQUIRED, main);
  3838. out = compile_file(main, fd, required);
  3839. fclose(fd);
  3840. }
  3841. if (outf && strcmp(outf, "-") != 0) {
  3842. FILE *fd = fopen(outf, "wb");
  3843. if (!fd) {
  3844. fprintf(stderr, "fatal: unable to open output file: '%s'\n", outf);
  3845. return 1;
  3846. }
  3847. fwrite(out, sizeof(char), strlen(out), fd);
  3848. fclose(fd);
  3849. } else
  3850. fwrite(out, sizeof(char), strlen(out), stdout);
  3851. return 0;
  3852. }