qic.c 127 KB

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