qic.c 145 KB

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