qic.c 143 KB

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