qic.c 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178
  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. #include <math.h>
  8. #if defined(_WIN32) || defined(_WIN64)
  9. #define ON_WINDOWS
  10. #include <windows.h>
  11. #undef TRUE
  12. #undef FALSE
  13. #else
  14. #define ON_POSIX
  15. #include <sys/stat.h>
  16. #endif
  17. int is_directory(char *path)
  18. {
  19. #ifdef ON_WINDOWS
  20. DWORD attributes = GetFileAttributesA(path);
  21. if (attributes == INVALID_FILE_ATTRIBUTES)
  22. return 0;
  23. return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  24. #else
  25. struct stat statbuf;
  26. if (stat(path, &statbuf) != 0)
  27. return 0;
  28. return S_ISDIR(statbuf.st_mode);
  29. #endif
  30. }
  31. #ifdef ON_WINDOWS
  32. #define realpath(p, fp) (_fullpath((fp), (p), 0))
  33. #endif
  34. #define __STR0(x) #x
  35. #define __STR1(x) __STR0(x)
  36. #define LIBQIRT_VER 1
  37. #define QIC_VER "qic v1 (libqirt>=" __STR1(LIBQIRT_VER) ") " __DATE__
  38. size_t GID = 0;
  39. char *PREFIX = NULL;
  40. void *malloc_checked(size_t s)
  41. {
  42. void *p = malloc(s);
  43. if (!p)
  44. {
  45. fprintf(stderr, "fatal: out of memory.\n");
  46. abort();
  47. }
  48. memset(p, 0, s);
  49. return p;
  50. }
  51. void *realloc_checked(void *p, size_t s)
  52. {
  53. p = realloc(p, s);
  54. if (!p)
  55. {
  56. fprintf(stderr, "fatal: out of memory.\n");
  57. abort();
  58. }
  59. return p;
  60. }
  61. void *calloc_checked(size_t k, size_t s)
  62. {
  63. void *p = calloc(k, s);
  64. if (!p)
  65. {
  66. fprintf(stderr, "fatal: out of memory.\n");
  67. abort();
  68. }
  69. return p;
  70. }
  71. typedef struct
  72. {
  73. void **data;
  74. size_t length;
  75. } list_t;
  76. list_t *list_new(void)
  77. {
  78. list_t *list = malloc_checked(sizeof(list_t));
  79. list->data = NULL;
  80. list->length = 0;
  81. return list;
  82. }
  83. list_t *list_copy(list_t *list)
  84. {
  85. list_t *nlist = malloc_checked(sizeof(list_t));
  86. nlist->length = list->length;
  87. nlist->data = realloc_checked(nlist->data, nlist->length * sizeof(void *));
  88. memcpy(nlist->data, list->data, nlist->length * sizeof(void *));
  89. return nlist;
  90. }
  91. void list_push(list_t *l, void *v)
  92. {
  93. size_t i = l->length++;
  94. l->data = realloc_checked(l->data, l->length * sizeof(void *));
  95. l->data[i] = v;
  96. }
  97. void *list_pop(list_t *l)
  98. {
  99. if (!l->length)
  100. return NULL;
  101. return l->data[--l->length];
  102. }
  103. void *list_index(list_t *l, ssize_t index)
  104. {
  105. if (!l->length)
  106. return NULL;
  107. if (index < 0)
  108. index += ((ssize_t)l->length);
  109. if (index < 0 || index >= l->length)
  110. return NULL;
  111. return l->data[index];
  112. }
  113. void list_set(list_t *l, ssize_t index, void *v)
  114. {
  115. if (!l->length)
  116. return;
  117. if (index < 0)
  118. index += ((ssize_t)l->length);
  119. if (index < 0 || index >= l->length)
  120. return;
  121. l->data[index] = v;
  122. }
  123. typedef struct
  124. {
  125. size_t *data;
  126. size_t length;
  127. } int_stack_t;
  128. int_stack_t *stack_new(void)
  129. {
  130. int_stack_t *stack = malloc_checked(sizeof(list_t));
  131. stack->data = NULL;
  132. stack->length = 0;
  133. return stack;
  134. }
  135. void stack_push(int_stack_t *l, size_t v)
  136. {
  137. size_t i = l->length++;
  138. l->data = realloc_checked(l->data, l->length * sizeof(size_t));
  139. l->data[i] = v;
  140. }
  141. size_t stack_pop(int_stack_t *l)
  142. {
  143. if (!l->length)
  144. return 0;
  145. return l->data[--l->length];
  146. }
  147. struct entry_t
  148. {
  149. char *key;
  150. void *value;
  151. };
  152. struct table_t
  153. {
  154. struct entry_t *entries;
  155. size_t used;
  156. size_t capacity;
  157. };
  158. typedef struct entry_t entry_t;
  159. typedef struct table_t table_t;
  160. table_t *table_new()
  161. {
  162. table_t *table = malloc_checked(sizeof(table_t));
  163. table->used = 0;
  164. table->capacity = 32;
  165. table->entries = calloc_checked(table->capacity, sizeof(entry_t));
  166. return table;
  167. }
  168. unsigned long ht_hash(const char *key)
  169. {
  170. unsigned long hash = 5381;
  171. int c;
  172. while ((c = *key++))
  173. hash = ((hash << 5) + hash) + c;
  174. return hash;
  175. }
  176. void *table_get(table_t *table, char *key)
  177. {
  178. if (!table->used)
  179. return NULL;
  180. unsigned long hash = ht_hash(key);
  181. size_t index = hash % table->capacity;
  182. size_t i = index;
  183. while (table->entries[i].key)
  184. {
  185. if (strcmp(table->entries[i].key, key) == 0)
  186. return table->entries[i].value;
  187. i++;
  188. if (i >= table->capacity)
  189. i = 0;
  190. if (i == index)
  191. break;
  192. }
  193. return NULL;
  194. }
  195. int table_has(table_t *table, char *key)
  196. {
  197. if (!table->used)
  198. return 0;
  199. unsigned long hash = ht_hash(key);
  200. size_t index = hash % table->capacity;
  201. size_t i = index;
  202. while (table->entries[i].key)
  203. {
  204. if (strcmp(table->entries[i].key, key) == 0)
  205. return 1;
  206. i++;
  207. if (i >= table->capacity)
  208. i = 0;
  209. if (i == index)
  210. break;
  211. }
  212. return 0;
  213. }
  214. static void table_entry_set(entry_t *entries, char *key, void *value,
  215. size_t capacity, size_t *used)
  216. {
  217. unsigned long hash = ht_hash(key);
  218. size_t index = hash % capacity;
  219. size_t i = index;
  220. while (entries[i].key)
  221. {
  222. if (strcmp(entries[i].key, key) == 0)
  223. {
  224. entries[i].value = value;
  225. return;
  226. }
  227. i++;
  228. if (i >= capacity)
  229. i = 0;
  230. if (i == index)
  231. break;
  232. }
  233. if (used)
  234. (*used)++;
  235. entries[i].key = key;
  236. entries[i].value = value;
  237. }
  238. table_t *table_set(table_t *table, char *key, void *value)
  239. {
  240. if (table->used >= table->capacity)
  241. {
  242. size_t capacity = table->capacity + 32;
  243. entry_t *entries = calloc_checked(capacity, sizeof(entry_t));
  244. for (size_t i = 0; i < table->capacity; i++)
  245. {
  246. entry_t entry = table->entries[i];
  247. if (entry.key)
  248. table_entry_set(entries, entry.key, entry.value, capacity, NULL);
  249. }
  250. table->entries = entries;
  251. table->capacity = capacity;
  252. }
  253. table_entry_set(table->entries, key, value, table->capacity, &table->used);
  254. return table;
  255. }
  256. #define table_iterate(table, code) \
  257. { \
  258. if ((table)->used) \
  259. { \
  260. size_t i = 0; \
  261. while (i < (table)->capacity) \
  262. { \
  263. entry_t entry = (table)->entries[i]; \
  264. if (entry.key) \
  265. { \
  266. code; \
  267. } \
  268. i++; \
  269. } \
  270. } \
  271. }
  272. typedef struct
  273. {
  274. char *str;
  275. size_t size;
  276. } buffer_t;
  277. buffer_t *buffer_new(void)
  278. {
  279. buffer_t *buf = malloc_checked(sizeof(buffer_t));
  280. buf->str = NULL;
  281. buf->size = 0;
  282. return buf;
  283. }
  284. void buffer_append(buffer_t *buf, char c)
  285. {
  286. buf->size++;
  287. buf->str = realloc_checked(buf->str, sizeof(char) * buf->size);
  288. buf->str[buf->size - 1] = c;
  289. }
  290. char *buffer_read(buffer_t *buf)
  291. {
  292. if (buf->size == 0 || buf->str[buf->size - 1])
  293. buffer_append(buf, 0);
  294. return buf->str;
  295. }
  296. void buffer_appends(buffer_t *buf, char *s)
  297. {
  298. for (size_t i = 0; i < strlen(s); i++)
  299. buffer_append(buf, s[i]);
  300. }
  301. void buffer_appendb(buffer_t *dst, buffer_t *src)
  302. {
  303. for (size_t i = 0; i < src->size; i++)
  304. buffer_append(dst, src->str[i]);
  305. }
  306. void buffer_fmt(buffer_t *buf, const char *fmt, ...)
  307. {
  308. va_list args;
  309. va_list largs;
  310. va_start(largs, fmt);
  311. va_copy(args, largs);
  312. size_t size = vsnprintf(NULL, 0, fmt, largs) + 1;
  313. char *str = malloc_checked(sizeof(char) * size);
  314. vsnprintf(str, size, fmt, args);
  315. va_end(args);
  316. va_end(largs);
  317. buffer_appends(buf, str);
  318. }
  319. typedef struct
  320. {
  321. enum
  322. {
  323. T_EOF,
  324. T_NUMBER,
  325. T_STRING,
  326. T_FSTRING,
  327. T_USTRING,
  328. T_BSTRING,
  329. T_NAME,
  330. T_TRUE,
  331. T_FALSE,
  332. T_NIL,
  333. T_VAR,
  334. T_LET,
  335. T_CONST,
  336. T_ENUM,
  337. T_IF,
  338. T_ELSE,
  339. T_ELIF,
  340. T_SWITCH,
  341. T_CASE,
  342. T_DEFAULT,
  343. T_FOR,
  344. T_OF,
  345. T_BREAK,
  346. T_CONTINUE,
  347. T_PASS,
  348. T_FUNC,
  349. T_USE,
  350. T_RETURN,
  351. T_DEFER,
  352. T_REQUIRE,
  353. T_TRY,
  354. T_THROW,
  355. T_GOTO,
  356. T_CLASS,
  357. T_DEL,
  358. T_WITH,
  359. T_AS,
  360. T_IS,
  361. T_IN,
  362. T_LPAR,
  363. T_RPAR,
  364. T_LSB,
  365. T_RSB,
  366. T_LCB,
  367. T_RCB,
  368. T_EQUALS,
  369. T_NOTEQUALS,
  370. T_PLUSASSIGN,
  371. T_MINUSASSIGN,
  372. T_SLASHASSIGN,
  373. T_STARASSIGN,
  374. T_SLASHSLASHASSIGN,
  375. T_PERCENTASSIGN,
  376. T_STARSTARASSIGN,
  377. T_BARASSIGN,
  378. T_ANDASSIGN,
  379. T_RAISEASSIGN,
  380. T_LTLTASSIGN,
  381. T_GTGTASSIGN,
  382. T_BARBAR,
  383. T_ANDAND,
  384. T_STARSTAR,
  385. T_PLUSPLUS,
  386. T_MINUSMINUS,
  387. T_SLASHSLASH,
  388. T_COLONASSIGN,
  389. T_ARROW,
  390. T_PLUS,
  391. T_MINUS,
  392. T_QM,
  393. T_COLON,
  394. T_BAR,
  395. T_AND,
  396. T_LT,
  397. T_LTLT,
  398. T_GT,
  399. T_GTGT,
  400. T_LE,
  401. T_GE,
  402. T_STAR,
  403. T_SLASH,
  404. T_PERCENT,
  405. T_COMMA,
  406. T_DOT,
  407. T_BANG,
  408. T_RAISE,
  409. T_TILDE,
  410. T_AT,
  411. T_INLINE,
  412. T_HEADER,
  413. T_INCLUDE,
  414. T_MACRO,
  415. T_ASSIGN,
  416. T_SEMI,
  417. T_MVAR
  418. } tag;
  419. char *text;
  420. size_t z;
  421. size_t fi;
  422. size_t pos;
  423. } token_t;
  424. token_t *token(int tag, char *text)
  425. {
  426. token_t *tok = malloc_checked(sizeof(token_t));
  427. tok->tag = tag;
  428. tok->text = text;
  429. return tok;
  430. }
  431. #define TK(tk) (token(T_##tk, NULL))
  432. #define WS() \
  433. while (source[*pos] == ' ' || source[*pos] == '\t' || \
  434. source[*pos] == '\n' || source[*pos] == '\r') \
  435. { \
  436. (*pos)++; \
  437. }
  438. void consume_ignored(char *source, size_t *pos)
  439. {
  440. WS();
  441. while (source[*pos] == '#')
  442. {
  443. (*pos)++;
  444. for (;;)
  445. {
  446. if (!source[*pos])
  447. break;
  448. if (source[*pos] == '\n')
  449. {
  450. (*pos)++;
  451. break;
  452. }
  453. (*pos)++;
  454. }
  455. WS();
  456. }
  457. }
  458. list_t *FILES;
  459. list_t *REQUIRED;
  460. int is_required(char *path)
  461. {
  462. for (size_t i = 0; i < REQUIRED->length; i++)
  463. if (strcmp(REQUIRED->data[i], path) == 0)
  464. return 1;
  465. return 0;
  466. }
  467. char *traverse(char *source, size_t pos, size_t *line, size_t *col)
  468. {
  469. if (line)
  470. *line = 1;
  471. if (col)
  472. *col = 1;
  473. size_t p = 0;
  474. for (size_t i = 0; i < pos; i++)
  475. {
  476. if (source[i] == '\n')
  477. {
  478. if (line)
  479. (*line)++;
  480. if (col)
  481. (*col) = 1;
  482. p = i + 1;
  483. }
  484. else if (col)
  485. (*col)++;
  486. }
  487. return &source[p];
  488. }
  489. void format_error(char *filename, char *source, size_t pos, char *fmt, ...)
  490. {
  491. size_t line, col;
  492. char *src = traverse(source, pos, &line, &col);
  493. va_list args;
  494. va_start(args, fmt);
  495. fprintf(stderr, "%s (%zu:%zu): ", filename, line, col);
  496. vfprintf(stderr, fmt, args);
  497. fputc('\n', stderr);
  498. va_end(args);
  499. if (!*src)
  500. return;
  501. int empty = 1;
  502. for (size_t i = 0; src[i] && src[i] != '\n'; i++)
  503. if (!isspace(src[i]))
  504. {
  505. empty = 0;
  506. break;
  507. }
  508. if (empty)
  509. return;
  510. fputc('\t', stderr);
  511. for (size_t i = 0; src[i] && src[i] != '\n' && i < 64; i++)
  512. fputc(src[i], stderr);
  513. fputc('\n', stderr);
  514. fputc('\t', stderr);
  515. for (size_t i = 1; i < col && i < 64; i++)
  516. fputc(' ', stderr);
  517. fputs("^\n", stderr);
  518. }
  519. #define GETFNAME(fi) ((char *)((list_t *)list_index(FILES, fi))->data[0])
  520. #define GETSRC(fi) ((char *)((list_t *)list_index(FILES, fi))->data[1])
  521. #define LEX_ERROR(fmt, ...) \
  522. { \
  523. format_error(GETFNAME(-1), source, *pos, fmt, ##__VA_ARGS__); \
  524. exit(1); \
  525. }
  526. token_t *tokenize_string(char *source, size_t *pos, size_t *size)
  527. {
  528. char term = source[(*pos)++];
  529. int hx = 0;
  530. buffer_t *text = buffer_new();
  531. while (source[*pos] != term)
  532. {
  533. if (!source[*pos])
  534. LEX_ERROR("unterminated string literal");
  535. char c = source[(*pos)++];
  536. if (c == '\n' && term != '`')
  537. LEX_ERROR("unterminated string literal");
  538. if (term != '`' && c == '\\')
  539. {
  540. char nc = source[(*pos)++];
  541. if (!nc)
  542. continue;
  543. switch (nc)
  544. {
  545. case 'x':
  546. {
  547. char buf[3];
  548. int k = 0;
  549. while (k < 2)
  550. {
  551. if (!source[*pos] || !strchr("0123456789abcdefABCDEF", source[*pos]))
  552. break;
  553. buf[k++] = source[(*pos)++];
  554. }
  555. if (k != 2 || (!size && strncmp(buf, "00", 2) == 0))
  556. LEX_ERROR("malformed \\x escape sequence");
  557. buf[k] = 0;
  558. buffer_fmt(text, "\\x%s", buf);
  559. hx = 1;
  560. if (size)
  561. (*size)++;
  562. }
  563. continue;
  564. case 'n':
  565. buffer_appends(text, "\\n");
  566. break;
  567. case 't':
  568. buffer_appends(text, "\\t");
  569. break;
  570. case 'r':
  571. buffer_appends(text, "\\r");
  572. break;
  573. case 'a':
  574. buffer_appends(text, "\\a");
  575. break;
  576. case 'b':
  577. buffer_appends(text, "\\b");
  578. break;
  579. case 'e':
  580. buffer_appends(text, "\\x1b");
  581. break;
  582. case 's':
  583. buffer_appends(text, " ");
  584. break;
  585. case '"':
  586. buffer_appends(text, "\\\"");
  587. break;
  588. case '?':
  589. buffer_appends(text, "\\\?");
  590. break;
  591. case '\\':
  592. buffer_appends(text, "\\\\");
  593. break;
  594. case '\n':
  595. buffer_appends(text, "\\n");
  596. break;
  597. default:
  598. if (hx)
  599. {
  600. hx = 0;
  601. if (strchr("0123456789abcdefABCDEF", nc) != NULL)
  602. {
  603. buffer_fmt(text, "\\x%x", nc);
  604. hx = 1;
  605. if (size)
  606. (*size)++;
  607. continue;
  608. }
  609. }
  610. buffer_append(text, nc);
  611. break;
  612. }
  613. if (hx)
  614. hx = 0;
  615. if (size)
  616. (*size)++;
  617. continue;
  618. }
  619. if (c == '"' || c == '\\' || c == '?')
  620. buffer_append(text, '\\');
  621. else if (c == '\n')
  622. {
  623. buffer_appends(text, "\\n");
  624. if (size)
  625. (*size)++;
  626. continue;
  627. }
  628. if (size)
  629. (*size)++;
  630. if (hx)
  631. {
  632. hx = 0;
  633. if (strchr("0123456789abcdefABCDEF", c) != NULL)
  634. {
  635. buffer_fmt(text, "\\x%x", c);
  636. hx = 1;
  637. continue;
  638. }
  639. }
  640. buffer_append(text, c);
  641. }
  642. (*pos)++;
  643. return token(T_STRING, buffer_read(text));
  644. }
  645. int NEEDS_UTF8 = 0;
  646. token_t *next_token(char *source, size_t *pos)
  647. {
  648. if (!source[*pos])
  649. return token(T_EOF, NULL);
  650. if (source[*pos] == '"' || source[*pos] == '\'' || source[*pos] == '`')
  651. return tokenize_string(source, pos, NULL);
  652. else if (source[*pos] == 'f' &&
  653. (source[(*pos) + 1] == '"' || source[(*pos) + 1] == '\'' ||
  654. source[(*pos) + 1] == '`'))
  655. {
  656. (*pos)++;
  657. token_t *t = tokenize_string(source, pos, NULL);
  658. t->tag = T_FSTRING;
  659. return t;
  660. }
  661. else if (source[*pos] == 'u' &&
  662. (source[(*pos) + 1] == '"' || source[(*pos) + 1] == '\'' ||
  663. source[(*pos) + 1] == '`'))
  664. {
  665. (*pos)++;
  666. token_t *t = tokenize_string(source, pos, NULL);
  667. t->tag = T_USTRING;
  668. NEEDS_UTF8 = 1;
  669. return t;
  670. }
  671. else if (source[*pos] == 'b' &&
  672. (source[(*pos) + 1] == '"' || source[(*pos) + 1] == '\'' ||
  673. source[(*pos) + 1] == '`'))
  674. {
  675. (*pos)++;
  676. size_t z = 0;
  677. token_t *t = tokenize_string(source, pos, &z);
  678. t->tag = T_BSTRING;
  679. t->z = z;
  680. return t;
  681. }
  682. else if (source[*pos] == '0' &&
  683. (source[(*pos) + 1] == 'x' || source[(*pos) + 1] == 'b' ||
  684. source[(*pos) + 1] == 'o'))
  685. {
  686. buffer_t *number = buffer_new();
  687. buffer_append(number, source[(*pos)++]);
  688. char b = source[(*pos)++];
  689. buffer_append(number, b);
  690. while (source[*pos] && strchr(b == 'x' ? "0123456789abcdefABCDEF"
  691. : b == 'b' ? "01"
  692. : "01234567",
  693. source[*pos]) != NULL)
  694. buffer_append(number, source[(*pos)++]);
  695. if (number->size < 3)
  696. LEX_ERROR("illegal number literal (trailing base)");
  697. return token(T_NUMBER, buffer_read(number));
  698. }
  699. else if ((source[*pos] == '.' && isdigit(source[(*pos) + 1])) ||
  700. isdigit(source[*pos]))
  701. {
  702. buffer_t *number = buffer_new();
  703. int dot = 0;
  704. int sub = 0;
  705. int skip = 0;
  706. if (source[*pos] == '.')
  707. {
  708. buffer_append(number, '0');
  709. skip = 1;
  710. }
  711. do
  712. {
  713. if (skip)
  714. skip = 0;
  715. else
  716. buffer_append(number, source[(*pos)++]);
  717. if (!dot && source[*pos] == '.')
  718. {
  719. buffer_append(number, source[(*pos)++]);
  720. if (!isdigit(source[*pos]))
  721. LEX_ERROR(
  722. "illegal number literal (missing part after floating point)");
  723. dot = 1;
  724. }
  725. else if (!sub && source[*pos] == '_')
  726. {
  727. (*pos)++;
  728. if (!isdigit(source[*pos]))
  729. LEX_ERROR("illegal number literal (missing part after underscore)");
  730. sub = 1;
  731. }
  732. else if (sub)
  733. sub = 0;
  734. } while (isdigit(source[*pos]));
  735. return token(T_NUMBER, buffer_read(number));
  736. }
  737. else if (source[*pos] == '$')
  738. {
  739. (*pos)++;
  740. buffer_t *name = buffer_new();
  741. if (source[*pos] == '$' || source[*pos] == '{' || source[*pos] == ':' ||
  742. source[*pos] == '*')
  743. buffer_append(name, source[(*pos)++]);
  744. else
  745. {
  746. if (!source[*pos] || !isalpha(source[*pos]))
  747. LEX_ERROR("illegal macro variable (missing or malformed part after "
  748. "dollar sign)");
  749. do
  750. {
  751. buffer_append(name, source[(*pos)++]);
  752. } while (isalpha(source[*pos]) || source[*pos] == '_' ||
  753. isdigit(source[*pos]));
  754. }
  755. return token(T_MVAR, buffer_read(name));
  756. }
  757. else if (isalpha(source[*pos]) || source[*pos] == '_')
  758. {
  759. buffer_t *text = buffer_new();
  760. do
  761. {
  762. buffer_append(text, source[(*pos)++]);
  763. } while (isalpha(source[*pos]) || source[*pos] == '_' ||
  764. isdigit(source[*pos]));
  765. char *name = buffer_read(text);
  766. if (strcmp(name, "var") == 0)
  767. return TK(VAR);
  768. else if (strcmp(name, "let") == 0)
  769. return TK(LET);
  770. else if (strcmp(name, "const") == 0)
  771. return TK(CONST);
  772. else if (strcmp(name, "enum") == 0)
  773. return TK(ENUM);
  774. else if (strcmp(name, "if") == 0)
  775. return TK(IF);
  776. else if (strcmp(name, "else") == 0)
  777. return TK(ELSE);
  778. else if (strcmp(name, "elif") == 0)
  779. return TK(ELIF);
  780. else if (strcmp(name, "switch") == 0)
  781. return TK(SWITCH);
  782. else if (strcmp(name, "case") == 0)
  783. return TK(CASE);
  784. else if (strcmp(name, "default") == 0)
  785. return TK(DEFAULT);
  786. else if (strcmp(name, "for") == 0)
  787. return TK(FOR);
  788. else if (strcmp(name, "break") == 0)
  789. return TK(BREAK);
  790. else if (strcmp(name, "continue") == 0)
  791. return TK(CONTINUE);
  792. else if (strcmp(name, "func") == 0)
  793. return TK(FUNC);
  794. else if (strcmp(name, "use") == 0)
  795. return TK(USE);
  796. else if (strcmp(name, "return") == 0)
  797. return TK(RETURN);
  798. else if (strcmp(name, "defer") == 0)
  799. return TK(DEFER);
  800. else if (strcmp(name, "pass") == 0)
  801. return TK(PASS);
  802. else if (strcmp(name, "require") == 0)
  803. return TK(REQUIRE);
  804. else if (strcmp(name, "try") == 0)
  805. return TK(TRY);
  806. else if (strcmp(name, "throw") == 0)
  807. return TK(THROW);
  808. else if (strcmp(name, "goto") == 0)
  809. return TK(GOTO);
  810. else if (strcmp(name, "class") == 0)
  811. return TK(CLASS);
  812. else if (strcmp(name, "del") == 0)
  813. return TK(DEL);
  814. else if (strcmp(name, "is") == 0)
  815. return TK(IS);
  816. else if (strcmp(name, "with") == 0)
  817. return TK(WITH);
  818. else if (strcmp(name, "as") == 0)
  819. return TK(AS);
  820. else if (strcmp(name, "in") == 0)
  821. return TK(IN);
  822. else if (strcmp(name, "of") == 0)
  823. return TK(OF);
  824. else if (strcmp(name, "inline") == 0)
  825. return TK(INLINE);
  826. else if (strcmp(name, "header") == 0)
  827. return TK(HEADER);
  828. else if (strcmp(name, "include") == 0)
  829. return TK(INCLUDE);
  830. else if (strcmp(name, "macro") == 0)
  831. return TK(MACRO);
  832. else if (strcmp(name, "true") == 0)
  833. return TK(TRUE);
  834. else if (strcmp(name, "false") == 0)
  835. return TK(FALSE);
  836. else if (strcmp(name, "nil") == 0)
  837. return TK(NIL);
  838. return token(T_NAME, name);
  839. }
  840. else if (strncmp(&source[*pos], "==", 2) == 0 && ++(*pos) && ++(*pos))
  841. return TK(EQUALS);
  842. else if (strncmp(&source[*pos], "!=", 2) == 0 && ++(*pos) && ++(*pos))
  843. return TK(NOTEQUALS);
  844. else if (strncmp(&source[*pos], "+=", 2) == 0 && ++(*pos) && ++(*pos))
  845. return TK(PLUSASSIGN);
  846. else if (strncmp(&source[*pos], "-=", 2) == 0 && ++(*pos) && ++(*pos))
  847. return TK(MINUSASSIGN);
  848. else if (strncmp(&source[*pos], "*=", 2) == 0 && ++(*pos) && ++(*pos))
  849. return TK(STARASSIGN);
  850. else if (strncmp(&source[*pos], "/=", 2) == 0 && ++(*pos) && ++(*pos))
  851. return TK(SLASHASSIGN);
  852. else if (strncmp(&source[*pos], "//=", 3) == 0 && ++(*pos) && ++(*pos) &&
  853. ++(*pos))
  854. return TK(SLASHSLASHASSIGN);
  855. else if (strncmp(&source[*pos], "%=", 2) == 0 && ++(*pos) && ++(*pos))
  856. return TK(PERCENTASSIGN);
  857. else if (strncmp(&source[*pos], "**=", 3) == 0 && ++(*pos) && ++(*pos) &&
  858. ++(*pos))
  859. return TK(STARSTARASSIGN);
  860. else if (strncmp(&source[*pos], "|=", 2) == 0 && ++(*pos) && ++(*pos))
  861. return TK(BARASSIGN);
  862. else if (strncmp(&source[*pos], "&=", 2) == 0 && ++(*pos) && ++(*pos))
  863. return TK(ANDASSIGN);
  864. else if (strncmp(&source[*pos], "^=", 2) == 0 && ++(*pos) && ++(*pos))
  865. return TK(RAISEASSIGN);
  866. else if (strncmp(&source[*pos], "<<=", 3) == 0 && ++(*pos) && ++(*pos) &&
  867. ++(*pos))
  868. return TK(LTLTASSIGN);
  869. else if (strncmp(&source[*pos], ">>=", 3) == 0 && ++(*pos) && ++(*pos) &&
  870. ++(*pos))
  871. return TK(GTGTASSIGN);
  872. else if (strncmp(&source[*pos], "||", 2) == 0 && ++(*pos) && ++(*pos))
  873. return TK(BARBAR);
  874. else if (strncmp(&source[*pos], "&&", 2) == 0 && ++(*pos) && ++(*pos))
  875. return TK(ANDAND);
  876. else if (strncmp(&source[*pos], "++", 2) == 0 && ++(*pos) && ++(*pos))
  877. return TK(PLUSPLUS);
  878. else if (strncmp(&source[*pos], "--", 2) == 0 && ++(*pos) && ++(*pos))
  879. return TK(MINUSMINUS);
  880. else if (strncmp(&source[*pos], "//", 2) == 0 && ++(*pos) && ++(*pos))
  881. return TK(SLASHSLASH);
  882. else if (strncmp(&source[*pos], "**", 2) == 0 && ++(*pos) && ++(*pos))
  883. return TK(STARSTAR);
  884. else if (strncmp(&source[*pos], "<<", 2) == 0 && ++(*pos) && ++(*pos))
  885. return TK(LTLT);
  886. else if (strncmp(&source[*pos], ">>", 2) == 0 && ++(*pos) && ++(*pos))
  887. return TK(GTGT);
  888. else if (strncmp(&source[*pos], "<=", 2) == 0 && ++(*pos) && ++(*pos))
  889. return TK(LE);
  890. else if (strncmp(&source[*pos], ">=", 2) == 0 && ++(*pos) && ++(*pos))
  891. return TK(GE);
  892. else if (strncmp(&source[*pos], ":=", 2) == 0 && ++(*pos) && ++(*pos))
  893. return TK(COLONASSIGN);
  894. else if (strncmp(&source[*pos], "=>", 2) == 0 && ++(*pos) && ++(*pos))
  895. return TK(ARROW);
  896. else if (source[*pos] == '(' && ++(*pos))
  897. return TK(LPAR);
  898. else if (source[*pos] == ')' && ++(*pos))
  899. return TK(RPAR);
  900. else if (source[*pos] == '[' && ++(*pos))
  901. return TK(LSB);
  902. else if (source[*pos] == ']' && ++(*pos))
  903. return TK(RSB);
  904. else if (source[*pos] == '{' && ++(*pos))
  905. return TK(LCB);
  906. else if (source[*pos] == '}' && ++(*pos))
  907. {
  908. if (source[*pos] == '$' && ++(*pos))
  909. return token(T_MVAR, strdup("}"));
  910. return TK(RCB);
  911. }
  912. else if (source[*pos] == '+' && ++(*pos))
  913. return TK(PLUS);
  914. else if (source[*pos] == '-' && ++(*pos))
  915. return TK(MINUS);
  916. else if (source[*pos] == '*' && ++(*pos))
  917. return TK(STAR);
  918. else if (source[*pos] == '/' && ++(*pos))
  919. return TK(SLASH);
  920. else if (source[*pos] == '%' && ++(*pos))
  921. return TK(PERCENT);
  922. else if (source[*pos] == '?' && ++(*pos))
  923. return TK(QM);
  924. else if (source[*pos] == ':' && ++(*pos))
  925. return TK(COLON);
  926. else if (source[*pos] == '=' && ++(*pos))
  927. return TK(ASSIGN);
  928. else if (source[*pos] == ';' && ++(*pos))
  929. return TK(SEMI);
  930. else if (source[*pos] == ',' && ++(*pos))
  931. return TK(COMMA);
  932. else if (source[*pos] == '.' && ++(*pos))
  933. return TK(DOT);
  934. else if (source[*pos] == '<' && ++(*pos))
  935. return TK(LT);
  936. else if (source[*pos] == '>' && ++(*pos))
  937. return TK(GT);
  938. else if (source[*pos] == '!' && ++(*pos))
  939. return TK(BANG);
  940. else if (source[*pos] == '|' && ++(*pos))
  941. return TK(BAR);
  942. else if (source[*pos] == '&' && ++(*pos))
  943. return TK(AND);
  944. else if (source[*pos] == '^' && ++(*pos))
  945. return TK(RAISE);
  946. else if (source[*pos] == '~' && ++(*pos))
  947. return TK(TILDE);
  948. else if (source[*pos] == '@' && ++(*pos))
  949. return TK(AT);
  950. LEX_ERROR("unexpected input")
  951. }
  952. list_t *tokenize(char *source)
  953. {
  954. size_t pos = 0;
  955. list_t *toks = list_new();
  956. do
  957. {
  958. consume_ignored(source, &pos);
  959. size_t tok_pos = pos;
  960. token_t *tok = next_token(source, &pos);
  961. tok->fi = FILES->length - 1;
  962. tok->pos = tok_pos;
  963. list_push(toks, tok);
  964. if (tok->tag == T_EOF)
  965. break;
  966. } while (1);
  967. return toks;
  968. }
  969. int DEBUG = 0;
  970. list_t *DEBUGDATA;
  971. list_t *FUNCNAMES;
  972. struct _node_t
  973. {
  974. enum
  975. {
  976. N_TOPLEVEL,
  977. N_PROGRAM,
  978. N_EXPRSTMT,
  979. N_BLOCK,
  980. N_EXPRS_BEGIN,
  981. N_COMMA,
  982. N_NOT,
  983. N_NEGATE,
  984. N_UNARY_PLUS,
  985. N_BNOT,
  986. N_REFERENCE,
  987. N_DEREFERENCE,
  988. N_LITERAL,
  989. N_LIST,
  990. N_LISTGEN,
  991. N_TABLEGEN,
  992. N_TUPLE,
  993. N_NILTUPLE,
  994. N_TABLE,
  995. N_CALL,
  996. N_MEMBER,
  997. N_INDEX,
  998. N_SLICE,
  999. N_ADD,
  1000. N_SUB,
  1001. N_MUL,
  1002. N_DIV,
  1003. N_IDIV,
  1004. N_MOD,
  1005. N_POW,
  1006. N_SHL,
  1007. N_SHR,
  1008. N_XOR,
  1009. N_BOR,
  1010. N_BAND,
  1011. N_ASSIGN,
  1012. N_ASSIGN_ADD,
  1013. N_ASSIGN_SUB,
  1014. N_ASSIGN_MUL,
  1015. N_ASSIGN_DIV,
  1016. N_ASSIGN_IDIV,
  1017. N_ASSIGN_MOD,
  1018. N_ASSIGN_POW,
  1019. N_ASSIGN_BOR,
  1020. N_ASSIGN_BAND,
  1021. N_ASSIGN_XOR,
  1022. N_ASSIGN_SHL,
  1023. N_ASSIGN_SHR,
  1024. N_DECL,
  1025. N_EQUALS,
  1026. N_NOTEQUALS,
  1027. N_IS,
  1028. N_IN,
  1029. N_NOTIS,
  1030. N_NOTIN,
  1031. N_LT,
  1032. N_GT,
  1033. N_LE,
  1034. N_GE,
  1035. N_INC,
  1036. N_DEC,
  1037. N_PINC,
  1038. N_PDEC,
  1039. N_IFEXPR,
  1040. N_FUNCEXPR,
  1041. N_SWITCHEXPR,
  1042. N_LOGOR,
  1043. N_LOGAND,
  1044. N_TRY,
  1045. N_EXPRS_END,
  1046. N_STAR,
  1047. N_VAR,
  1048. N_LET,
  1049. N_VARUNPACK,
  1050. N_LETUNPACK,
  1051. N_CONST,
  1052. N_ENUM,
  1053. N_IF,
  1054. N_SWITCH,
  1055. N_FOR,
  1056. N_FOROF,
  1057. N_FOROFVAR,
  1058. N_FOROFUNPACK,
  1059. N_FOROFVARUNPACK,
  1060. N_BREAK,
  1061. N_CONTINUE,
  1062. N_FUNCDEF,
  1063. N_RETURN,
  1064. N_DEFER,
  1065. N_PASS,
  1066. N_REQUIRE,
  1067. N_THROW,
  1068. N_LABEL,
  1069. N_GOTO,
  1070. N_CLASS,
  1071. N_DEL,
  1072. N_WITH,
  1073. N_INLINE,
  1074. N_HEADER,
  1075. N_INCLUDE,
  1076. N_BUFFER,
  1077. N_MACRO_CALL,
  1078. N_MVAR,
  1079. N_MIF,
  1080. N_MFOR,
  1081. N_MREPEAT,
  1082. N_MSET,
  1083. N_MPUSH,
  1084. N_MSTMT,
  1085. N_MEXPR
  1086. } tag;
  1087. struct _node_t *a;
  1088. struct _node_t *b;
  1089. struct _node_t *c;
  1090. struct _node_t *d;
  1091. list_t *l;
  1092. list_t *l2;
  1093. table_t *h;
  1094. table_t *h2;
  1095. token_t *t;
  1096. token_t *t2;
  1097. buffer_t *buf;
  1098. size_t fi;
  1099. size_t pos;
  1100. };
  1101. typedef struct _node_t node_t;
  1102. node_t *node_pos(node_t *node, size_t fi, size_t pos)
  1103. {
  1104. node->fi = fi;
  1105. node->pos = pos;
  1106. return node;
  1107. }
  1108. node_t *node_copy(node_t *node)
  1109. {
  1110. node_t *nnode = malloc_checked(sizeof(node_t));
  1111. memcpy(nnode, node, sizeof(node_t));
  1112. return nnode;
  1113. }
  1114. node_t *nodet(int tag, token_t *t)
  1115. {
  1116. node_t *node = malloc_checked(sizeof(node_t));
  1117. node->tag = tag;
  1118. node->t = t;
  1119. return node;
  1120. }
  1121. #define NODET(n, a) \
  1122. (node_pos(nodet(N_##n, (a)), \
  1123. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1124. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1125. node_t *nodel(int tag, list_t *l)
  1126. {
  1127. node_t *node = malloc_checked(sizeof(node_t));
  1128. node->tag = tag;
  1129. node->l = l;
  1130. return node;
  1131. }
  1132. #define NODEL(n, a) \
  1133. (node_pos(nodel(N_##n, (a)), \
  1134. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1135. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1136. node_t *nodetl(int tag, token_t *t, list_t *l)
  1137. {
  1138. node_t *node = malloc_checked(sizeof(node_t));
  1139. node->tag = tag;
  1140. node->t = t;
  1141. node->l = l;
  1142. return node;
  1143. }
  1144. #define NODETL(n, t, l) \
  1145. (node_pos(nodetl(N_##n, (t), (l)), \
  1146. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1147. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1148. node_t *nodeh(int tag, table_t *h)
  1149. {
  1150. node_t *node = malloc_checked(sizeof(node_t));
  1151. node->tag = tag;
  1152. node->h = h;
  1153. return node;
  1154. }
  1155. #define NODEH(n, a) \
  1156. (node_pos(nodeh(N_##n, (a)), \
  1157. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1158. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1159. node_t *node0(int tag)
  1160. {
  1161. node_t *node = malloc_checked(sizeof(node_t));
  1162. node->tag = tag;
  1163. return node;
  1164. }
  1165. #define NODE0(n) \
  1166. (node_pos(node0(N_##n), \
  1167. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1168. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1169. node_t *node1(int tag, node_t *a)
  1170. {
  1171. node_t *node = malloc_checked(sizeof(node_t));
  1172. node->tag = tag;
  1173. node->a = a;
  1174. return node;
  1175. }
  1176. #define NODE1(n, a) \
  1177. (node_pos(node1(N_##n, (a)), \
  1178. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1179. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1180. node_t *node1l(int tag, node_t *a, list_t *l)
  1181. {
  1182. node_t *node = malloc_checked(sizeof(node_t));
  1183. node->tag = tag;
  1184. node->a = a;
  1185. node->l = l;
  1186. return node;
  1187. }
  1188. #define NODE1l(n, a, l) \
  1189. (node_pos(node1l(N_##n, (a), (l)), \
  1190. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1191. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1192. node_t *node1l2(int tag, node_t *a, list_t *l, list_t *l2)
  1193. {
  1194. node_t *node = malloc_checked(sizeof(node_t));
  1195. node->tag = tag;
  1196. node->a = a;
  1197. node->l = l;
  1198. node->l2 = l2;
  1199. return node;
  1200. }
  1201. #define NODE1l2(n, a, l, l2) \
  1202. (node_pos(node1l2(N_##n, (a), (l), (l2)), \
  1203. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1204. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1205. node_t *node1t(int tag, node_t *a, token_t *t)
  1206. {
  1207. node_t *node = malloc_checked(sizeof(node_t));
  1208. node->tag = tag;
  1209. node->a = a;
  1210. node->t = t;
  1211. return node;
  1212. }
  1213. #define NODE1t(n, a, t) \
  1214. (node_pos(node1t(N_##n, (a), (t)), \
  1215. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1216. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1217. node_t *node2(int tag, node_t *a, node_t *b)
  1218. {
  1219. node_t *node = malloc_checked(sizeof(node_t));
  1220. node->tag = tag;
  1221. node->a = a;
  1222. node->b = b;
  1223. return node;
  1224. }
  1225. #define NODE2(n, a, b) \
  1226. (node_pos(node2(N_##n, (a), (b)), \
  1227. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1228. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1229. node_t *node2l(int tag, node_t *a, node_t *b, list_t *l)
  1230. {
  1231. node_t *node = malloc_checked(sizeof(node_t));
  1232. node->tag = tag;
  1233. node->a = a;
  1234. node->b = b;
  1235. node->l = l;
  1236. return node;
  1237. }
  1238. #define NODE2l(n, a, b, l) \
  1239. (node_pos(node2l(N_##n, (a), (b), (l)), \
  1240. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1241. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1242. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t)
  1243. {
  1244. node_t *node = malloc_checked(sizeof(node_t));
  1245. node->tag = tag;
  1246. node->a = a;
  1247. node->b = b;
  1248. node->t = t;
  1249. return node;
  1250. }
  1251. #define NODE2t(n, a, b, c) \
  1252. (node_pos(node2t(N_##n, (a), (b), (c)), \
  1253. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1254. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1255. node_t *node3(int tag, node_t *a, node_t *b, node_t *c)
  1256. {
  1257. node_t *node = malloc_checked(sizeof(node_t));
  1258. node->tag = tag;
  1259. node->a = a;
  1260. node->b = b;
  1261. node->c = c;
  1262. return node;
  1263. }
  1264. #define NODE3(n, a, b, c) \
  1265. (node_pos(node3(N_##n, (a), (b), (c)), \
  1266. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1267. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1268. node_t *node3t(int tag, node_t *a, node_t *b, node_t *c, token_t *t)
  1269. {
  1270. node_t *node = malloc_checked(sizeof(node_t));
  1271. node->tag = tag;
  1272. node->a = a;
  1273. node->b = b;
  1274. node->c = c;
  1275. node->t = t;
  1276. return node;
  1277. }
  1278. #define NODE3t(n, a, b, c, d) \
  1279. (node_pos(node3t(N_##n, (a), (b), (c), (d)), \
  1280. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1281. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1282. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d)
  1283. {
  1284. node_t *node = malloc_checked(sizeof(node_t));
  1285. node->tag = tag;
  1286. node->a = a;
  1287. node->b = b;
  1288. node->c = c;
  1289. node->d = d;
  1290. return node;
  1291. }
  1292. #define NODE4(n, a, b, c, d) \
  1293. (node_pos(node4(N_##n, (a), (b), (c), (d)), \
  1294. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1295. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1296. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured,
  1297. node_t *body)
  1298. {
  1299. node_t *node = malloc_checked(sizeof(node_t));
  1300. node->tag = tag;
  1301. node->t = name;
  1302. node->h = params;
  1303. node->h2 = captured;
  1304. node->a = body;
  1305. return node;
  1306. }
  1307. #define NODEF(n, a, b, c, d) \
  1308. (node_pos(nodef(N_##n, (a), (b), (c), (d)), \
  1309. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi, \
  1310. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos))
  1311. node_t *nodeb(buffer_t *buf)
  1312. {
  1313. node_t *node = malloc_checked(sizeof(node_t));
  1314. node->tag = N_BUFFER;
  1315. node->buf = buf;
  1316. return node;
  1317. }
  1318. typedef struct
  1319. {
  1320. char *name;
  1321. list_t *params;
  1322. list_t *body;
  1323. int variable;
  1324. } macro_t;
  1325. list_t *MACROS;
  1326. #define LABELLOOP(n) \
  1327. node_t *ln = (n); \
  1328. ln->t2 = label;
  1329. #define AT(tk) \
  1330. (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  1331. #define ATP(tk, p) \
  1332. ((*pos) + p < tokens->length && \
  1333. ((token_t *)tokens->data[(*pos) + p])->tag == T_##tk)
  1334. #define MATCH(tk) ((*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk) && ++(*pos))
  1335. #define PARSE_ERROR(fmt, ...) \
  1336. { \
  1337. format_error( \
  1338. GETFNAME( \
  1339. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi), \
  1340. GETSRC( \
  1341. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->fi), \
  1342. ((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])->pos, fmt, \
  1343. ##__VA_ARGS__); \
  1344. exit(1); \
  1345. }
  1346. #define EXPECT(tk, s) \
  1347. { \
  1348. if (!((*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk) && ++(*pos))) \
  1349. PARSE_ERROR("expected %s", (s)); \
  1350. }
  1351. node_t *parse_expr(list_t *tokens, size_t *pos);
  1352. list_t *parse_sequence(list_t *tokens, size_t *pos, int term)
  1353. {
  1354. list_t *seq = list_new();
  1355. do
  1356. {
  1357. if (term != -1 && *pos < tokens->length &&
  1358. ((token_t *)tokens->data[*pos])->tag == term)
  1359. break;
  1360. if (MATCH(STAR))
  1361. list_push(seq, NODE1(STAR, parse_expr(tokens, pos)));
  1362. else
  1363. list_push(seq, parse_expr(tokens, pos));
  1364. } while (MATCH(COMMA));
  1365. return seq;
  1366. }
  1367. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  1368. node_t *parse_block(list_t *tokens, size_t *pos);
  1369. char *unescape(char *s);
  1370. node_t *parse_primary(list_t *tokens, size_t *pos)
  1371. {
  1372. if (MATCH(MVAR))
  1373. return NODET(MVAR, tokens->data[(*pos) - 1]);
  1374. else if (AT(AND) && ATP(NAME, 1))
  1375. {
  1376. MATCH(AND);
  1377. return NODET(REFERENCE, tokens->data[(*pos)++]);
  1378. }
  1379. else if (MATCH(TRY))
  1380. {
  1381. node_t *a;
  1382. if (AT(LCB))
  1383. a = parse_block(tokens, pos);
  1384. else
  1385. a = parse_expr(tokens, pos);
  1386. return NODE1(TRY, a);
  1387. }
  1388. else if (MATCH(FUNC))
  1389. return parse_func(tokens, pos, 1);
  1390. else if (MATCH(LPAR))
  1391. {
  1392. if (MATCH(RPAR))
  1393. return NODE0(NILTUPLE);
  1394. node_t *a = parse_expr(tokens, pos);
  1395. if (MATCH(COMMA))
  1396. {
  1397. list_t *l = list_new();
  1398. list_push(l, a);
  1399. if (!AT(RPAR))
  1400. do
  1401. {
  1402. node_t *n = parse_expr(tokens, pos);
  1403. list_push(l, n);
  1404. } while (MATCH(COMMA));
  1405. a = NODEL(TUPLE, l);
  1406. }
  1407. EXPECT(RPAR, ")");
  1408. return a;
  1409. }
  1410. else if (MATCH(LSB))
  1411. {
  1412. list_t *a = parse_sequence(tokens, pos, T_RSB);
  1413. node_t *loop = NULL;
  1414. node_t *cond = NULL;
  1415. if (MATCH(FOR))
  1416. {
  1417. int is_var = MATCH(VAR);
  1418. if (MATCH(LSB))
  1419. {
  1420. list_t *l = list_new();
  1421. do
  1422. {
  1423. if (!AT(NAME))
  1424. PARSE_ERROR("expected identifier");
  1425. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1426. } while (MATCH(COMMA));
  1427. EXPECT(RSB, "]");
  1428. EXPECT(OF, "of");
  1429. if (is_var)
  1430. loop = NODE2l(FOROFVARUNPACK, parse_expr(tokens, pos), NODEL(LIST, a),
  1431. l);
  1432. else
  1433. loop =
  1434. NODE2l(FOROFUNPACK, parse_expr(tokens, pos), NODEL(LIST, a), l);
  1435. }
  1436. else
  1437. {
  1438. if (!AT(NAME))
  1439. PARSE_ERROR("expected identifier");
  1440. token_t *t = tokens->data[(*pos)++];
  1441. EXPECT(OF, "of");
  1442. if (is_var)
  1443. loop = NODE2t(FOROFVAR, parse_expr(tokens, pos), NODEL(LIST, a), t);
  1444. else
  1445. loop = NODE2t(FOROF, parse_expr(tokens, pos), NODEL(LIST, a), t);
  1446. }
  1447. if (MATCH(IF))
  1448. cond = parse_expr(tokens, pos);
  1449. }
  1450. EXPECT(RSB, "]");
  1451. if (loop)
  1452. return NODE2(LISTGEN, loop, cond);
  1453. return NODEL(LIST, a);
  1454. }
  1455. else if (MATCH(LCB))
  1456. {
  1457. list_t *pairs = list_new();
  1458. do
  1459. {
  1460. if (AT(RCB))
  1461. break;
  1462. node_t *key = parse_expr(tokens, pos);
  1463. EXPECT(COLON, ":");
  1464. node_t *val = parse_expr(tokens, pos);
  1465. list_t *pair = list_new();
  1466. list_push(pair, key);
  1467. list_push(pair, val);
  1468. list_push(pairs, pair);
  1469. } while (MATCH(COMMA));
  1470. node_t *loop = NULL;
  1471. node_t *cond = NULL;
  1472. if (MATCH(FOR))
  1473. {
  1474. int is_var = MATCH(VAR);
  1475. if (MATCH(LSB))
  1476. {
  1477. list_t *l = list_new();
  1478. do
  1479. {
  1480. if (!AT(NAME))
  1481. PARSE_ERROR("expected identifier");
  1482. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1483. } while (MATCH(COMMA));
  1484. EXPECT(RSB, "]");
  1485. EXPECT(OF, "of");
  1486. if (is_var)
  1487. loop = NODE2l(FOROFVARUNPACK, parse_expr(tokens, pos),
  1488. NODEL(LIST, pairs), l);
  1489. else
  1490. loop = NODE2l(FOROFUNPACK, parse_expr(tokens, pos),
  1491. NODEL(LIST, pairs), l);
  1492. }
  1493. else
  1494. {
  1495. if (!AT(NAME))
  1496. PARSE_ERROR("expected identifier");
  1497. token_t *t = tokens->data[(*pos)++];
  1498. EXPECT(OF, "of");
  1499. if (is_var)
  1500. loop =
  1501. NODE2t(FOROFVAR, parse_expr(tokens, pos), NODEL(LIST, pairs), t);
  1502. else
  1503. loop = NODE2t(FOROF, parse_expr(tokens, pos), NODEL(LIST, pairs), t);
  1504. }
  1505. if (MATCH(IF))
  1506. cond = parse_expr(tokens, pos);
  1507. }
  1508. EXPECT(RCB, "}");
  1509. if (loop)
  1510. return NODE2(TABLEGEN, loop, cond);
  1511. return NODEL(TABLE, pairs);
  1512. }
  1513. else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(FSTRING) ||
  1514. MATCH(USTRING) || MATCH(BSTRING) || MATCH(NAME) || MATCH(TRUE) ||
  1515. MATCH(FALSE) || MATCH(NIL))
  1516. return NODET(LITERAL, tokens->data[(*pos) - 1]);
  1517. if (MATCH(RPAR))
  1518. {
  1519. PARSE_ERROR("extraneous )");
  1520. }
  1521. else if (MATCH(RSB))
  1522. {
  1523. PARSE_ERROR("extraneous ]");
  1524. }
  1525. else if (MATCH(RCB))
  1526. {
  1527. PARSE_ERROR("extraneous }");
  1528. }
  1529. else
  1530. {
  1531. PARSE_ERROR("expected expression");
  1532. }
  1533. return NULL;
  1534. }
  1535. size_t get_lineno(token_t *tok)
  1536. {
  1537. size_t line, col;
  1538. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  1539. return line;
  1540. }
  1541. #define CLIFF \
  1542. (get_lineno(((token_t *)tokens->data[(*pos) > 0 ? (*pos) - 1 : (*pos)])) != \
  1543. get_lineno( \
  1544. ((token_t *)tokens \
  1545. ->data[(*pos) >= tokens->length ? tokens->length - 1 : (*pos)])))
  1546. #define CLIFF_AHEAD \
  1547. (get_lineno(( \
  1548. (token_t *)tokens \
  1549. ->data[(*pos) >= tokens->length ? tokens->length - 1 : (*pos)])) != \
  1550. get_lineno(((token_t *)tokens \
  1551. ->data[(*pos) + 1 >= tokens->length ? tokens->length - 1 \
  1552. : (*pos) + 1])))
  1553. node_t *_parse_stmt(list_t *tokens, size_t *pos, int allow_comma);
  1554. #define parse_stmt(t, p) (_parse_stmt((t), (p), 0))
  1555. #define parse_stmt_c(t, p) (_parse_stmt((t), (p), 1))
  1556. node_t *parse_call(list_t *tokens, size_t *pos)
  1557. {
  1558. node_t *a = parse_primary(tokens, pos);
  1559. if (a->tag == N_LITERAL && a->t->tag == T_NAME && !CLIFF && !CLIFF_AHEAD &&
  1560. AT(BANG) && ATP(LPAR, 1))
  1561. {
  1562. MATCH(BANG);
  1563. MATCH(LPAR);
  1564. list_t *args = list_new();
  1565. if (!AT(RPAR))
  1566. do
  1567. {
  1568. node_t *n = parse_stmt(tokens, pos);
  1569. if (n->tag == N_BLOCK)
  1570. n->tag = N_PROGRAM;
  1571. else if (n->tag == N_EXPRSTMT)
  1572. n = n->a;
  1573. list_push(args, n);
  1574. } while (MATCH(COMMA));
  1575. EXPECT(RPAR, ")");
  1576. return NODETL(MACRO_CALL, a->t, args);
  1577. }
  1578. do
  1579. {
  1580. if (!CLIFF && MATCH(LPAR))
  1581. {
  1582. list_t *b = NULL;
  1583. if (!AT(RPAR))
  1584. b = parse_sequence(tokens, pos, -1);
  1585. EXPECT(RPAR, ")");
  1586. a = NODE1l(CALL, a, b);
  1587. continue;
  1588. }
  1589. else if (!CLIFF && MATCH(LSB))
  1590. {
  1591. if (MATCH(COLON))
  1592. {
  1593. a = NODE3(SLICE, a, NULL, parse_expr(tokens, pos));
  1594. EXPECT(RSB, "]");
  1595. continue;
  1596. }
  1597. node_t *b = parse_expr(tokens, pos);
  1598. if (MATCH(COLON))
  1599. {
  1600. node_t *c = NULL;
  1601. if (!AT(RSB))
  1602. c = parse_expr(tokens, pos);
  1603. EXPECT(RSB, "]");
  1604. a = NODE3(SLICE, a, b, c);
  1605. continue;
  1606. }
  1607. EXPECT(RSB, "]");
  1608. a = NODE2(INDEX, a, b);
  1609. continue;
  1610. }
  1611. else if (!CLIFF && MATCH(DOT))
  1612. {
  1613. if (!AT(NAME))
  1614. PARSE_ERROR("expected identifier after .");
  1615. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  1616. continue;
  1617. }
  1618. break;
  1619. } while (1);
  1620. return a;
  1621. }
  1622. node_t *parse_dereference(list_t *tokens, size_t *pos)
  1623. {
  1624. if (MATCH(RAISE))
  1625. {
  1626. node_t *a = parse_dereference(tokens, pos);
  1627. return NODE1(DEREFERENCE, a);
  1628. }
  1629. return parse_call(tokens, pos);
  1630. }
  1631. node_t *parse_postfix(list_t *tokens, size_t *pos)
  1632. {
  1633. node_t *a = parse_dereference(tokens, pos);
  1634. if (CLIFF)
  1635. return a;
  1636. if (MATCH(PLUSPLUS))
  1637. return NODE1(INC, a);
  1638. else if (MATCH(MINUSMINUS))
  1639. return NODE1(DEC, a);
  1640. else if (MATCH(SWITCH))
  1641. {
  1642. EXPECT(LCB, "{");
  1643. list_t *cases = list_new();
  1644. node_t *default_case = NULL;
  1645. for (;;)
  1646. {
  1647. if (MATCH(DEFAULT))
  1648. {
  1649. MATCH(ARROW);
  1650. default_case = parse_expr(tokens, pos);
  1651. break;
  1652. }
  1653. if (AT(RCB))
  1654. break;
  1655. node_t *expr = parse_expr(tokens, pos);
  1656. MATCH(ARROW);
  1657. list_t *pair = list_new();
  1658. list_push(pair, expr);
  1659. list_push(pair, parse_expr(tokens, pos));
  1660. list_push(cases, pair);
  1661. }
  1662. EXPECT(RCB, "}");
  1663. if (!cases->length && !default_case)
  1664. PARSE_ERROR("empty switch expression");
  1665. return NODE2l(SWITCHEXPR, a, default_case, cases);
  1666. }
  1667. return a;
  1668. }
  1669. node_t *parse_unary(list_t *tokens, size_t *pos)
  1670. {
  1671. if (MATCH(MINUS))
  1672. {
  1673. node_t *a = parse_unary(tokens, pos);
  1674. return NODE1(NEGATE, a);
  1675. }
  1676. else if (MATCH(PLUS))
  1677. {
  1678. node_t *a = parse_unary(tokens, pos);
  1679. return NODE1(UNARY_PLUS, a);
  1680. }
  1681. else if (MATCH(BANG))
  1682. {
  1683. node_t *a = parse_unary(tokens, pos);
  1684. return NODE1(NOT, a);
  1685. }
  1686. else if (MATCH(TILDE))
  1687. {
  1688. node_t *a = parse_unary(tokens, pos);
  1689. return NODE1(BNOT, a);
  1690. }
  1691. else if (MATCH(PLUSPLUS))
  1692. {
  1693. node_t *a = parse_postfix(tokens, pos);
  1694. return NODE1(PINC, a);
  1695. }
  1696. else if (MATCH(MINUSMINUS))
  1697. {
  1698. node_t *a = parse_postfix(tokens, pos);
  1699. return NODE1(PDEC, a);
  1700. }
  1701. return parse_postfix(tokens, pos);
  1702. }
  1703. node_t *parse_pow(list_t *tokens, size_t *pos)
  1704. {
  1705. node_t *a = parse_unary(tokens, pos);
  1706. do
  1707. {
  1708. if (MATCH(STARSTAR))
  1709. {
  1710. node_t *b = parse_unary(tokens, pos);
  1711. a = NODE2(POW, a, b);
  1712. continue;
  1713. }
  1714. break;
  1715. } while (1);
  1716. return a;
  1717. }
  1718. node_t *parse_mul(list_t *tokens, size_t *pos)
  1719. {
  1720. node_t *a = parse_pow(tokens, pos);
  1721. do
  1722. {
  1723. if (MATCH(STAR))
  1724. {
  1725. node_t *b = parse_pow(tokens, pos);
  1726. a = NODE2(MUL, a, b);
  1727. continue;
  1728. }
  1729. else if (MATCH(SLASH))
  1730. {
  1731. node_t *b = parse_pow(tokens, pos);
  1732. a = NODE2(DIV, a, b);
  1733. continue;
  1734. }
  1735. else if (MATCH(SLASHSLASH))
  1736. {
  1737. node_t *b = parse_pow(tokens, pos);
  1738. a = NODE2(IDIV, a, b);
  1739. continue;
  1740. }
  1741. else if (MATCH(PERCENT))
  1742. {
  1743. node_t *b = parse_pow(tokens, pos);
  1744. a = NODE2(MOD, a, b);
  1745. continue;
  1746. }
  1747. break;
  1748. } while (1);
  1749. return a;
  1750. }
  1751. node_t *parse_add(list_t *tokens, size_t *pos)
  1752. {
  1753. node_t *a = parse_mul(tokens, pos);
  1754. do
  1755. {
  1756. if (MATCH(PLUS))
  1757. {
  1758. node_t *b = parse_mul(tokens, pos);
  1759. a = NODE2(ADD, a, b);
  1760. continue;
  1761. }
  1762. else if (MATCH(MINUS))
  1763. {
  1764. node_t *b = parse_mul(tokens, pos);
  1765. a = NODE2(SUB, a, b);
  1766. continue;
  1767. }
  1768. break;
  1769. } while (1);
  1770. return a;
  1771. }
  1772. node_t *parse_shift(list_t *tokens, size_t *pos)
  1773. {
  1774. node_t *a = parse_add(tokens, pos);
  1775. do
  1776. {
  1777. if (MATCH(LTLT))
  1778. {
  1779. node_t *b = parse_add(tokens, pos);
  1780. a = NODE2(SHL, a, b);
  1781. continue;
  1782. }
  1783. else if (MATCH(GTGT))
  1784. {
  1785. node_t *b = parse_add(tokens, pos);
  1786. a = NODE2(SHR, a, b);
  1787. continue;
  1788. }
  1789. break;
  1790. } while (1);
  1791. return a;
  1792. }
  1793. node_t *parse_relation(list_t *tokens, size_t *pos)
  1794. {
  1795. node_t *a = parse_shift(tokens, pos);
  1796. do
  1797. {
  1798. if (MATCH(LT))
  1799. {
  1800. node_t *b = parse_shift(tokens, pos);
  1801. a = NODE2(LT, a, b);
  1802. continue;
  1803. }
  1804. else if (MATCH(GT))
  1805. {
  1806. node_t *b = parse_shift(tokens, pos);
  1807. a = NODE2(GT, a, b);
  1808. continue;
  1809. }
  1810. else if (MATCH(LE))
  1811. {
  1812. node_t *b = parse_shift(tokens, pos);
  1813. a = NODE2(LE, a, b);
  1814. continue;
  1815. }
  1816. else if (MATCH(GE))
  1817. {
  1818. node_t *b = parse_shift(tokens, pos);
  1819. a = NODE2(GE, a, b);
  1820. continue;
  1821. }
  1822. break;
  1823. } while (1);
  1824. return a;
  1825. }
  1826. node_t *parse_equality(list_t *tokens, size_t *pos)
  1827. {
  1828. node_t *a = parse_relation(tokens, pos);
  1829. do
  1830. {
  1831. if (MATCH(EQUALS))
  1832. {
  1833. node_t *b = parse_relation(tokens, pos);
  1834. a = NODE2(EQUALS, a, b);
  1835. continue;
  1836. }
  1837. else if (MATCH(NOTEQUALS))
  1838. {
  1839. node_t *b = parse_relation(tokens, pos);
  1840. a = NODE2(NOTEQUALS, a, b);
  1841. continue;
  1842. }
  1843. else if (MATCH(IS))
  1844. {
  1845. node_t *b = parse_relation(tokens, pos);
  1846. a = NODE2(IS, a, b);
  1847. continue;
  1848. }
  1849. else if (AT(BANG) && ATP(IS, 1))
  1850. {
  1851. EXPECT(BANG, "!");
  1852. EXPECT(IS, "is");
  1853. node_t *b = parse_relation(tokens, pos);
  1854. a = NODE2(NOTIS, a, b);
  1855. continue;
  1856. }
  1857. else if (MATCH(IN))
  1858. {
  1859. node_t *b = parse_relation(tokens, pos);
  1860. a = NODE2(IN, a, b);
  1861. continue;
  1862. }
  1863. else if (AT(BANG) && ATP(IN, 1))
  1864. {
  1865. EXPECT(BANG, "!");
  1866. EXPECT(IN, "in");
  1867. node_t *b = parse_relation(tokens, pos);
  1868. a = NODE2(NOTIN, a, b);
  1869. continue;
  1870. }
  1871. break;
  1872. } while (1);
  1873. return a;
  1874. }
  1875. node_t *parse_bitand(list_t *tokens, size_t *pos)
  1876. {
  1877. node_t *a = parse_equality(tokens, pos);
  1878. while (MATCH(AND))
  1879. {
  1880. node_t *b = parse_equality(tokens, pos);
  1881. a = NODE2(BAND, a, b);
  1882. }
  1883. return a;
  1884. }
  1885. node_t *parse_bitxor(list_t *tokens, size_t *pos)
  1886. {
  1887. node_t *a = parse_bitand(tokens, pos);
  1888. if (CLIFF)
  1889. return a;
  1890. while (MATCH(RAISE))
  1891. {
  1892. node_t *b = parse_bitand(tokens, pos);
  1893. a = NODE2(XOR, a, b);
  1894. if (CLIFF)
  1895. break;
  1896. }
  1897. return a;
  1898. }
  1899. node_t *parse_bitor(list_t *tokens, size_t *pos)
  1900. {
  1901. node_t *a = parse_bitxor(tokens, pos);
  1902. while (MATCH(BAR))
  1903. {
  1904. node_t *b = parse_bitxor(tokens, pos);
  1905. a = NODE2(BOR, a, b);
  1906. }
  1907. return a;
  1908. }
  1909. node_t *parse_logand(list_t *tokens, size_t *pos)
  1910. {
  1911. node_t *a = parse_bitor(tokens, pos);
  1912. if (MATCH(ANDAND))
  1913. {
  1914. node_t *b = parse_logand(tokens, pos);
  1915. return NODE2(LOGAND, a, b);
  1916. }
  1917. return a;
  1918. }
  1919. node_t *parse_logor(list_t *tokens, size_t *pos)
  1920. {
  1921. node_t *a = parse_logand(tokens, pos);
  1922. if (MATCH(BARBAR))
  1923. {
  1924. node_t *b = parse_logor(tokens, pos);
  1925. return NODE2(LOGOR, a, b);
  1926. }
  1927. return a;
  1928. }
  1929. node_t *parse_assignment(list_t *tokens, size_t *pos);
  1930. node_t *parse_conditional(list_t *tokens, size_t *pos)
  1931. {
  1932. node_t *a = parse_logor(tokens, pos);
  1933. if (MATCH(QM))
  1934. {
  1935. node_t *b = parse_assignment(tokens, pos);
  1936. EXPECT(COLON, ":");
  1937. node_t *c = parse_assignment(tokens, pos);
  1938. return NODE3(IFEXPR, a, b, c);
  1939. }
  1940. return a;
  1941. }
  1942. node_t *parse_assignment(list_t *tokens, size_t *pos)
  1943. {
  1944. node_t *a = parse_conditional(tokens, pos);
  1945. if (MATCH(COLONASSIGN))
  1946. {
  1947. node_t *b = parse_assignment(tokens, pos);
  1948. return NODE2(DECL, a, b);
  1949. }
  1950. else if (MATCH(ASSIGN))
  1951. {
  1952. node_t *b = parse_assignment(tokens, pos);
  1953. return NODE2(ASSIGN, a, b);
  1954. }
  1955. else if (MATCH(PLUSASSIGN))
  1956. {
  1957. node_t *b = parse_assignment(tokens, pos);
  1958. return NODE2(ASSIGN_ADD, a, b);
  1959. }
  1960. else if (MATCH(MINUSASSIGN))
  1961. {
  1962. node_t *b = parse_assignment(tokens, pos);
  1963. return NODE2(ASSIGN_SUB, a, b);
  1964. }
  1965. else if (MATCH(STARASSIGN))
  1966. {
  1967. node_t *b = parse_assignment(tokens, pos);
  1968. return NODE2(ASSIGN_MUL, a, b);
  1969. }
  1970. else if (MATCH(SLASHASSIGN))
  1971. {
  1972. node_t *b = parse_assignment(tokens, pos);
  1973. return NODE2(ASSIGN_DIV, a, b);
  1974. }
  1975. else if (MATCH(SLASHSLASHASSIGN))
  1976. {
  1977. node_t *b = parse_assignment(tokens, pos);
  1978. return NODE2(ASSIGN_IDIV, a, b);
  1979. }
  1980. else if (MATCH(PERCENTASSIGN))
  1981. {
  1982. node_t *b = parse_assignment(tokens, pos);
  1983. return NODE2(ASSIGN_MOD, a, b);
  1984. }
  1985. else if (MATCH(STARSTARASSIGN))
  1986. {
  1987. node_t *b = parse_assignment(tokens, pos);
  1988. return NODE2(ASSIGN_POW, a, b);
  1989. }
  1990. else if (MATCH(BARASSIGN))
  1991. {
  1992. node_t *b = parse_assignment(tokens, pos);
  1993. return NODE2(ASSIGN_BOR, a, b);
  1994. }
  1995. else if (MATCH(ANDASSIGN))
  1996. {
  1997. node_t *b = parse_assignment(tokens, pos);
  1998. return NODE2(ASSIGN_BAND, a, b);
  1999. }
  2000. else if (MATCH(RAISEASSIGN))
  2001. {
  2002. node_t *b = parse_assignment(tokens, pos);
  2003. return NODE2(ASSIGN_XOR, a, b);
  2004. }
  2005. else if (MATCH(LTLTASSIGN))
  2006. {
  2007. node_t *b = parse_assignment(tokens, pos);
  2008. return NODE2(ASSIGN_SHL, a, b);
  2009. }
  2010. else if (MATCH(GTGTASSIGN))
  2011. {
  2012. node_t *b = parse_assignment(tokens, pos);
  2013. return NODE2(ASSIGN_SHR, a, b);
  2014. }
  2015. return a;
  2016. }
  2017. node_t *parse_expr(list_t *tokens, size_t *pos)
  2018. {
  2019. return parse_assignment(tokens, pos);
  2020. }
  2021. node_t *parse_comma_expr(list_t *tokens, size_t *pos)
  2022. {
  2023. node_t *a = parse_expr(tokens, pos);
  2024. if (MATCH(COMMA))
  2025. {
  2026. list_t *exprs = list_new();
  2027. list_push(exprs, a);
  2028. do
  2029. {
  2030. list_push(exprs, parse_expr(tokens, pos));
  2031. } while (MATCH(COMMA));
  2032. a = NODEL(COMMA, exprs);
  2033. }
  2034. return a;
  2035. }
  2036. node_t *parse_block(list_t *tokens, size_t *pos)
  2037. {
  2038. EXPECT(LCB, "{");
  2039. list_t *stmts = list_new();
  2040. while (!AT(EOF) && !AT(RCB))
  2041. {
  2042. list_push(stmts, parse_stmt_c(tokens, pos));
  2043. MATCH(SEMI);
  2044. }
  2045. EXPECT(RCB, "}");
  2046. return NODEL(PROGRAM, stmts);
  2047. }
  2048. #define BLOCK() \
  2049. (CLIFF || MATCH(COLON) ? parse_stmt(tokens, pos) : parse_block(tokens, pos))
  2050. #define STMT_OR_BLOCK() \
  2051. (MATCH(COLON) ? parse_stmt(tokens, pos) \
  2052. : AT(LCB) ? parse_block(tokens, pos) \
  2053. : parse_stmt(tokens, pos))
  2054. node_t *parse_if(list_t *tokens, size_t *pos)
  2055. {
  2056. node_t *a = parse_comma_expr(tokens, pos);
  2057. node_t *b = BLOCK();
  2058. node_t *c = NULL;
  2059. if (MATCH(ELSE))
  2060. c = STMT_OR_BLOCK();
  2061. else if (MATCH(ELIF))
  2062. c = parse_if(tokens, pos);
  2063. return NODE3(IF, a, b, c);
  2064. }
  2065. node_t *parse_var(list_t *tokens, size_t *pos, int is_let)
  2066. {
  2067. table_t *h = table_new();
  2068. do
  2069. {
  2070. if (!AT(NAME))
  2071. PARSE_ERROR("expected identifier");
  2072. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  2073. node_t *v = NULL;
  2074. if (is_let)
  2075. {
  2076. EXPECT(ASSIGN, "=");
  2077. v = parse_expr(tokens, pos);
  2078. }
  2079. else if (MATCH(ASSIGN))
  2080. v = parse_expr(tokens, pos);
  2081. table_set(h, k, v);
  2082. } while (MATCH(COMMA));
  2083. if (is_let)
  2084. return NODEH(LET, h);
  2085. return NODEH(VAR, h);
  2086. }
  2087. node_t *parse_unpack(list_t *tokens, size_t *pos, int tag)
  2088. {
  2089. EXPECT(LSB, "[");
  2090. list_t *l = list_new();
  2091. do
  2092. {
  2093. if (!AT(NAME))
  2094. PARSE_ERROR("expected identifier");
  2095. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  2096. } while (MATCH(COMMA));
  2097. EXPECT(RSB, "]");
  2098. EXPECT(ASSIGN, "=");
  2099. node_t *a = parse_expr(tokens, pos);
  2100. if (tag == N_LETUNPACK)
  2101. return NODE1l(LETUNPACK, a, l);
  2102. return NODE1l(VARUNPACK, a, l);
  2103. }
  2104. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr)
  2105. {
  2106. token_t *name = NULL;
  2107. if (!is_expr)
  2108. {
  2109. if (!AT(NAME))
  2110. PARSE_ERROR("expected identifier");
  2111. name = tokens->data[(*pos)++];
  2112. }
  2113. table_t *params = NULL;
  2114. if (MATCH(LPAR))
  2115. {
  2116. if (!AT(RPAR))
  2117. {
  2118. int flag = 0;
  2119. params = table_new();
  2120. size_t argc = 0;
  2121. do
  2122. {
  2123. if (!AT(NAME))
  2124. PARSE_ERROR("expected identifier");
  2125. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  2126. node_t *r = NULL;
  2127. if (!flag && strcmp(l, "_") != 0 && AT(ASSIGN))
  2128. flag = 1;
  2129. if (flag)
  2130. {
  2131. EXPECT(ASSIGN, "=");
  2132. r = parse_expr(tokens, pos);
  2133. }
  2134. list_t *pair = list_new();
  2135. size_t *argcp = malloc_checked(sizeof(size_t));
  2136. memcpy(argcp, &argc, sizeof(size_t));
  2137. argc++;
  2138. list_push(pair, argcp);
  2139. list_push(pair, r);
  2140. table_set(params, l, pair);
  2141. } while (MATCH(COMMA));
  2142. }
  2143. EXPECT(RPAR, ")");
  2144. }
  2145. table_t *captured = NULL;
  2146. if (MATCH(USE))
  2147. {
  2148. EXPECT(LPAR, "(");
  2149. captured = table_new();
  2150. do
  2151. {
  2152. int is_ref = 0;
  2153. if (MATCH(AND))
  2154. is_ref = 1;
  2155. if (!AT(NAME))
  2156. PARSE_ERROR("expected identifier");
  2157. token_t *name = tokens->data[(*pos)++];
  2158. if (is_ref)
  2159. table_set(captured, name->text, NODET(REFERENCE, name));
  2160. else
  2161. table_set(captured, name->text, NODET(LITERAL, name));
  2162. } while (MATCH(COMMA));
  2163. EXPECT(RPAR, ")");
  2164. }
  2165. int colon = AT(COLON);
  2166. node_t *body = !colon && !AT(LCB) ? parse_stmt(tokens, pos) : BLOCK();
  2167. if (colon && body->tag == N_EXPRSTMT)
  2168. body = NODE1(RETURN, body->a);
  2169. if (is_expr)
  2170. return NODEF(FUNCEXPR, NULL, params, captured, body);
  2171. return NODEF(FUNCDEF, name, params, captured, body);
  2172. }
  2173. node_t *_parse_stmt(list_t *tokens, size_t *pos, int allow_comma)
  2174. {
  2175. if (MATCH(LCB))
  2176. {
  2177. list_t *stmts = list_new();
  2178. while (!AT(EOF) && !AT(RCB))
  2179. {
  2180. node_t *n = parse_stmt_c(tokens, pos);
  2181. MATCH(SEMI);
  2182. list_push(stmts, n);
  2183. }
  2184. EXPECT(RCB, "}");
  2185. return NODEL(BLOCK, stmts);
  2186. }
  2187. else if (MATCH(VAR))
  2188. {
  2189. if (AT(LSB))
  2190. return parse_unpack(tokens, pos, N_VARUNPACK);
  2191. return parse_var(tokens, pos, 0);
  2192. }
  2193. else if (MATCH(LET))
  2194. {
  2195. if (AT(LSB))
  2196. return parse_unpack(tokens, pos, N_LETUNPACK);
  2197. return parse_var(tokens, pos, 1);
  2198. }
  2199. else if (MATCH(CONST))
  2200. {
  2201. table_t *h = table_new();
  2202. do
  2203. {
  2204. if (!AT(NAME))
  2205. PARSE_ERROR("expected identifier");
  2206. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  2207. if (k[0] != '_' && !(k[0] >= 'A' && k[0] <= 'Z'))
  2208. PARSE_ERROR("compile-time constant identifiers must begin with an "
  2209. "uppercase letter or with an underscore, but '%s' does not",
  2210. k);
  2211. if (table_get(h, k))
  2212. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  2213. EXPECT(ASSIGN, "=");
  2214. node_t *v = parse_expr(tokens, pos);
  2215. table_set(h, k, v);
  2216. } while (MATCH(COMMA));
  2217. return NODEH(CONST, h);
  2218. }
  2219. else if (MATCH(ENUM))
  2220. {
  2221. table_t *h = table_new();
  2222. EXPECT(LCB, "{");
  2223. if (AT(RCB))
  2224. PARSE_ERROR("empty enum");
  2225. while (!AT(EOF))
  2226. {
  2227. if (AT(RCB))
  2228. break;
  2229. if (!AT(NAME))
  2230. PARSE_ERROR("expected identifier");
  2231. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  2232. if (k[0] != '_' && !(k[0] >= 'A' && k[0] <= 'Z'))
  2233. PARSE_ERROR("compile-time constant identifiers must begin with an "
  2234. "uppercase letter or with an underscore, but '%s' does not",
  2235. k);
  2236. if (table_get(h, k))
  2237. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  2238. node_t *v = NULL;
  2239. if (MATCH(ASSIGN))
  2240. v = parse_expr(tokens, pos);
  2241. table_set(h, k, v);
  2242. }
  2243. EXPECT(RCB, "}");
  2244. return NODEH(ENUM, h);
  2245. }
  2246. else if (MATCH(IF))
  2247. return parse_if(tokens, pos);
  2248. else if (MATCH(SWITCH))
  2249. {
  2250. token_t *label = NULL;
  2251. if (MATCH(AT))
  2252. {
  2253. if (!AT(NAME))
  2254. PARSE_ERROR("expected identifier");
  2255. label = tokens->data[(*pos)++];
  2256. }
  2257. node_t *a = parse_expr(tokens, pos);
  2258. EXPECT(LCB, "{");
  2259. list_t *cases = list_new();
  2260. int has_default = 0;
  2261. for (;;)
  2262. {
  2263. if (AT(RCB))
  2264. break;
  2265. node_t *expr = NULL;
  2266. list_t *stmts = list_new();
  2267. if (MATCH(DEFAULT))
  2268. {
  2269. if (has_default)
  2270. PARSE_ERROR("duplicated default case in switch");
  2271. has_default = 1;
  2272. }
  2273. else
  2274. {
  2275. EXPECT(CASE, "case");
  2276. expr = parse_expr(tokens, pos);
  2277. }
  2278. MATCH(COLON);
  2279. while (!AT(CASE) && !AT(DEFAULT) && !AT(RCB))
  2280. list_push(stmts, parse_stmt(tokens, pos));
  2281. list_t *pair = list_new();
  2282. list_push(pair, expr);
  2283. list_push(pair, NODEL(PROGRAM, stmts));
  2284. list_push(cases, pair);
  2285. }
  2286. EXPECT(RCB, "}");
  2287. if (!cases->length)
  2288. PARSE_ERROR("empty switch statement");
  2289. LABELLOOP(NODE1l(SWITCH, a, cases));
  2290. return ln;
  2291. }
  2292. else if (MATCH(FOR))
  2293. {
  2294. token_t *label = NULL;
  2295. if (MATCH(AT))
  2296. {
  2297. if (!AT(NAME))
  2298. PARSE_ERROR("expected identifier");
  2299. label = tokens->data[(*pos)++];
  2300. }
  2301. node_t *a = NULL;
  2302. node_t *b = NULL;
  2303. node_t *c = NULL;
  2304. if (!AT(LCB) && !AT(COLON) && !CLIFF)
  2305. {
  2306. if (MATCH(LSB))
  2307. {
  2308. list_t *l = list_new();
  2309. do
  2310. {
  2311. if (!AT(NAME))
  2312. PARSE_ERROR("expected identifier");
  2313. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  2314. } while (MATCH(COMMA));
  2315. EXPECT(RSB, "]");
  2316. EXPECT(OF, "of");
  2317. a = parse_expr(tokens, pos);
  2318. b = BLOCK();
  2319. LABELLOOP(NODE2l(FOROFUNPACK, a, b, l));
  2320. return ln;
  2321. }
  2322. if (AT(NAME) && ATP(OF, 1))
  2323. {
  2324. token_t *t = tokens->data[(*pos)++];
  2325. EXPECT(OF, "of");
  2326. a = parse_expr(tokens, pos);
  2327. b = BLOCK();
  2328. LABELLOOP(NODE2t(FOROF, a, b, t));
  2329. return ln;
  2330. }
  2331. if (MATCH(VAR))
  2332. {
  2333. if (MATCH(LSB))
  2334. {
  2335. list_t *l = list_new();
  2336. do
  2337. {
  2338. if (!AT(NAME))
  2339. PARSE_ERROR("expected identifier");
  2340. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  2341. } while (MATCH(COMMA));
  2342. EXPECT(RSB, "]");
  2343. EXPECT(OF, "of");
  2344. a = parse_expr(tokens, pos);
  2345. b = BLOCK();
  2346. LABELLOOP(NODE2l(FOROFVARUNPACK, a, b, l));
  2347. return ln;
  2348. }
  2349. if (AT(NAME) && ATP(OF, 1))
  2350. {
  2351. token_t *t = tokens->data[(*pos)++];
  2352. EXPECT(OF, "of");
  2353. a = parse_expr(tokens, pos);
  2354. b = BLOCK();
  2355. LABELLOOP(NODE2t(FOROFVAR, a, b, t));
  2356. return ln;
  2357. }
  2358. a = parse_var(tokens, pos, 0);
  2359. EXPECT(SEMI, ";");
  2360. b = parse_comma_expr(tokens, pos);
  2361. if (MATCH(SEMI))
  2362. c = parse_comma_expr(tokens, pos);
  2363. }
  2364. else
  2365. {
  2366. a = parse_comma_expr(tokens, pos);
  2367. if (MATCH(SEMI))
  2368. {
  2369. b = parse_comma_expr(tokens, pos);
  2370. if (MATCH(SEMI))
  2371. c = parse_comma_expr(tokens, pos);
  2372. }
  2373. }
  2374. }
  2375. node_t *d = BLOCK();
  2376. LABELLOOP(NODE4(FOR, a, b, c, d));
  2377. return ln;
  2378. }
  2379. else if (MATCH(BREAK))
  2380. {
  2381. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  2382. return NODET(BREAK, tokens->data[(*pos)++]);
  2383. return NODE0(BREAK);
  2384. }
  2385. else if (MATCH(CONTINUE))
  2386. {
  2387. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  2388. return NODET(CONTINUE, tokens->data[(*pos)++]);
  2389. return NODE0(CONTINUE);
  2390. }
  2391. else if (MATCH(FUNC))
  2392. return parse_func(tokens, pos, 0);
  2393. else if (MATCH(RETURN))
  2394. {
  2395. node_t *a = NULL;
  2396. if (!AT(EOF) && !AT(RCB) && !CLIFF)
  2397. {
  2398. a = parse_expr(tokens, pos);
  2399. if (!CLIFF_AHEAD && MATCH(COMMA))
  2400. {
  2401. list_t *l = list_new();
  2402. list_push(l, a);
  2403. do
  2404. {
  2405. list_push(l, parse_expr(tokens, pos));
  2406. } while (!CLIFF_AHEAD && MATCH(COMMA));
  2407. a = NODEL(TUPLE, l);
  2408. }
  2409. }
  2410. return NODE1(RETURN, a);
  2411. }
  2412. else if (MATCH(DEFER))
  2413. {
  2414. node_t *a;
  2415. if (AT(LCB))
  2416. a = BLOCK();
  2417. else
  2418. a = parse_stmt(tokens, pos);
  2419. return NODE1(DEFER, a);
  2420. }
  2421. else if (MATCH(PASS))
  2422. return NODE0(PASS);
  2423. else if (MATCH(THROW))
  2424. {
  2425. node_t *a = NULL;
  2426. if (!CLIFF && !AT(COMMA) && !AT(RPAR) && !AT(RCB) && !AT(EOF))
  2427. a = parse_expr(tokens, pos);
  2428. return NODE1(THROW, a);
  2429. }
  2430. else if (MATCH(GOTO))
  2431. {
  2432. if (!AT(NAME))
  2433. PARSE_ERROR("expected identifier");
  2434. token_t *t = tokens->data[(*pos)++];
  2435. return NODET(GOTO, t);
  2436. }
  2437. else if (AT(NAME) && ATP(COLON, 1) && !CLIFF_AHEAD)
  2438. {
  2439. token_t *t = tokens->data[(*pos)++];
  2440. EXPECT(COLON, ":");
  2441. return NODET(LABEL, t);
  2442. }
  2443. else if (MATCH(CLASS))
  2444. {
  2445. if (!AT(NAME))
  2446. PARSE_ERROR("expected identifier");
  2447. token_t *t = tokens->data[(*pos)++];
  2448. list_t *l = NULL;
  2449. if (MATCH(LPAR))
  2450. {
  2451. l = list_new();
  2452. do
  2453. {
  2454. if (!AT(NAME))
  2455. PARSE_ERROR("expected identifier");
  2456. token_t *t = tokens->data[(*pos)++];
  2457. list_push(l, t);
  2458. } while (MATCH(COMMA));
  2459. EXPECT(RPAR, ")");
  2460. }
  2461. list_t *triples = list_new();
  2462. if (!CLIFF && !AT(EOF) && !AT(SEMI))
  2463. {
  2464. EXPECT(LCB, "{");
  2465. for (;;)
  2466. {
  2467. int is_out = 0;
  2468. int is_static = 0;
  2469. if (AT(RCB))
  2470. break;
  2471. if (MATCH(LET))
  2472. is_out = 1;
  2473. else if (MATCH(CONST))
  2474. is_static = 1;
  2475. if (!AT(NAME))
  2476. PARSE_ERROR("expected identifier");
  2477. list_t *triple = list_new();
  2478. token_t *t = tokens->data[(*pos)++];
  2479. list_push(triple, t);
  2480. int *flagp = malloc_checked(sizeof(int));
  2481. int flag = is_static ? 2 : is_out ? 1
  2482. : 0;
  2483. memcpy(flagp, &flag, sizeof(int));
  2484. if (MATCH(ASSIGN))
  2485. {
  2486. list_push(triple, flagp);
  2487. list_push(triple, parse_expr(tokens, pos));
  2488. }
  2489. else
  2490. {
  2491. list_push(triple, flagp);
  2492. list_push(triple, parse_func(tokens, pos, 1));
  2493. }
  2494. list_push(triples, triple);
  2495. }
  2496. EXPECT(RCB, "}");
  2497. }
  2498. list_t *pair = list_new();
  2499. list_push(pair, l);
  2500. list_push(pair, triples);
  2501. return NODETL(CLASS, t, pair);
  2502. }
  2503. else if (MATCH(DEL))
  2504. {
  2505. node_t *a = parse_expr(tokens, pos);
  2506. return NODE1(DEL, a);
  2507. }
  2508. else if (MATCH(WITH))
  2509. {
  2510. node_t *a = parse_expr(tokens, pos);
  2511. EXPECT(AS, "as");
  2512. if (!AT(NAME))
  2513. PARSE_ERROR("expected identifier");
  2514. token_t *t = tokens->data[(*pos)++];
  2515. node_t *b = STMT_OR_BLOCK();
  2516. return NODE2t(WITH, a, b, t);
  2517. }
  2518. else if (MATCH(INLINE))
  2519. {
  2520. if (!AT(STRING))
  2521. PARSE_ERROR("expected string");
  2522. token_t *t = tokens->data[(*pos)++];
  2523. return NODET(INLINE, t);
  2524. }
  2525. return NODE1(EXPRSTMT, allow_comma ? parse_comma_expr(tokens, pos)
  2526. : parse_expr(tokens, pos));
  2527. }
  2528. #define ATM(t) \
  2529. (AT(MVAR) && strcmp(((token_t *)tokens->data[*pos])->text, t) == 0)
  2530. #define MATCHM(t) (ATM(t) && MATCH(MVAR))
  2531. node_t *parse_mexpr(list_t *tokens, size_t *pos);
  2532. node_t *parse_mprimary(list_t *tokens, size_t *pos)
  2533. {
  2534. if (MATCH(STAR))
  2535. return NODET(LITERAL, token(T_NAME, strdup("*")));
  2536. else if (MATCHM("{"))
  2537. {
  2538. node_t *a = parse_stmt(tokens, pos);
  2539. if (!MATCHM("}"))
  2540. PARSE_ERROR("expected }$");
  2541. if (a->tag == N_EXPRSTMT)
  2542. a = a->a;
  2543. return NODE1(MSTMT, a);
  2544. }
  2545. else if (MATCH(LPAR))
  2546. {
  2547. node_t *a = parse_mexpr(tokens, pos);
  2548. EXPECT(RPAR, ")");
  2549. return a;
  2550. }
  2551. else if (MATCH(NAME) || MATCH(TRUE) || MATCH(FALSE) || MATCH(NIL))
  2552. {
  2553. token_t *t = tokens->data[(*pos) - 1];
  2554. int macro = 0;
  2555. if (!CLIFF && !CLIFF_AHEAD && AT(BANG) && ATP(LPAR, 1))
  2556. {
  2557. MATCH(BANG);
  2558. macro = 1;
  2559. }
  2560. if (!CLIFF && MATCH(LPAR))
  2561. {
  2562. list_t *args = list_new();
  2563. if (!AT(RPAR))
  2564. do
  2565. {
  2566. list_push(args, parse_mexpr(tokens, pos));
  2567. } while (MATCH(COMMA));
  2568. EXPECT(RPAR, ")");
  2569. if (macro)
  2570. return NODETL(MACRO_CALL, t, args);
  2571. return NODETL(CALL, t, args);
  2572. }
  2573. return NODET(LITERAL, t);
  2574. }
  2575. else if (MATCH(NUMBER) || MATCH(STRING))
  2576. return NODET(LITERAL, tokens->data[(*pos) - 1]);
  2577. PARSE_ERROR("expected m-expression");
  2578. return NULL;
  2579. }
  2580. node_t *parse_mexpr(list_t *tokens, size_t *pos)
  2581. {
  2582. if (MATCH(MINUS))
  2583. {
  2584. node_t *a = parse_mexpr(tokens, pos);
  2585. return NODE1(NEGATE, a);
  2586. }
  2587. node_t *a = parse_mprimary(tokens, pos);
  2588. do
  2589. {
  2590. if (MATCH(BAR))
  2591. {
  2592. node_t *b = parse_mprimary(tokens, pos);
  2593. a = NODE2(LOGOR, a, b);
  2594. continue;
  2595. }
  2596. else if (MATCH(AND))
  2597. {
  2598. node_t *b = parse_mprimary(tokens, pos);
  2599. a = NODE2(LOGAND, a, b);
  2600. continue;
  2601. }
  2602. else if (MATCH(PLUS))
  2603. {
  2604. node_t *b = parse_mprimary(tokens, pos);
  2605. a = NODE2(ADD, a, b);
  2606. continue;
  2607. }
  2608. else if (MATCH(MINUS))
  2609. {
  2610. node_t *b = parse_mprimary(tokens, pos);
  2611. a = NODE2(SUB, a, b);
  2612. continue;
  2613. }
  2614. else if (MATCH(STAR))
  2615. {
  2616. node_t *b = parse_mprimary(tokens, pos);
  2617. a = NODE2(MUL, a, b);
  2618. continue;
  2619. }
  2620. else if (MATCH(SLASH))
  2621. {
  2622. node_t *b = parse_mprimary(tokens, pos);
  2623. a = NODE2(DIV, a, b);
  2624. continue;
  2625. }
  2626. else if (MATCH(ASSIGN))
  2627. {
  2628. node_t *b = parse_mprimary(tokens, pos);
  2629. a = NODE2(EQUALS, a, b);
  2630. continue;
  2631. }
  2632. else if (MATCH(LT))
  2633. {
  2634. node_t *b = parse_mprimary(tokens, pos);
  2635. a = NODE2(LT, a, b);
  2636. continue;
  2637. }
  2638. else if (MATCH(GT))
  2639. {
  2640. node_t *b = parse_mprimary(tokens, pos);
  2641. a = NODE2(GT, a, b);
  2642. continue;
  2643. }
  2644. break;
  2645. } while (1);
  2646. return a;
  2647. }
  2648. node_t *parse_mstmt(list_t *tokens, size_t *pos);
  2649. node_t *parse_mif(list_t *tokens, size_t *pos, int sub)
  2650. {
  2651. node_t *a = parse_mexpr(tokens, pos);
  2652. list_t *l = list_new();
  2653. list_t *l2 = NULL;
  2654. while (!AT(EOF) && !ATM("else") && !ATM("elif") && !ATM("endif"))
  2655. list_push(l, parse_mstmt(tokens, pos));
  2656. if (MATCHM("elif"))
  2657. {
  2658. l2 = list_new();
  2659. list_push(l2, parse_mif(tokens, pos, 1));
  2660. }
  2661. else if (MATCHM("else"))
  2662. {
  2663. l2 = list_new();
  2664. while (!AT(EOF) && !ATM("endif"))
  2665. list_push(l2, parse_mstmt(tokens, pos));
  2666. }
  2667. if (!sub && !MATCHM("endif"))
  2668. PARSE_ERROR("expected $endif");
  2669. return NODE1l2(MIF, a, l, l2);
  2670. }
  2671. node_t *parse_mstmt(list_t *tokens, size_t *pos)
  2672. {
  2673. if (MATCHM("if"))
  2674. return parse_mif(tokens, pos, 0);
  2675. else if (MATCHM("for"))
  2676. {
  2677. node_t *a = parse_mexpr(tokens, pos);
  2678. list_t *l = list_new();
  2679. while (!AT(EOF) && !ATM("endfor"))
  2680. list_push(l, parse_mstmt(tokens, pos));
  2681. if (!MATCHM("endfor"))
  2682. PARSE_ERROR("expected $endfor");
  2683. return NODE1l(MFOR, a, l);
  2684. }
  2685. else if (MATCHM("repeat"))
  2686. {
  2687. node_t *a = parse_mexpr(tokens, pos);
  2688. list_t *l = list_new();
  2689. while (!AT(EOF) && !ATM("endrep"))
  2690. list_push(l, parse_mstmt(tokens, pos));
  2691. if (!MATCHM("endrep"))
  2692. PARSE_ERROR("expected $endrep");
  2693. return NODE1l(MREPEAT, a, l);
  2694. }
  2695. else if (MATCHM("set"))
  2696. {
  2697. if (!AT(NAME))
  2698. PARSE_ERROR("expected identifier");
  2699. token_t *t = tokens->data[(*pos)++];
  2700. node_t *a = parse_mexpr(tokens, pos);
  2701. return NODE1t(MSET, a, t);
  2702. }
  2703. else if (MATCHM("push"))
  2704. {
  2705. if (!AT(NAME))
  2706. PARSE_ERROR("expected identifier");
  2707. token_t *t = tokens->data[(*pos)++];
  2708. node_t *a = parse_mexpr(tokens, pos);
  2709. return NODE1t(MPUSH, a, t);
  2710. }
  2711. else if (MATCHM("$"))
  2712. {
  2713. node_t *a = parse_stmt(tokens, pos);
  2714. if (a->tag == N_EXPRSTMT)
  2715. a = a->a;
  2716. return NODE1(MSTMT, a);
  2717. }
  2718. else if (MATCHM("{"))
  2719. {
  2720. list_t *stmts = list_new();
  2721. while (!AT(EOF) && !ATM("}"))
  2722. {
  2723. list_push(stmts, parse_stmt(tokens, pos));
  2724. MATCH(SEMI);
  2725. }
  2726. if (!MATCHM("}"))
  2727. PARSE_ERROR("expected }$");
  2728. return NODE1(MSTMT, nodel(N_PROGRAM, stmts));
  2729. }
  2730. else if (MATCHM(":"))
  2731. return NODE1(MEXPR, parse_mexpr(tokens, pos));
  2732. node_t *a = parse_stmt(tokens, pos);
  2733. if (a->tag == N_EXPRSTMT)
  2734. a = a->a;
  2735. return a;
  2736. }
  2737. list_t *macros_get(char *name)
  2738. {
  2739. list_t *val = NULL;
  2740. for (ssize_t i = MACROS->length - 1; i >= 0; i--)
  2741. if ((val = table_get(MACROS->data[i], name)))
  2742. break;
  2743. return val;
  2744. }
  2745. node_t *parse_program(list_t *tokens, size_t *pos)
  2746. {
  2747. if (AT(EOF))
  2748. PARSE_ERROR("empty program");
  2749. list_t *stmts = list_new();
  2750. int flag = 0;
  2751. while (!AT(EOF) && *pos < tokens->length)
  2752. {
  2753. node_t *n = NULL;
  2754. if (MATCH(REQUIRE))
  2755. {
  2756. if (flag)
  2757. PARSE_ERROR("misplaced require statement")
  2758. list_t *paths = list_new();
  2759. do
  2760. {
  2761. if (!AT(STRING) && !AT(NAME))
  2762. PARSE_ERROR("expected string or identifier");
  2763. list_push(paths, tokens->data[(*pos)++]);
  2764. } while (MATCH(COMMA));
  2765. n = NODEL(REQUIRE, paths);
  2766. }
  2767. else if (MATCH(HEADER))
  2768. {
  2769. if (flag)
  2770. PARSE_ERROR("misplaced header statement")
  2771. if (!AT(STRING))
  2772. PARSE_ERROR("expected string");
  2773. token_t *text = tokens->data[(*pos)++];
  2774. n = NODET(HEADER, text);
  2775. }
  2776. else if (MATCH(INCLUDE))
  2777. {
  2778. if (flag)
  2779. PARSE_ERROR("misplaced include statement")
  2780. if (!AT(STRING))
  2781. PARSE_ERROR("expected string");
  2782. token_t *text = tokens->data[(*pos)++];
  2783. n = NODET(INCLUDE, text);
  2784. }
  2785. else if (MATCH(MACRO))
  2786. {
  2787. if (!AT(NAME))
  2788. PARSE_ERROR("expected identifier");
  2789. char *name = ((token_t *)tokens->data[(*pos)++])->text;
  2790. EXPECT(LPAR, "(");
  2791. int variable = 0;
  2792. list_t *params = list_new();
  2793. if (!AT(RPAR))
  2794. {
  2795. if (MATCH(STAR))
  2796. variable = 1;
  2797. else
  2798. do
  2799. {
  2800. if (!AT(NAME))
  2801. PARSE_ERROR("expected identifier");
  2802. list_push(params, tokens->data[(*pos)++]);
  2803. } while (MATCH(COMMA));
  2804. }
  2805. EXPECT(RPAR, ")");
  2806. list_t *body = list_new();
  2807. if (MATCH(COLON) || !AT(LCB))
  2808. list_push(body, parse_mstmt(tokens, pos));
  2809. else
  2810. {
  2811. EXPECT(LCB, "{");
  2812. while (!AT(EOF) && !AT(RCB))
  2813. list_push(body, parse_mstmt(tokens, pos));
  2814. EXPECT(RCB, "}");
  2815. }
  2816. list_t *ms = macros_get(name);
  2817. if (!ms)
  2818. {
  2819. ms = list_new();
  2820. table_set(list_index(MACROS, -1), name, ms);
  2821. }
  2822. macro_t *m = malloc_checked(sizeof(macro_t));
  2823. m->name = name;
  2824. m->params = params;
  2825. m->body = body;
  2826. m->variable = variable;
  2827. list_push(ms, m);
  2828. }
  2829. else
  2830. {
  2831. n = parse_stmt_c(tokens, pos);
  2832. flag = 1;
  2833. }
  2834. MATCH(SEMI);
  2835. if (n)
  2836. list_push(stmts, n);
  2837. }
  2838. return NODEL(TOPLEVEL, stmts);
  2839. }
  2840. node_t *parse(char *source)
  2841. {
  2842. size_t pos = 0;
  2843. return parse_program(tokenize(source), &pos);
  2844. }
  2845. #define NEWGID() size_t gid = GID++
  2846. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  2847. #define BINOP(s) \
  2848. { \
  2849. EMIT("qi_" s "(state, "); \
  2850. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); \
  2851. EMIT(", "); \
  2852. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b); \
  2853. EMIT(")"); \
  2854. }
  2855. #define UNOP(s) \
  2856. { \
  2857. EMIT("qi_" s "(state, "); \
  2858. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); \
  2859. EMIT(")"); \
  2860. }
  2861. #define ASSIGNIN(buf, lhs, rhs, prefix) \
  2862. { \
  2863. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) \
  2864. { \
  2865. buffer_fmt(buf, "qi_set(state, " #prefix ", \"%s\", ", (lhs)->t->text); \
  2866. rhs; \
  2867. buffer_fmt(buf, ")"); \
  2868. } \
  2869. else if ((lhs)->tag == N_INDEX) \
  2870. { \
  2871. buffer_fmt(buf, "qi_index_set(state, " #prefix ", "); \
  2872. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a); \
  2873. buffer_fmt(buf, ", "); \
  2874. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->b); \
  2875. buffer_fmt(buf, ", "); \
  2876. rhs; \
  2877. buffer_fmt(buf, ")"); \
  2878. } \
  2879. else if ((lhs)->tag == N_MEMBER) \
  2880. { \
  2881. buffer_fmt(buf, "qi_index_set(state, " #prefix ", "); \
  2882. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a); \
  2883. buffer_fmt(buf, ", qi_make_string(state, \"%s\"), ", (lhs)->t->text); \
  2884. rhs; \
  2885. buffer_fmt(buf, ")"); \
  2886. } \
  2887. else if ((lhs)->tag == N_DEREFERENCE) \
  2888. { \
  2889. buffer_fmt(buf, "qi_set_ref(state, " #prefix ", "); \
  2890. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a); \
  2891. buffer_fmt(buf, ", "); \
  2892. rhs; \
  2893. buffer_fmt(buf, ")"); \
  2894. } \
  2895. else \
  2896. COMPILE_ERROR("illegal assignment left-hand side"); \
  2897. }
  2898. #define ASSIGN(lhs, rhs) ASSIGNIN(buf, lhs, rhs, false)
  2899. #define DECLIN(buf, lhs, rhs) \
  2900. { \
  2901. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) \
  2902. { \
  2903. buffer_fmt(buf, "qi_decl_expr(state, \"%s\", ", (lhs)->t->text); \
  2904. rhs; \
  2905. buffer_fmt(buf, ")"); \
  2906. } \
  2907. else \
  2908. COMPILE_ERROR("illegal declaration left-hand side"); \
  2909. }
  2910. #define DECL(lhs, rhs) DECLIN(buf, lhs, rhs)
  2911. #define COMPASSIGN(lhs, s, rhs) \
  2912. { \
  2913. ASSIGN(node->a, { \
  2914. EMIT("qi_%s(state, ", s); \
  2915. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)); \
  2916. EMIT(", "); \
  2917. rhs; \
  2918. EMIT(")"); \
  2919. }); \
  2920. }
  2921. #define COMPASSIGNP(lhs, s, rhs) \
  2922. { \
  2923. ASSIGNIN( \
  2924. buf, node->a, \
  2925. { \
  2926. EMIT("qi_%s(state, ", s); \
  2927. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)); \
  2928. EMIT(", "); \
  2929. rhs; \
  2930. EMIT(")"); \
  2931. }, \
  2932. true); \
  2933. }
  2934. #define COMPILE_ERROR(fmt, ...) \
  2935. { \
  2936. if (MACROCALLS->length) \
  2937. { \
  2938. format_error(GETFNAME(((node_t *)MACROCALLS->data[MACROCALLS->length - 1])->fi), \
  2939. GETSRC(((node_t *)MACROCALLS->data[MACROCALLS->length - 1])->fi), \
  2940. ((node_t *)MACROCALLS->data[MACROCALLS->length - 1])->pos, fmt, \
  2941. ##__VA_ARGS__); \
  2942. format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, \
  2943. "after the expansion of macro:"); \
  2944. } \
  2945. else \
  2946. format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, \
  2947. ##__VA_ARGS__); \
  2948. exit(1); \
  2949. }
  2950. #define COMPILE_NOTE(fmt, ...) \
  2951. { \
  2952. format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, \
  2953. ##__VA_ARGS__); \
  2954. }
  2955. list_t *MACROCALLS;
  2956. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2957. list_t *lstk, list_t *sstk, list_t *lbl, node_t *node);
  2958. char *tempvar()
  2959. {
  2960. NEWGID();
  2961. char *s = malloc_checked(sizeof(char) * (64 + strlen(PREFIX)));
  2962. snprintf(s, 64 + strlen(PREFIX), "__%s%zu", PREFIX, gid);
  2963. return s;
  2964. }
  2965. void compile_list(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  2966. list_t *lstk, list_t *sstk, list_t *lbl, list_t *seq)
  2967. {
  2968. if (!seq || seq->length < 1)
  2969. {
  2970. EMIT("NULL");
  2971. return;
  2972. }
  2973. int has_star = 0;
  2974. for (size_t i = 0; i < seq->length; i++)
  2975. if (((node_t *)seq->data[i])->tag == N_STAR)
  2976. {
  2977. has_star = 1;
  2978. break;
  2979. }
  2980. buffer_t *tbuf = buffer_new();
  2981. NEWGID();
  2982. buffer_fmt(tbuf, "inline static qi_list_t *__%s%d(qi_state_t *state) {\n",
  2983. PREFIX, gid);
  2984. if (has_star)
  2985. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  2986. else
  2987. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make_n(%d);\n", seq->length);
  2988. for (size_t i = 0; i < seq->length; i++)
  2989. {
  2990. node_t *node = seq->data[i];
  2991. if (!has_star)
  2992. {
  2993. buffer_fmt(tbuf, "qi_list_data(list, %d) = ", i);
  2994. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  2995. buffer_fmt(tbuf, ";\n");
  2996. continue;
  2997. }
  2998. if (node->tag == N_STAR)
  2999. {
  3000. char *varname = tempvar();
  3001. buffer_fmt(tbuf, "qi_value_t *%s = qi_iter(state, ", varname);
  3002. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3003. buffer_fmt(tbuf, ");\n");
  3004. buffer_fmt(tbuf,
  3005. "for (qi_size_t i = 0; i < %s->value.list->length; i++)\n",
  3006. varname);
  3007. buffer_fmt(tbuf,
  3008. "qi_list_push(list, qi_index(state, %s, qi_make_number(state, "
  3009. "i)));\n",
  3010. varname);
  3011. }
  3012. else
  3013. {
  3014. buffer_fmt(tbuf, "qi_list_push(list, ");
  3015. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  3016. buffer_fmt(tbuf, ");\n");
  3017. }
  3018. }
  3019. buffer_fmt(tbuf, "return list;\n");
  3020. buffer_fmt(tbuf, "}\n");
  3021. buffer_appendb(gbuf, tbuf);
  3022. EMIT("__%s%d(state)", PREFIX, gid);
  3023. }
  3024. void compile_table(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3025. list_t *lstk, list_t *sstk, list_t *lbl, table_t *table)
  3026. {
  3027. if (!table || table->used < 1)
  3028. {
  3029. EMIT("NULL");
  3030. return;
  3031. }
  3032. buffer_t *tbuf = buffer_new();
  3033. NEWGID();
  3034. buffer_fmt(tbuf, "inline static qi_table_t *__%s%d(qi_state_t *state) {\n",
  3035. PREFIX, gid);
  3036. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  3037. table_iterate(table, {
  3038. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  3039. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, entry.value);
  3040. buffer_fmt(tbuf, ");\n");
  3041. });
  3042. buffer_fmt(tbuf, "return table;\n");
  3043. buffer_fmt(tbuf, "}\n");
  3044. buffer_appendb(gbuf, tbuf);
  3045. EMIT("__%s%d(state)", PREFIX, gid);
  3046. }
  3047. void compile_pairs(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3048. list_t *lstk, list_t *sstk, list_t *lbl, list_t *pairs)
  3049. {
  3050. if (!pairs || pairs->length < 1)
  3051. {
  3052. EMIT("NULL");
  3053. return;
  3054. }
  3055. buffer_t *tbuf = buffer_new();
  3056. NEWGID();
  3057. buffer_fmt(tbuf, "inline static qi_table_t *__%s%d(qi_state_t *state) {\n",
  3058. PREFIX, gid);
  3059. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  3060. for (size_t i = 0; i < pairs->length; i++)
  3061. {
  3062. list_t *pair = pairs->data[i];
  3063. buffer_fmt(tbuf, "qi_table_set(table, qi_to_string(state, ");
  3064. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  3065. buffer_fmt(tbuf, ")->value.string, ");
  3066. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  3067. buffer_fmt(tbuf, ");\n");
  3068. }
  3069. buffer_fmt(tbuf, "return table;\n");
  3070. buffer_fmt(tbuf, "}\n");
  3071. buffer_appendb(gbuf, tbuf);
  3072. EMIT("__%s%d(state)", PREFIX, gid);
  3073. }
  3074. #define CTXPUSH(s) list_push(ctx, (s))
  3075. #define CTXPOP() list_pop(ctx)
  3076. int in_context(list_t *ctx, char *s)
  3077. {
  3078. if (!ctx->length)
  3079. return 0;
  3080. for (ssize_t i = ctx->length - 1; i >= 0; i--)
  3081. if (strcmp(ctx->data[i], "gap") == 0)
  3082. break;
  3083. else if (strcmp(ctx->data[i], s) == 0)
  3084. return 1;
  3085. return 0;
  3086. }
  3087. int in_switch(list_t *ctx)
  3088. {
  3089. if (!ctx->length)
  3090. return 0;
  3091. for (ssize_t i = ctx->length - 1; i >= 0; i--)
  3092. if (strcmp(ctx->data[i], "gap") == 0 || strcmp(ctx->data[i], "for") == 0)
  3093. break;
  3094. else if (strcmp(ctx->data[i], "switch") == 0)
  3095. return 1;
  3096. return 0;
  3097. }
  3098. size_t count_ctxs(list_t *ctx, char *s)
  3099. {
  3100. if (!ctx->length)
  3101. return 0;
  3102. size_t k = 0;
  3103. for (ssize_t i = ctx->length - 1; i >= 0; i--)
  3104. if (strcmp(ctx->data[i], "gap") == 0)
  3105. break;
  3106. else if (strcmp(ctx->data[i], s) == 0)
  3107. k++;
  3108. return k;
  3109. }
  3110. list_t *CONSTANTS;
  3111. #define INCTX(s) (in_context(ctx, (s)))
  3112. #define SCOPESK (count_ctxs(ctx, "scope"))
  3113. #define TRAPSK (count_ctxs(ctx, "trap"))
  3114. #define LPUSH(i) \
  3115. { \
  3116. int_stack_t *pair = stack_new(); \
  3117. stack_push(pair, (i)); \
  3118. stack_push(pair, scope_index(ctx)); \
  3119. list_push(lstk, pair); \
  3120. }
  3121. #define LPOP() list_pop(lstk)
  3122. #define LID (((int_stack_t *)lstk->data[lstk->length - 1])->data[0])
  3123. #define SPUSH(i) \
  3124. { \
  3125. int_stack_t *pair = stack_new(); \
  3126. stack_push(pair, (i)); \
  3127. stack_push(pair, scope_index(ctx)); \
  3128. list_push(sstk, pair); \
  3129. }
  3130. #define SPOP() list_pop(sstk)
  3131. #define SID (sstk->data[sstk->length - 1]->data[0])
  3132. #define LBPUSH() list_push(lbl, table_new())
  3133. #define LBPOP() list_pop(lbl)
  3134. size_t insert_debug(node_t *node)
  3135. {
  3136. size_t line;
  3137. (void)traverse(GETSRC(node->fi), node->pos, &line, NULL);
  3138. buffer_t *tbuf = buffer_new();
  3139. buffer_fmt(tbuf, "File \"%s\", line %d", GETFNAME(node->fi), line);
  3140. if (FUNCNAMES->length)
  3141. buffer_fmt(tbuf, ", in %s", list_index(FUNCNAMES, -1));
  3142. list_push(DEBUGDATA, buffer_read(tbuf));
  3143. return DEBUGDATA->length - 1;
  3144. }
  3145. void emit_debug(buffer_t *buf, node_t *node)
  3146. {
  3147. buffer_fmt(buf, "state->_debug_data = __debugData[%d];\n",
  3148. insert_debug(node));
  3149. }
  3150. void compile_func(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3151. list_t *lstk, list_t *sstk, list_t *lbl, node_t *node,
  3152. char *name)
  3153. {
  3154. NEWGID();
  3155. char *funname = name ? name : node->t ? node->t->text
  3156. : "<anon>";
  3157. buffer_t *tbuf = buffer_new();
  3158. buffer_fmt(tbuf,
  3159. "qi_value_t *__%s%d(qi_state_t *state, qi_size_t pargc, qi_list_t "
  3160. "*pargs) {\n",
  3161. PREFIX, gid);
  3162. LBPUSH();
  3163. CTXPUSH("gap");
  3164. CTXPUSH("func");
  3165. list_push(CONSTANTS, table_new());
  3166. list_push(MACROS, table_new());
  3167. list_push(FUNCNAMES, funname);
  3168. if (DEBUG)
  3169. emit_debug(tbuf, node);
  3170. size_t optargc = 0;
  3171. if (node->h)
  3172. {
  3173. table_iterate(node->h, {
  3174. list_t *pair = entry.value;
  3175. size_t argc = *(size_t *)pair->data[0];
  3176. if (pair->data[1])
  3177. {
  3178. optargc++;
  3179. buffer_fmt(
  3180. tbuf,
  3181. "qi_decl(state, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ",
  3182. entry.key, argc + 1, argc);
  3183. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  3184. buffer_fmt(tbuf, ");\n");
  3185. }
  3186. else if (strcmp(entry.key, "_") != 0)
  3187. buffer_fmt(tbuf, "qi_decl(state, \"%s\", qi_list_index(pargs, %d));\n",
  3188. entry.key, argc);
  3189. argc++;
  3190. });
  3191. }
  3192. compile_node(gbuf, tbuf, ctx, table_new(), list_new(), list_new(), lbl,
  3193. node->a);
  3194. list_pop(FUNCNAMES);
  3195. list_pop(MACROS);
  3196. list_pop(CONSTANTS);
  3197. CTXPOP();
  3198. CTXPOP();
  3199. LBPOP();
  3200. buffer_fmt(tbuf, "return state->nil;\n");
  3201. buffer_fmt(tbuf, "}\n");
  3202. buffer_appendb(gbuf, tbuf);
  3203. tbuf = buffer_new();
  3204. buffer_fmt(tbuf, "qi_make_function(state, \"%s\", %d, __%s%d, ", funname,
  3205. !node->h ? 0 : (node->h->used - optargc), PREFIX, gid);
  3206. compile_table(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->h2);
  3207. buffer_fmt(tbuf, ")");
  3208. if (node->tag == N_FUNCEXPR)
  3209. {
  3210. buffer_appendb(buf, tbuf);
  3211. return;
  3212. }
  3213. EMIT("qi_decl(state, \"%s\", ", node->t->text);
  3214. buffer_appendb(buf, tbuf);
  3215. EMIT(");");
  3216. }
  3217. int const_set(char *name, node_t *val)
  3218. {
  3219. table_t *table = list_index(CONSTANTS, -1);
  3220. if (table_get(table, name))
  3221. return 0;
  3222. table_set(table, name, val);
  3223. return 1;
  3224. }
  3225. node_t *const_get(char *name)
  3226. {
  3227. node_t *val = NULL;
  3228. for (ssize_t i = CONSTANTS->length - 1; i >= 0; i--)
  3229. if ((val = table_get(CONSTANTS->data[i], name)))
  3230. break;
  3231. return val;
  3232. }
  3233. size_t count_scopes(list_t *ctx, size_t offset)
  3234. {
  3235. if (ctx->length < 2 || offset >= ctx->length)
  3236. return 0;
  3237. size_t k = 0;
  3238. for (ssize_t i = ctx->length - 1; i >= 0 && i > offset; i--)
  3239. if (strcmp(ctx->data[i], "gap") == 0)
  3240. break;
  3241. else if (strcmp(ctx->data[i], "scope") == 0)
  3242. k++;
  3243. return k;
  3244. }
  3245. size_t scope_index(list_t *ctx)
  3246. {
  3247. if (ctx->length < 2)
  3248. return 0;
  3249. for (ssize_t i = ctx->length - 1; i >= 0; i--)
  3250. if (strcmp(ctx->data[i], "gap") == 0)
  3251. break;
  3252. else if (strcmp(ctx->data[i], "scope") == 0)
  3253. return i;
  3254. return 0;
  3255. }
  3256. void compile_block(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3257. list_t *lstk, list_t *sstk, list_t *lbl, list_t *block)
  3258. {
  3259. for (size_t i = 0; i < block->length; i++)
  3260. {
  3261. node_t *node = block->data[i];
  3262. if (node->tag == N_CONST)
  3263. {
  3264. table_iterate(node->h, {
  3265. char *name = entry.key;
  3266. if (!const_set(name, entry.value))
  3267. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  3268. });
  3269. }
  3270. else if (node->tag == N_ENUM)
  3271. {
  3272. size_t k = 0;
  3273. table_iterate(node->h, {
  3274. char *name = entry.key;
  3275. node_t *v = entry.value;
  3276. if (!v)
  3277. {
  3278. char buf[128];
  3279. snprintf(buf, sizeof(buf), "%zu", k++);
  3280. v = nodet(N_LITERAL, token(T_NUMBER, strdup(buf)));
  3281. }
  3282. else
  3283. k++;
  3284. if (!const_set(name, v))
  3285. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  3286. });
  3287. }
  3288. else if (node->tag == N_FUNCDEF)
  3289. {
  3290. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  3291. EMIT("\n");
  3292. }
  3293. else if (node->tag == N_CLASS)
  3294. {
  3295. NEWGID();
  3296. char *name = node->t->text;
  3297. list_t *supers = list_index(node->l, 0);
  3298. list_t *triples = list_index(node->l, 1);
  3299. buffer_t *tbuf = buffer_new();
  3300. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX,
  3301. gid);
  3302. buffer_fmt(tbuf, "qi_list_t *supers = qi_list_make_n(%d);\n",
  3303. !supers ? 0 : supers->length);
  3304. if (supers)
  3305. for (size_t i = 0; i < supers->length; i++)
  3306. {
  3307. token_t *t = supers->data[i];
  3308. buffer_fmt(tbuf,
  3309. "qi_list_data(supers, %d) = qi_get(state, \"%s\");\n", i,
  3310. t->text);
  3311. }
  3312. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  3313. buffer_fmt(tbuf, "qi_table_t *metatable = qi_table_make();\n");
  3314. buffer_fmt(tbuf, "qi_table_t *statictable = qi_table_make();\n");
  3315. for (size_t i = 0; i < triples->length; i++)
  3316. {
  3317. list_t *triple = triples->data[i];
  3318. token_t *t = triple->data[0];
  3319. int flag = *(int *)triple->data[1];
  3320. if (flag == 0)
  3321. {
  3322. buffer_fmt(tbuf, "qi_table_set(metatable, \"%s\", ", t->text);
  3323. if (((node_t *)triple->data[2])->tag == N_FUNCEXPR)
  3324. {
  3325. buffer_t *methodname = buffer_new();
  3326. buffer_fmt(methodname, "%s.%s", name, t->text);
  3327. compile_func(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  3328. triple->data[2], buffer_read(methodname));
  3329. }
  3330. else
  3331. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  3332. triple->data[2]);
  3333. }
  3334. else
  3335. {
  3336. buffer_fmt(tbuf, "qi_table_set(%s, \"%s\", ",
  3337. flag == 1 ? "table" : "statictable", t->text);
  3338. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2]);
  3339. }
  3340. buffer_fmt(tbuf, ");\n");
  3341. }
  3342. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(5);\n");
  3343. buffer_fmt(tbuf,
  3344. "qi_list_data(pargs, 0) = qi_make_string(state, \"%s\");\n",
  3345. name);
  3346. buffer_fmt(tbuf,
  3347. "qi_list_data(pargs, 1) = qi_make_list(state, supers);\n");
  3348. buffer_fmt(tbuf,
  3349. "qi_list_data(pargs, 2) = qi_make_table(state, table);\n");
  3350. buffer_fmt(tbuf,
  3351. "qi_list_data(pargs, 3) = qi_make_table(state, metatable);\n");
  3352. buffer_fmt(
  3353. tbuf,
  3354. "qi_list_data(pargs, 4) = qi_make_table(state, statictable);\n");
  3355. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, "
  3356. "\"__class_wrapper\"), pargs);\n");
  3357. buffer_fmt(tbuf, "}\n");
  3358. buffer_appendb(gbuf, tbuf);
  3359. EMIT("qi_set(state, false, \"%s\", __%s%d(state));", name, PREFIX, gid);
  3360. }
  3361. else if (node->tag == N_LABEL)
  3362. {
  3363. char *label = node->t->text;
  3364. if (table_get(list_index(lbl, -1), label))
  3365. COMPILE_ERROR("duplicated label: '%s'", label);
  3366. NEWGID();
  3367. int_stack_t *pair = stack_new();
  3368. stack_push(pair, gid);
  3369. stack_push(pair, scope_index(ctx));
  3370. table_set(list_index(lbl, -1), label, pair);
  3371. }
  3372. }
  3373. for (size_t i = 0; i < block->length; i++)
  3374. {
  3375. node_t *n = block->data[i];
  3376. if (n->tag == N_CONST || n->tag == N_ENUM || n->tag == N_FUNCDEF ||
  3377. n->tag == N_CLASS || n->tag == N_PASS)
  3378. continue;
  3379. if (DEBUG)
  3380. emit_debug(buf, n);
  3381. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  3382. EMIT("\n");
  3383. }
  3384. }
  3385. const char *STD[][2] = {
  3386. {"json",
  3387. "require \"string\"\n"
  3388. "class JSONError(Error)\n"
  3389. "func json_tokenize(s) {\n"
  3390. " let toks = []\n"
  3391. " for var i = 0; i < len(s); i++ {\n"
  3392. " if isws(s[i])\n"
  3393. " continue\n"
  3394. " if s[i] in \"[]{}:,\"\n"
  3395. " toks.push((s[i], nil))\n"
  3396. " elif isalpha(s[i]) {\n"
  3397. " var text = \"\"\n"
  3398. " for i < len(s) && isalpha(s[i])\n"
  3399. " text += s[i++]\n"
  3400. " i--\n"
  3401. " toks.push((\"name\", text))\n"
  3402. " } elif s[i] == '-' || isdigit(s[i]) {\n"
  3403. " var text = \"\"\n"
  3404. " if s[i] == '-'\n"
  3405. " text += s[i++]\n"
  3406. " if i >= len(s) || !isdigit(s[i])\n"
  3407. " throw JSONError(f\"${i}: malformed number literal\")\n"
  3408. " for i < len(s) && isdigit(s[i]) {\n"
  3409. " text += s[i++]\n"
  3410. " if i < len(s) && s[i] == \".\" && \".\" !in text\n"
  3411. " text += s[i++]\n"
  3412. " }\n"
  3413. " i--\n"
  3414. " toks.push((\"number\", text))\n"
  3415. " } elif s[i] == '\"' {\n"
  3416. " var text = \"\"\n"
  3417. " i++\n"
  3418. " for i < len(s) && s[i] != '\"' {\n"
  3419. " var c = s[i++]\n"
  3420. " if c == `\\` {\n"
  3421. " if i >= len(s)\n"
  3422. " throw JSONError(f\"#${i}: unterminated string literal\")\n"
  3423. " switch s[i] {\n"
  3424. " case \"n\":\n"
  3425. " c = \"\\n\"\n"
  3426. " break\n"
  3427. " case \"r\":\n"
  3428. " c = \"\\r\"\n"
  3429. " break\n"
  3430. " case \"t\":\n"
  3431. " c = \"\\t\"\n"
  3432. " break\n"
  3433. " }\n"
  3434. " i++\n"
  3435. " }\n"
  3436. " text += c\n"
  3437. " }\n"
  3438. " if i >= len(s) || s[i] != '\"'\n"
  3439. " throw JSONError(f\"#${i}: unterminated string literal\")\n"
  3440. " toks.push((\"string\", text))\n"
  3441. " } else\n"
  3442. " throw JSONError(f\"#${i}: unknown input\")\n"
  3443. " }\n"
  3444. " return toks\n"
  3445. "}\n"
  3446. "func json_parse(toks) {\n"
  3447. " func parse_array(toks) {\n"
  3448. " let r = []\n"
  3449. " if toks && toks[0][0] == ']'\n"
  3450. " return r, toks[1:]\n"
  3451. " for {\n"
  3452. " var e\n"
  3453. " [e, toks] = parse_expression(toks)\n"
  3454. " r.push(e)\n"
  3455. " if !toks || toks[0][0] != ','\n"
  3456. " break\n"
  3457. " if toks[0][0] == \",\"\n"
  3458. " toks = toks[1:]\n"
  3459. " }\n"
  3460. " if !toks || toks[0][0] != ']'\n"
  3461. " throw JSONError(\"missing ]\")\n"
  3462. " return r, toks[1:]\n"
  3463. " }\n"
  3464. " func parse_object(toks) {\n"
  3465. " let r = {}\n"
  3466. " if toks && toks[0][0] == \"}\"\n"
  3467. " return r, toks[1:]\n"
  3468. " for {\n"
  3469. " var k, e\n"
  3470. " if !toks || toks[0][0] != \"string\"\n"
  3471. " throw JSONError(\"expected string\")\n"
  3472. " k = toks[0][1]\n"
  3473. " toks = toks[1:]\n"
  3474. " if !toks || toks[0][0] != \":\"\n"
  3475. " throw JSONError(\"expected :\")\n"
  3476. " toks = toks[1:]\n"
  3477. " [e, toks] = parse_expression(toks)\n"
  3478. " r[k] = e\n"
  3479. " if !toks || toks[0][0] != \",\"\n"
  3480. " break\n"
  3481. " if toks[0][0] == \",\"\n"
  3482. " toks = toks[1:]\n"
  3483. " }\n"
  3484. " if !toks || toks[0][0] != \"}\"\n"
  3485. " throw JSONError(\"missing }\")\n"
  3486. " return r, toks[1:]\n"
  3487. " }\n"
  3488. " func parse_expression(toks) {\n"
  3489. " if toks\n"
  3490. " switch toks[0][0] {\n"
  3491. " case \"{\":\n"
  3492. " return parse_object(toks[1:])\n"
  3493. " case \"[\":\n"
  3494. " return parse_array(toks[1:])\n"
  3495. " case \"name\":\n"
  3496. " switch toks[0][1] {\n"
  3497. " case \"true\":\n"
  3498. " return true, toks[1:]\n"
  3499. " case \"false\":\n"
  3500. " return false, toks[1:]\n"
  3501. " case \"null\":\n"
  3502. " return nil, toks[1:]\n"
  3503. " }\n"
  3504. " throw JSONError(f\"illegal name: ${toks[0][1]}\")\n"
  3505. " case \"number\":\n"
  3506. " return num(toks[0][1]), toks[1:]\n"
  3507. " case \"string\":\n"
  3508. " return toks[0][1], toks[1:]\n"
  3509. " }\n"
  3510. " throw JSONError(\"expected expression\")\n"
  3511. " }\n"
  3512. " if !toks\n"
  3513. " throw JSONError(\"empty document\")\n"
  3514. " if toks[0][0] !in \"{[\"\n"
  3515. " throw JSONError(\"expected { or [\")\n"
  3516. " let [r, unconsumed] = parse_expression(toks)\n"
  3517. " if unconsumed\n"
  3518. " throw JSONError(\"unconsumed input\")\n"
  3519. " return r\n"
  3520. "}\n"
  3521. "func json_read(s)\n"
  3522. " return json_parse(json_tokenize(s))\n"
  3523. "func json_dump(d) {\n"
  3524. " func escape(s) {\n"
  3525. " var r = \"\"\n"
  3526. " \n"
  3527. " for var c of s {\n"
  3528. " if c == `\\`\n"
  3529. " r += `\\\\`\n"
  3530. " elif c == '\"'\n"
  3531. " r += `\\\"`\n"
  3532. " elif c == \"\\n\"\n"
  3533. " r += `\\n`\n"
  3534. " elif c == \"\\r\"\n"
  3535. " r += `\\r`\n"
  3536. " elif c == \"\\t\"\n"
  3537. " r += `\\t`\n"
  3538. " else r += c\n"
  3539. " }\n"
  3540. " return r\n"
  3541. " }\n"
  3542. " switch type(d) {\n"
  3543. " case \"nil\":\n"
  3544. " return \"null\"\n"
  3545. " case \"bool\":\n"
  3546. " return d? \"true\": \"false\"\n"
  3547. " case \"number\":\n"
  3548. " return str(d)\n"
  3549. " case \"string\":\n"
  3550. " return \"\\\"\" + escape(d) + \"\\\"\"\n"
  3551. " case \"list\":\n"
  3552. " var f = true\n"
  3553. " var buf = \"[\"\n"
  3554. " for var el of d {\n"
  3555. " if f\n"
  3556. " f = false\n"
  3557. " else\n"
  3558. " buf += \", \"\n"
  3559. " buf += json_dump(el) \n"
  3560. " }\n"
  3561. " buf += \"]\"\n"
  3562. " return buf\n"
  3563. " case \"table\":\n"
  3564. " var f = true\n"
  3565. " var buf = \"{\"\n"
  3566. " for var [k, v] of enumerate(d) {\n"
  3567. " if f\n"
  3568. " f = false\n"
  3569. " else\n"
  3570. " buf += \", \"\n"
  3571. " buf += f`\"${escape(k)}\": ${json_dump(v)}`\n"
  3572. " }\n"
  3573. " buf += \"}\"\n"
  3574. " return buf\n"
  3575. " }\n"
  3576. " throw JSONError(f\"cannot serialize ${type(d)} into a JSON\")\n"
  3577. "}\n"},
  3578. {"utf8", "func utf8_chrlen(s) {\n"
  3579. " s = bytes(s)\n"
  3580. " var z = len(s)\n"
  3581. " if z < 2\n"
  3582. " return z\n"
  3583. " var l = 1\n"
  3584. " for var i = 1; i < z && (s[i] & 0xc0) == 0x80; i++\n"
  3585. " l++\n"
  3586. " return l\n"
  3587. "}\n"
  3588. "func utf8_decode(s) {\n"
  3589. " s = bytes(s)\n"
  3590. " var l = utf8_chrlen(s)\n"
  3591. " if !l\n"
  3592. " throw ValueError(\"malformed sequence\")\n"
  3593. " var c = (s[0] & ((1 << (8 - l)) - 1)) << (l - 1) * 6\n"
  3594. " for var i = 1; i < l; i++\n"
  3595. " c |= (s[i] & 0x3f) << (l - i - 1) * 6\n"
  3596. " return (c, l)\n"
  3597. "}\n"
  3598. "func utf8_encode(c) {\n"
  3599. " if c <= 0x7f\n"
  3600. " return bytes([c & 0xFF])\n"
  3601. " elif c >= 0x80 && c <= 0x7ff\n"
  3602. " return bytes([0xC0 | ((c >> 6) & 0x1f), 0x80 | (c & 0x3f)])\n"
  3603. " elif c >= 0x800 && c <= 0xfff\n"
  3604. " return bytes([0xe0 | ((c >> 12) & 0xf), 0x80 | ((c >> 6) & "
  3605. "0x3f), 0x80 | (c & 0x3f)])\n"
  3606. " elif c >= 0x10000 && c <= 0x10ffff\n"
  3607. " return bytes([0xf0 | ((c >> 18) & 0x7), 0x80 | ((c >> 12) & "
  3608. "0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  3609. " throw ValueError(\"malformed codepoint\")\n"
  3610. "}\n"
  3611. "class ustr {\n"
  3612. " _ucs = nil\n"
  3613. " constructor (this, s=\"\") {\n"
  3614. " if type(s) == \"list\" && all(map(func (x): type(x) == "
  3615. "\"number\", s)) {\n"
  3616. " this._ucs = s\n"
  3617. " return\n"
  3618. " }\n"
  3619. " s = str(s)\n"
  3620. " this._ucs = []\n"
  3621. " for var i = 0; i < len(s) {\n"
  3622. " let [c, l] = utf8_decode(slice(s, i))\n"
  3623. " this._ucs.push(c)\n"
  3624. " i += l\n"
  3625. " }\n"
  3626. " }\n"
  3627. " nth (this, i): this._ucs[i]\n"
  3628. " __type (this): \"ustr\"\n"
  3629. " __str (this) {\n"
  3630. " var s = \"\"\n"
  3631. " for var uc of this._ucs\n"
  3632. " s += str(utf8_encode(uc))\n"
  3633. " return s\n"
  3634. " }\n"
  3635. " __repr (this): repr(str(this))\n"
  3636. " __len (this): len(this._ucs)\n"
  3637. " __index (this, i): ustr([this._ucs[i]])\n"
  3638. " __index_set (this): throw\n"
  3639. " __iter (this): this._ucs\n"
  3640. " __list (this): list_copy(this._ucs)\n"
  3641. " __add (this, other) {\n"
  3642. " if type(other) != \"ustr\"\n"
  3643. " throw\n"
  3644. " return ustr(this._ucs + other._ucs)\n"
  3645. " }\n"
  3646. " __equals (this, other) {\n"
  3647. " if type(other) != \"ustr\"\n"
  3648. " return false\n"
  3649. " return this._ucs == other._ucs\n"
  3650. " }\n"
  3651. " __in (this, other) {\n"
  3652. " if type(other) !in (\"ustr\", \"str\")\n"
  3653. " throw\n"
  3654. " return str(this) in str(other)\n"
  3655. " }\n"
  3656. "}\n"},
  3657. {"thread",
  3658. "include `pthread.h`\n"
  3659. "func thread_create(fn, args=[]) {\n"
  3660. " if type(fn) != \"function\"\n"
  3661. " throw TypeError(\"expected first argument to be: function, but got: \" + "
  3662. "type(fn))\n"
  3663. " if type(args) !in (\"list\", \"tuple\")\n"
  3664. " throw TypeError(\"expected second argument to be: list or tuple, but got: \" + "
  3665. "type(args))\n"
  3666. " inline `qi_value_t *args = qi_get(state, \"args\")`\n"
  3667. " inline `qi_list_t *list`\n"
  3668. " inline `if (args->type == QI_TUPLE) {`\n"
  3669. " inline ` list = args->value.list;`\n"
  3670. " inline `} else {`\n"
  3671. " inline ` LOCKED(args, {list = qi_list_copy(args->value.list);})`\n"
  3672. " inline `}`\n"
  3673. " inline `void *td = qi_thread_create(state, qi_get(state, \"fn\"), "
  3674. "list)`\n"
  3675. " inline `qi_decl(state, \"td\", qi_make_data(state, 'T', td))`\n"
  3676. " return Object({\n"
  3677. " \"__str\": func (this): \"<Thread>\",\n"
  3678. " \"_td\": td,\n"
  3679. " \"joined\": false,\n"
  3680. " \"join\": func (this) {\n"
  3681. " if this.joined\n"
  3682. " return\n"
  3683. " var td = this._td\n"
  3684. " inline `qi_value_t *ret = qi_thread_join(state, qi_get_data(state, "
  3685. "'T', qi_get(state, \"td\")))`\n"
  3686. " this.joined = true\n"
  3687. " inline `return ret`\n"
  3688. " }\n"
  3689. " })\n"
  3690. "}\n"
  3691. "func Thread(fn, args=[]): Object({\n"
  3692. " \"__str\": func (this) use (fn, args): format(\"<Thread _ _>\", fn, "
  3693. "args),\n"
  3694. " \"_thread\": nil,\n"
  3695. " \"start\": func (this) use (fn, args) {\n"
  3696. " if this._thread !is nil\n"
  3697. " return\n"
  3698. " this._thread = thread_create(fn, args)\n"
  3699. " return this\n"
  3700. " },\n"
  3701. " \"join\": func (this) {\n"
  3702. " if this._thread !is nil\n"
  3703. " return this._thread.join()\n"
  3704. " },\n"
  3705. " \"is_joined\": func (this): this._thread.joined\n"
  3706. "})\n"
  3707. "func Mutex() {\n"
  3708. " inline `void *mutex = qi_mutex_create()`\n"
  3709. " inline `if (!mutex) qi_throw_format(state, \"mutex init failed\")`\n"
  3710. " inline `qi_decl(state, \"mutex\", qi_make_data(state, 'M', mutex))`\n"
  3711. " return Object({\n"
  3712. " \"__fin\": func (this) {\n"
  3713. " mutex = this._mutex\n"
  3714. " this._mutex = nil\n"
  3715. " inline `qi_mutex_destroy(qi_get_data(state, 'M', qi_get(state, "
  3716. "\"mutex\")))`\n"
  3717. " },\n"
  3718. " \"__str\": func (this): \"<Mutex>\",\n"
  3719. " \"_mutex\": mutex,\n"
  3720. " \"lock\": func (this) {\n"
  3721. " var mutex = this._mutex\n"
  3722. " inline `qi_mutex_lock(qi_get_data(state, 'M', qi_get(state, "
  3723. "\"mutex\")))`\n"
  3724. " },\n"
  3725. " \"trylock\": func (this) {\n"
  3726. " var mutex = this._mutex\n"
  3727. " inline `return qi_make_boolean(state, "
  3728. "qi_mutex_trylock(qi_get_data(state, 'M', qi_get(state, \"mutex\"))))`\n"
  3729. " },\n"
  3730. " \"unlock\": func (this) {\n"
  3731. " var mutex = this._mutex\n"
  3732. " inline `qi_mutex_unlock(qi_get_data(state, 'M', qi_get(state, "
  3733. "\"mutex\")))`\n"
  3734. " }\n"
  3735. " })\n"
  3736. "}\n"
  3737. "func Cond() {\n"
  3738. " inline `void *cond = qi_cond_create()`\n"
  3739. " inline `if (!cond) qi_throw_format(state, \"cond init failed\")`\n"
  3740. " inline `qi_decl(state, \"cond\", qi_make_data(state, 'C', cond))`\n"
  3741. " return Object({\n"
  3742. " \"__fin\": func (this) {\n"
  3743. " cond = this._cond\n"
  3744. " this._cond = nil\n"
  3745. " inline `qi_cond_destroy(qi_get_data(state, 'C', qi_get(state, "
  3746. "\"cond\")))`\n"
  3747. " },\n"
  3748. " \"__str\": func (this): \"<Cond>\",\n"
  3749. " \"_cond\": cond,\n"
  3750. " \"wait\": func (this, mutex) {\n"
  3751. " var cond = this._cond\n"
  3752. " mutex = mutex._mutex\n"
  3753. " inline `qi_cond_wait(qi_get_data(state, 'C', qi_get(state, "
  3754. "\"cond\")), qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  3755. " },\n"
  3756. " \"signal\": func (this) {\n"
  3757. " var cond = this._cond\n"
  3758. " inline `qi_cond_signal(qi_get_data(state, 'C', qi_get(state, "
  3759. "\"cond\")))`\n"
  3760. " },\n"
  3761. " \"broadcast\": func (this) {\n"
  3762. " var cond = this._cond\n"
  3763. " inline `qi_cond_broadcast(qi_get_data(state, 'C', qi_get(state, "
  3764. "\"cond\")))`\n"
  3765. " }\n"
  3766. " })\n"
  3767. "}\n"
  3768. "func thread_exit(ret=nil)\n"
  3769. " inline `qi_thread_exit(state, qi_get(state, \"ret\"))`\n"
  3770. "func is_main_thread()\n"
  3771. " inline `return qi_make_boolean(state, qi_thread_main())`\n"},
  3772. {"os",
  3773. "header `#ifdef _WIN32`\n"
  3774. "include `Windows.h`\n"
  3775. "header `#endif`\n"
  3776. "func system(s) {\n"
  3777. " if type(s) != \"string\"\n"
  3778. " throw TypeError(\"expected first argument to be: string, but got: \" + "
  3779. "type(s))\n"
  3780. " inline `return qi_make_number(state, system(qi_get(state, "
  3781. "\"s\")->value.string))`"
  3782. "}\n"
  3783. "func getenv(n) {\n"
  3784. " if type(n) != \"string\"\n"
  3785. " throw TypeError(\"expected first argument to be: string, but got: \" + "
  3786. "type(n))\n"
  3787. " inline `char *value = getenv(qi_get(state, \"n\")->value.string)`\n"
  3788. " inline `return value? qi_make_string_copy(state, value): state->nil`\n"
  3789. "}\n"
  3790. "func setenv(n, v) {\n"
  3791. " if type(n) != \"string\"\n"
  3792. " throw TypeError(\"expected first argument to be: string, but got: \" + "
  3793. "type(n))\n"
  3794. " v = str(v)\n"
  3795. " inline \"#ifdef _WIN32\"\n"
  3796. " var s = n + \"=\" + v\n"
  3797. " inline `_putenv(qi_get(state, \"s\")->value.string)`\n"
  3798. " inline \"#else\"\n"
  3799. " inline `setenv(qi_get(state, \"n\")->value.string, qi_get(state, "
  3800. "\"v\")->value.string, 1)`\n"
  3801. " inline \"#endif\"\n"
  3802. "}\n"
  3803. "func exit(c) {\n"
  3804. " if type(c) != \"number\"\n"
  3805. " throw TypeError(\"expected first argument to be: number, but got: \" + type(c))\n"
  3806. " inline `qi_exit(state, qi_get(state, \"c\")->value.number)`\n"
  3807. "}\n"
  3808. "func die(msg, c=1) {\n"
  3809. " fputs(STDERR, str(msg) + \"\\n\")\n"
  3810. " exit(c)\n"
  3811. "}\n"},
  3812. {"string", "let STR_LETTERS = "
  3813. "\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  3814. "let STR_ASCII_LC = \"abcdefghijklmnopqrstuvwxyz\"\n"
  3815. "let STR_ASCII_UC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  3816. "let STR_DIGITS = \"0123456789\"\n"
  3817. "let STR_WS = \" \\t\\n\\r\\x0b\\x0c\"\n"
  3818. "let STR_PUNCTS = \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"\n"
  3819. "func is_char(c): return type(c) == \"string\" && len(c) == 1\n"
  3820. "func isalpha(c): return (c >= 'a' && c <= 'z') || (c >= 'A' && "
  3821. "c <= 'Z')\n"
  3822. "func isdigit(c): return c >= '0' && c <= '9'\n"
  3823. "func ispunct(c): return c in STR_PUNCTS\n"
  3824. "func isws(c): return c in STR_WS\n"},
  3825. {"time",
  3826. "include `time.h`\n"
  3827. "include `errno.h`\n"
  3828. "header `#ifdef _WIN32`\n"
  3829. "include `Windows.h`\n"
  3830. "header `#endif`\n"
  3831. "func time() {\n"
  3832. " inline `unsigned long long ts = time(NULL)`\n"
  3833. " inline `return qi_make_number(state, ts)`\n"
  3834. "}\n"
  3835. "func strftime(f, t=time()) {\n"
  3836. " if type(f) != \"string\"\n"
  3837. " throw TypeError(\"expected first argument to be: string, but got: \" + "
  3838. "type(f))\n"
  3839. " if type(t) != \"number\"\n"
  3840. " throw TypeError(\"expected second argument to be: number, but got: \" + "
  3841. "type(t))\n"
  3842. " inline `time_t ts = qi_get(state, \"t\")->value.number`\n"
  3843. " inline `struct tm lt`\n"
  3844. " inline `lt = *localtime(&ts)`\n"
  3845. " inline `char buffer[512]`\n"
  3846. " inline `strftime(buffer, sizeof(buffer), qi_get(state, "
  3847. "\"f\")->value.string, &lt)`\n"
  3848. " inline `return qi_make_string_copy(state, buffer)`\n"
  3849. "}\n"
  3850. "func usleep(t) {\n"
  3851. " if type(t) != \"number\"\n"
  3852. " throw \"expected first argument to be: number, but got: \" + "
  3853. "type(t)\n"
  3854. " \n"
  3855. " inline `#ifdef _WIN32`\n"
  3856. " inline `Sleep((unsigned long)(qi_get(state, \"t\")->value.number))`\n"
  3857. " inline `#else`\n"
  3858. " inline `unsigned long ms = (unsigned long)(qi_get(state, "
  3859. "\"t\")->value.number)`\n"
  3860. " inline `struct timespec ts`\n"
  3861. " inline `ts.tv_sec = ms / 1000`\n"
  3862. " inline `ts.tv_nsec = (ms % 1000) * 1000000`\n"
  3863. " inline `struct timespec r`\n"
  3864. " inline `while (nanosleep(&ts, &r) < 0) if (errno == EINTR) ts = r; "
  3865. "else break`\n"
  3866. " inline `#endif`\n"
  3867. "}\n"
  3868. "func sleep(t)\n"
  3869. " usleep(t * 1000)\n"},
  3870. {"random",
  3871. "func rand() {\n"
  3872. " inline `return qi_make_number(state, rand())`\n"
  3873. "}\n"
  3874. "func randf() {\n"
  3875. " inline `return qi_make_number(state, (double)rand()/RAND_MAX)`\n"
  3876. "}\n"
  3877. "func random_int(min, max): return rand() % (max + 1 - min) + min\n"
  3878. "func random_choice(l, k=1) {\n"
  3879. " if k < 0 || k > len(l)\n"
  3880. " throw ValueError(\"sample larger than population or is negative\")\n"
  3881. " l = list_copy(list(l))\n"
  3882. " var r = []\n"
  3883. " for var i = 0; i < k; i++\n"
  3884. " list_push(r, list_pop_at(l, random_int(0, len(l)-1)))\n"
  3885. " return r\n"
  3886. "}\n"
  3887. "func random_pick(l, k=-1) {\n"
  3888. " if k < 0\n"
  3889. " return l[random_int(0, len(l)-1)]\n"
  3890. " var r = []\n"
  3891. " for var i = 0; i < k; i++\n"
  3892. " list_push(r, l[random_int(0, len(l)-1)])\n"
  3893. " return r\n"
  3894. "}\n"
  3895. "inline `srand(time(NULL))`\n"},
  3896. {"math", NULL},
  3897. {NULL, NULL}};
  3898. const struct
  3899. {
  3900. const char *name;
  3901. const char *fname;
  3902. int arity;
  3903. } MATHFUNCS[] = {{"ceil", NULL, 1}, {"floor", NULL, 1}, {"trunc", NULL, 1}, {"round", NULL, 1}, {"abs", "fabs", 1}, {"exp", NULL, 1}, {"sqrt", NULL, 1}, {"sinh", NULL, 1}, {"cosh", NULL, 1}, {"tanh", NULL, 1}, {"asinh", NULL, 1}, {"acosh", NULL, 1}, {"atanh", NULL, 1}, {"sin", NULL, 1}, {"cos", NULL, 1}, {"tan", NULL, 1}, {"asin", NULL, 1}, {"acos", NULL, 1}, {"atan", NULL, 1}, {"atan2", NULL, 2}, {"hypot", NULL, 2},
  3904. {NULL, 0}};
  3905. void genmathlib(void)
  3906. {
  3907. buffer_t *buffer = buffer_new();
  3908. buffer_appends(
  3909. buffer,
  3910. "let Math = {\"tau\": 6.283185307179586, \"pi\": 3.141592653589793, "
  3911. "\"e\": 2.718281828459045, \"inf\": INFINITY, \"nan\": NAN, ");
  3912. for (size_t i = 0; MATHFUNCS[i].name; i++)
  3913. {
  3914. if (MATHFUNCS[i].arity == 0)
  3915. buffer_fmt(
  3916. buffer,
  3917. "\"%s\": func () { inline `return qi_make_number(state, %s())` }",
  3918. MATHFUNCS[i].name,
  3919. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  3920. else if (MATHFUNCS[i].arity == 1)
  3921. buffer_fmt(
  3922. buffer,
  3923. "\"%s\": func (x) { if type(x) != \"number\" { throw TypeError(\"expected "
  3924. "first argument to be: number, but got: \" + type(x)) } inline "
  3925. "`double n = %s(qi_get(state, \"x\")->value.number)`; inline `return "
  3926. "qi_make_number(state, n)` }",
  3927. MATHFUNCS[i].name,
  3928. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  3929. else
  3930. buffer_fmt(
  3931. buffer,
  3932. "\"%s\": func (x, y) { if type(x) != \"number\" { throw TypeError(\"expected "
  3933. "first argument to be: number, but got: \" + type(x)) } if type(y) != "
  3934. "\"number\" { throw TypeError(\"expected second argument to be: number, but "
  3935. "got: \" + type(y)) } inline `double n = %s(qi_get(state, "
  3936. "\"x\")->value.number, qi_get(state, \"y\")->value.number)`; inline "
  3937. "`return qi_make_number(state, n)` }",
  3938. MATHFUNCS[i].name,
  3939. MATHFUNCS[i].fname ? MATHFUNCS[i].fname : MATHFUNCS[i].name);
  3940. if (MATHFUNCS[i + 1].name)
  3941. buffer_append(buffer, ',');
  3942. }
  3943. buffer_append(buffer, '}');
  3944. size_t i;
  3945. for (i = 0; strcmp(STD[i][0], "math") != 0; i++)
  3946. ;
  3947. STD[i][1] = buffer_read(buffer);
  3948. }
  3949. char *unescape(char *s)
  3950. {
  3951. buffer_t *buf = buffer_new();
  3952. for (size_t i = 0; i < strlen(s); i++)
  3953. {
  3954. char c = s[i];
  3955. if (c == '\\')
  3956. {
  3957. char nc = s[i + 1];
  3958. if (!nc)
  3959. continue;
  3960. switch (nc)
  3961. {
  3962. case 'n':
  3963. buffer_append(buf, '\n');
  3964. break;
  3965. case 't':
  3966. buffer_append(buf, '\t');
  3967. break;
  3968. case 'r':
  3969. buffer_append(buf, '\r');
  3970. break;
  3971. default:
  3972. buffer_append(buf, nc);
  3973. break;
  3974. }
  3975. i++;
  3976. }
  3977. else
  3978. buffer_append(buf, c);
  3979. }
  3980. return buffer_read(buf);
  3981. }
  3982. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  3983. table_t *ltab, list_t *lstk, list_t *sstk, list_t *lbl);
  3984. int require_once(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  3985. list_t *lstk, list_t *sstk, list_t *lbl, char *path)
  3986. {
  3987. char tmp[512];
  3988. char *source = NULL;
  3989. if (is_required(path))
  3990. return 1;
  3991. for (size_t i = 0; STD[i][0]; i++)
  3992. {
  3993. if (strcmp(path, STD[i][0]) == 0)
  3994. {
  3995. source = (char *)STD[i][1];
  3996. break;
  3997. }
  3998. }
  3999. if (!source)
  4000. {
  4001. FILE *fd;
  4002. if (is_directory(path))
  4003. {
  4004. snprintf(tmp, sizeof(tmp), "%s/main.qi", path);
  4005. fd = fopen(tmp, "rb");
  4006. if (fd)
  4007. {
  4008. path = strdup(tmp);
  4009. goto pass;
  4010. }
  4011. }
  4012. fd = fopen(path, "rb");
  4013. if (!fd)
  4014. {
  4015. char *qipath = getenv("QIPATH");
  4016. if (!qipath)
  4017. return -1;
  4018. char *n = strtok(qipath, ":");
  4019. while (n)
  4020. {
  4021. snprintf(tmp, sizeof(tmp), "%s/%s", n, path);
  4022. fd = fopen(tmp, "rb");
  4023. if (fd)
  4024. {
  4025. path = strdup(tmp);
  4026. break;
  4027. }
  4028. }
  4029. if (!fd)
  4030. return -1;
  4031. }
  4032. pass:
  4033. path = realpath(path, NULL);
  4034. if (is_required(path))
  4035. {
  4036. fclose(fd);
  4037. return 1;
  4038. }
  4039. buffer_t *fbuf = buffer_new();
  4040. for (;;)
  4041. {
  4042. char line[512];
  4043. if (!fgets(line, sizeof(line), fd))
  4044. break;
  4045. buffer_appends(fbuf, line);
  4046. }
  4047. source = buffer_read(fbuf);
  4048. }
  4049. list_t *pair = list_new();
  4050. list_push(pair, path);
  4051. list_push(pair, source);
  4052. list_push(FILES, pair);
  4053. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  4054. list_pop(FILES);
  4055. list_push(REQUIRED, path);
  4056. return 0;
  4057. }
  4058. buffer_t *HBUF;
  4059. list_t *MVARS;
  4060. node_t *YES;
  4061. #define IS_EXPR(n) \
  4062. ((n) && ((node_t *)(n))->tag > N_EXPRS_BEGIN && \
  4063. ((node_t *)(n))->tag < N_EXPRS_END)
  4064. #define IS_NUMBER(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_NUMBER)
  4065. #define TO_DOUBLE(n) (strtod((n)->t->text, NULL))
  4066. #define IS_STRING(n) ((n) && (n)->tag == N_LITERAL && (n)->t->tag == T_STRING)
  4067. node_t *make_number(double v)
  4068. {
  4069. char buf[64];
  4070. snprintf(buf, sizeof(buf), "%g", v);
  4071. return nodet(N_LITERAL, token(T_NUMBER, strdup(buf)));
  4072. }
  4073. node_t *mexpr_negate(node_t *a)
  4074. {
  4075. if (!IS_NUMBER(a))
  4076. return NULL;
  4077. return make_number(-TO_DOUBLE(a));
  4078. }
  4079. node_t *mexpr_add(node_t *a, node_t *b)
  4080. {
  4081. if (IS_STRING(a) && IS_STRING(b)) {
  4082. char *buf = malloc(strlen(a->t->text) + strlen(b->t->text) + 1);
  4083. strcpy(buf, a->t->text);
  4084. strcat(buf, b->t->text);
  4085. return nodet(N_LITERAL, token(T_STRING, buf));
  4086. }
  4087. if (!IS_NUMBER(a))
  4088. return NULL;
  4089. if (!IS_NUMBER(b))
  4090. return NULL;
  4091. return make_number(TO_DOUBLE(a) + TO_DOUBLE(b));
  4092. }
  4093. node_t *mexpr_sub(node_t *a, node_t *b)
  4094. {
  4095. if (!IS_NUMBER(a))
  4096. return NULL;
  4097. if (!IS_NUMBER(b))
  4098. return NULL;
  4099. return make_number(TO_DOUBLE(a) - TO_DOUBLE(b));
  4100. }
  4101. node_t *mexpr_mul(node_t *a, node_t *b)
  4102. {
  4103. if (!IS_NUMBER(a))
  4104. return NULL;
  4105. if (!IS_NUMBER(b))
  4106. return NULL;
  4107. return make_number(TO_DOUBLE(a) * TO_DOUBLE(b));
  4108. }
  4109. node_t *mexpr_pow(node_t *a, node_t *b)
  4110. {
  4111. if (!IS_NUMBER(a))
  4112. return NULL;
  4113. if (!IS_NUMBER(b))
  4114. return NULL;
  4115. return make_number(pow(TO_DOUBLE(a), TO_DOUBLE(b)));
  4116. }
  4117. node_t *mexpr_div(node_t *a, node_t *b)
  4118. {
  4119. if (!IS_NUMBER(a))
  4120. return NULL;
  4121. if (!IS_NUMBER(b))
  4122. return NULL;
  4123. double x = TO_DOUBLE(b);
  4124. if (x == 0)
  4125. return make_number(0);
  4126. return make_number(TO_DOUBLE(a) * x);
  4127. }
  4128. node_t *mexpr_mod(node_t *a, node_t *b)
  4129. {
  4130. if (!IS_NUMBER(a))
  4131. return NULL;
  4132. if (!IS_NUMBER(b))
  4133. return NULL;
  4134. double x = TO_DOUBLE(b);
  4135. if (x == 0)
  4136. return make_number(0);
  4137. return make_number(fmod(TO_DOUBLE(a), x));
  4138. }
  4139. int mexpr_equals(node_t *a, node_t *b)
  4140. {
  4141. if (!a && !b)
  4142. return 1;
  4143. if (!a && b)
  4144. return 0;
  4145. if (a && !b)
  4146. return 0;
  4147. if (a->tag != b->tag)
  4148. return 0;
  4149. switch (a->tag)
  4150. {
  4151. case N_LITERAL:
  4152. return a->t->tag == b->t->tag && strcmp(a->t->text, b->t->text) == 0;
  4153. default:
  4154. break;
  4155. }
  4156. return 0;
  4157. }
  4158. int mexpr_less(node_t *a, node_t *b)
  4159. {
  4160. if (!IS_NUMBER(a))
  4161. return 0;
  4162. if (!IS_NUMBER(b))
  4163. return 0;
  4164. return TO_DOUBLE(a) < TO_DOUBLE(b);
  4165. }
  4166. int mexpr_greater(node_t *a, node_t *b)
  4167. {
  4168. if (!IS_NUMBER(a))
  4169. return 0;
  4170. if (!IS_NUMBER(b))
  4171. return 0;
  4172. return TO_DOUBLE(a) > TO_DOUBLE(b);
  4173. }
  4174. macro_t *find_macro(char *name, size_t argc, int *res);
  4175. node_t *run_macro(macro_t *macro, list_t *args);
  4176. node_t *expand_mvars(node_t *node, node_t *_node, int expr);
  4177. int mdepth = 0;
  4178. size_t macro_rlimit = 100;
  4179. node_t *mexpr_eval(node_t *node)
  4180. {
  4181. if (mdepth >= macro_rlimit) {
  4182. COMPILE_ERROR("max. recursion depth (%d) reached while evaluating constant expression", macro_rlimit);
  4183. }
  4184. mdepth++;
  4185. if (node)
  4186. switch (node->tag)
  4187. {
  4188. case N_LITERAL:
  4189. if (node->t->tag == T_NAME)
  4190. {
  4191. node_t *v = const_get(node->t->text);
  4192. if (v)
  4193. node = mexpr_eval(v);
  4194. }
  4195. break;
  4196. case N_UNARY_PLUS:
  4197. node = mexpr_eval(node->a);
  4198. break;
  4199. case N_NEGATE:
  4200. {
  4201. node_t *a = mexpr_eval(node->a);
  4202. node = mexpr_negate(a);
  4203. } break;
  4204. case N_EQUALS:
  4205. {
  4206. node_t *a = mexpr_eval(node->a);
  4207. node_t *b = mexpr_eval(node->b);
  4208. node = mexpr_equals(a, b)? nodet(N_LITERAL, token(T_TRUE, "true")): nodet(N_LITERAL, token(T_FALSE, "false"));
  4209. } break;
  4210. case N_NOTEQUALS:
  4211. {
  4212. node_t *a = mexpr_eval(node->a);
  4213. node_t *b = mexpr_eval(node->b);
  4214. node = !mexpr_equals(a, b)? nodet(N_LITERAL, token(T_TRUE, "true")): nodet(N_LITERAL, token(T_FALSE, "false"));
  4215. } break;
  4216. case N_ADD:
  4217. {
  4218. node_t *a = mexpr_eval(node->a);
  4219. node_t *b = mexpr_eval(node->b);
  4220. if (IS_STRING(a) && IS_STRING(b)) {
  4221. node = mexpr_add(a, b);
  4222. break;
  4223. }
  4224. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4225. node = node2(N_ADD, node->a, b);
  4226. break;
  4227. }
  4228. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4229. node = node2(N_ADD, a, node->b);
  4230. break;
  4231. }
  4232. node = mexpr_add(a, b);
  4233. } break;
  4234. case N_SUB:
  4235. {
  4236. node_t *a = mexpr_eval(node->a);
  4237. node_t *b = mexpr_eval(node->b);
  4238. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4239. node = node2(N_SUB, node->a, b);
  4240. break;
  4241. }
  4242. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4243. node = node2(N_SUB, a, node->b);
  4244. break;
  4245. }
  4246. node = mexpr_sub(a, b);
  4247. } break;
  4248. case N_MUL:
  4249. {
  4250. node_t *a = mexpr_eval(node->a);
  4251. node_t *b = mexpr_eval(node->b);
  4252. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4253. node = node2(N_MUL, node->a, b);
  4254. break;
  4255. }
  4256. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4257. node = node2(N_MUL, a, node->b);
  4258. break;
  4259. }
  4260. node = mexpr_mul(a, b);
  4261. } break;
  4262. case N_POW:
  4263. {
  4264. node_t *a = mexpr_eval(node->a);
  4265. node_t *b = mexpr_eval(node->b);
  4266. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4267. node = node2(N_POW, node->a, b);
  4268. break;
  4269. }
  4270. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4271. node = node2(N_POW, a, node->b);
  4272. break;
  4273. }
  4274. node = mexpr_pow(a, b);
  4275. } break;
  4276. case N_DIV:
  4277. {
  4278. node_t *a = mexpr_eval(node->a);
  4279. node_t *b = mexpr_eval(node->b);
  4280. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4281. node = node2(N_DIV, node->a, b);
  4282. break;
  4283. }
  4284. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4285. node = node2(N_DIV, a, node->b);
  4286. break;
  4287. }
  4288. node = mexpr_div(a, b);
  4289. } break;
  4290. case N_MOD:
  4291. {
  4292. node_t *a = mexpr_eval(node->a);
  4293. node_t *b = mexpr_eval(node->b);
  4294. if (!IS_NUMBER(a) && IS_NUMBER(b)) {
  4295. node = node2(N_MOD, node->a, b);
  4296. break;
  4297. }
  4298. if (IS_NUMBER(a) && !IS_NUMBER(b)) {
  4299. node = node2(N_MOD, a, node->b);
  4300. break;
  4301. }
  4302. node = mexpr_mod(a, b);
  4303. } break;
  4304. case N_IFEXPR:
  4305. {
  4306. node_t *a = mexpr_eval(node->a);
  4307. if (a)
  4308. node = mexpr_eval(node->b);
  4309. else
  4310. node = mexpr_eval(node->c);
  4311. } break;
  4312. case N_TUPLE:
  4313. case N_LIST:
  4314. {
  4315. int f = 0;
  4316. list_t *l = list_new();
  4317. for (size_t i = 0; i < node->l->length; i++)
  4318. {
  4319. node_t *a = mexpr_eval(node->l->data[i]);
  4320. if (!IS_EXPR(a)) {
  4321. f = 1; break;
  4322. }
  4323. list_push(l, a);
  4324. }
  4325. if (f) break;
  4326. node = nodel(node->tag, l);
  4327. } break;
  4328. case N_COMMA:
  4329. node = mexpr_eval(list_index(node->l, -1));
  4330. break;
  4331. case N_MACRO_CALL:
  4332. {
  4333. list_t *args = list_new();
  4334. for (size_t i = 0; i < node->l->length; i++)
  4335. list_push(args, mexpr_eval(node->l->data[i]));
  4336. macro_t *m = find_macro(node->t->text, args->length, NULL);
  4337. if (m) {
  4338. list_push(MVARS, table_new());
  4339. node_t *r = run_macro(m, args);
  4340. list_pop(MVARS);
  4341. node = mexpr_eval(expand_mvars(node, r, 1));
  4342. }
  4343. } break;
  4344. default:
  4345. break;
  4346. }
  4347. mdepth--;
  4348. return node;
  4349. }
  4350. node_t *mf_isExpr(list_t *t)
  4351. {
  4352. if (t->length != 1)
  4353. return NULL;
  4354. return IS_EXPR(t->data[0]) ? YES : NULL;
  4355. }
  4356. node_t *mf_isList(list_t *t)
  4357. {
  4358. if (t->length != 1)
  4359. return NULL;
  4360. node_t *a = t->data[0];
  4361. if (!a)
  4362. return NULL;
  4363. return a->tag == N_LIST ? YES : NULL;
  4364. }
  4365. node_t *mf_newList(list_t *t)
  4366. {
  4367. for (size_t i = 0; i < t->length; i++)
  4368. if (!IS_EXPR(t->data[i]))
  4369. return NULL;
  4370. return nodel(N_LIST, t);
  4371. }
  4372. node_t *mf_newBlock(list_t *t)
  4373. {
  4374. for (size_t i = 0; i < t->length; i++)
  4375. if (!t->data[i])
  4376. return NULL;
  4377. else if (IS_EXPR(t->data[i]))
  4378. t->data[i] = node1(N_EXPRSTMT, t->data[i]);
  4379. return nodel(N_PROGRAM, t);
  4380. }
  4381. node_t *mf_newName(list_t *t)
  4382. {
  4383. if (t->length != 1)
  4384. return NULL;
  4385. node_t *a = t->data[0];
  4386. if (!IS_STRING(a))
  4387. return NULL;
  4388. char *text = a->t->text;
  4389. if (*text != '_' && !isalpha(*text))
  4390. return NULL;
  4391. for (size_t i = 0; i < strlen(text); i++)
  4392. if (text[i] != '_' && !isdigit(text[i]) && !isalpha(text[i]))
  4393. return NULL;
  4394. return nodet(N_LITERAL, token(T_NAME, text));
  4395. }
  4396. node_t *mf_newVar(list_t *t)
  4397. {
  4398. if (t->length != 1 && t->length != 2)
  4399. return NULL;
  4400. node_t *a = t->data[0];
  4401. if (!a || a->tag != N_LITERAL || a->t->tag != T_NAME)
  4402. return NULL;
  4403. node_t *b = NULL;
  4404. if (t->length == 2)
  4405. {
  4406. b = t->data[1];
  4407. if (!IS_EXPR(b))
  4408. return NULL;
  4409. }
  4410. table_t *h = table_new();
  4411. table_set(h, a->t->text, b);
  4412. return nodeh(N_VAR, h);
  4413. }
  4414. node_t *mf_len(list_t *t)
  4415. {
  4416. if (t->length != 1)
  4417. return NULL;
  4418. node_t *a = t->data[0];
  4419. if (!a)
  4420. return NULL;
  4421. if (a->tag == N_LIST || a->tag == N_TUPLE)
  4422. return make_number(a->l->length);
  4423. return NULL;
  4424. }
  4425. node_t *mf_nth(list_t *t)
  4426. {
  4427. if (t->length != 2)
  4428. return NULL;
  4429. node_t *a = t->data[0];
  4430. if (!a)
  4431. return NULL;
  4432. node_t *b = t->data[1];
  4433. if (!IS_NUMBER(b))
  4434. return NULL;
  4435. if (a->tag == N_LIST || a->tag == N_TUPLE)
  4436. return list_index(a->l, TO_DOUBLE(b));
  4437. return NULL;
  4438. }
  4439. node_t *mf_E(list_t *t)
  4440. {
  4441. if (t->length != 1)
  4442. return NULL;
  4443. node_t *a = t->data[0];
  4444. return mexpr_eval(a);
  4445. }
  4446. node_t *mf_C(list_t *t)
  4447. {
  4448. if (t->length != 1)
  4449. return NULL;
  4450. node_t *a = t->data[0];
  4451. if (!IS_STRING(a))
  4452. return NULL;
  4453. return const_get(a->t->text);
  4454. }
  4455. struct
  4456. {
  4457. char *name;
  4458. node_t *(*handler)(list_t *);
  4459. } METAFUNCS[] = {{"isExpr", mf_isExpr},
  4460. {"isList", mf_isList},
  4461. {"newName", mf_newName},
  4462. {"newList", mf_newList},
  4463. {"newBlock", mf_newBlock},
  4464. {"newVar", mf_newVar},
  4465. {"len", mf_len},
  4466. {"nth", mf_nth},
  4467. {"E", mf_E},
  4468. {"C", mf_C},
  4469. {NULL, NULL}};
  4470. macro_t *find_macro(char *name, size_t argc, int *res)
  4471. {
  4472. list_t *ms = macros_get(name);
  4473. if (!ms)
  4474. {
  4475. if (res)
  4476. *res = 1;
  4477. return NULL;
  4478. }
  4479. macro_t *m = NULL;
  4480. for (size_t i = 0; i < ms->length; i++)
  4481. {
  4482. macro_t *t = ms->data[i];
  4483. if (t->variable || t->params->length == argc)
  4484. {
  4485. m = t;
  4486. break;
  4487. }
  4488. }
  4489. if (!m)
  4490. {
  4491. if (res)
  4492. *res = 2;
  4493. return NULL;
  4494. }
  4495. if (res)
  4496. *res = 0;
  4497. return m;
  4498. }
  4499. typedef struct
  4500. {
  4501. node_t *mvar;
  4502. int code;
  4503. } mvar_expand_err_t;
  4504. node_t *_expand_mvars(node_t *node, int expr, mvar_expand_err_t *err);
  4505. node_t *run_macro(macro_t *macro, list_t *args);
  4506. node_t *run_mexpr(node_t *node)
  4507. {
  4508. switch (node->tag)
  4509. {
  4510. case N_LITERAL:
  4511. switch (node->t->tag)
  4512. {
  4513. case T_NIL:
  4514. return NULL;
  4515. case T_NAME:
  4516. return table_get(list_index(MVARS, -1), node->t->text);
  4517. case T_NUMBER:
  4518. case T_STRING:
  4519. return node;
  4520. default:
  4521. COMPILE_ERROR("not yet implemented");
  4522. }
  4523. break;
  4524. case N_MSTMT:
  4525. {
  4526. mvar_expand_err_t err = {NULL, 0};
  4527. node_t *n = _expand_mvars(node->a, 1, &err);
  4528. if (!n || err.code != 0)
  4529. return NULL;
  4530. return n;
  4531. }
  4532. break;
  4533. case N_CALL:
  4534. case N_MACRO_CALL:
  4535. {
  4536. list_t *args = list_new();
  4537. for (size_t i = 0; i < node->l->length; i++)
  4538. list_push(args, run_mexpr(node->l->data[i]));
  4539. if (node->tag == N_MACRO_CALL)
  4540. {
  4541. macro_t *m = find_macro(node->t->text, args->length, NULL);
  4542. if (!m)
  4543. return NULL;
  4544. list_push(MVARS, table_new());
  4545. node_t *r = run_macro(m, args);
  4546. list_pop(MVARS);
  4547. return r;
  4548. }
  4549. for (size_t i = 0; METAFUNCS[i].name; i++)
  4550. if (strcmp(METAFUNCS[i].name, node->t->text) == 0)
  4551. return METAFUNCS[i].handler(args);
  4552. }
  4553. break;
  4554. case N_LOGOR:
  4555. if (run_mexpr(node->a) || run_mexpr(node->b))
  4556. return YES;
  4557. case N_LOGAND:
  4558. if (run_mexpr(node->a) && run_mexpr(node->b))
  4559. return YES;
  4560. case N_NEGATE:
  4561. {
  4562. node_t *a = run_mexpr(node->a);
  4563. return mexpr_negate(a);
  4564. }
  4565. case N_ADD:
  4566. {
  4567. node_t *a = run_mexpr(node->a);
  4568. node_t *b = run_mexpr(node->b);
  4569. return mexpr_add(a, b);
  4570. }
  4571. case N_SUB:
  4572. {
  4573. node_t *a = run_mexpr(node->a);
  4574. node_t *b = run_mexpr(node->b);
  4575. return mexpr_sub(a, b);
  4576. }
  4577. case N_MUL:
  4578. {
  4579. node_t *a = run_mexpr(node->a);
  4580. node_t *b = run_mexpr(node->b);
  4581. return mexpr_mul(a, b);
  4582. }
  4583. case N_POW:
  4584. {
  4585. node_t *a = run_mexpr(node->a);
  4586. node_t *b = run_mexpr(node->b);
  4587. return mexpr_pow(a, b);
  4588. }
  4589. case N_DIV:
  4590. {
  4591. node_t *a = run_mexpr(node->a);
  4592. node_t *b = run_mexpr(node->b);
  4593. return mexpr_div(a, b);
  4594. }
  4595. case N_MOD:
  4596. {
  4597. node_t *a = run_mexpr(node->a);
  4598. node_t *b = run_mexpr(node->b);
  4599. return mexpr_mod(a, b);
  4600. }
  4601. case N_EQUALS:
  4602. {
  4603. node_t *a = run_mexpr(node->a);
  4604. node_t *b = run_mexpr(node->b);
  4605. return mexpr_equals(a, b) ? YES : NULL;
  4606. }
  4607. case N_NOTEQUALS:
  4608. {
  4609. node_t *a = run_mexpr(node->a);
  4610. node_t *b = run_mexpr(node->b);
  4611. return !mexpr_equals(a, b) ? YES : NULL;
  4612. }
  4613. case N_LT:
  4614. {
  4615. node_t *a = run_mexpr(node->a);
  4616. node_t *b = run_mexpr(node->b);
  4617. return mexpr_less(a, b) ? YES : NULL;
  4618. }
  4619. case N_GT:
  4620. {
  4621. node_t *a = run_mexpr(node->a);
  4622. node_t *b = run_mexpr(node->b);
  4623. return mexpr_greater(a, b) ? YES : NULL;
  4624. }
  4625. default:
  4626. COMPILE_ERROR("not yet implemented");
  4627. }
  4628. return NULL;
  4629. }
  4630. node_t *run_mnode(node_t *node);
  4631. node_t *run_mnodes(list_t *l)
  4632. {
  4633. node_t *r = NULL;
  4634. for (size_t i = 0; i < l->length; i++)
  4635. if ((r = run_mnode(l->data[i])))
  4636. break;
  4637. return r;
  4638. }
  4639. node_t *run_mnode(node_t *node)
  4640. {
  4641. node_t *r = NULL;
  4642. switch (node->tag)
  4643. {
  4644. case N_MIF:
  4645. if (run_mexpr(node->a))
  4646. r = run_mnodes(node->l);
  4647. else if (node->l2)
  4648. r = run_mnodes(node->l2);
  4649. break;
  4650. case N_MFOR:
  4651. while (run_mexpr(node->a))
  4652. if ((r = run_mnodes(node->l)))
  4653. break;
  4654. break;
  4655. case N_MREPEAT:
  4656. {
  4657. list_t *l = list_new();
  4658. while (run_mexpr(node->a))
  4659. {
  4660. node_t *n = run_mnodes(node->l);
  4661. if (!n)
  4662. return NULL;
  4663. if (IS_EXPR(n))
  4664. n = node1(N_EXPRSTMT, n);
  4665. list_push(l, n);
  4666. }
  4667. r = nodel(N_PROGRAM, l);
  4668. }
  4669. break;
  4670. case N_MSET:
  4671. table_set(list_index(MVARS, -1), node->t->text, run_mexpr(node->a));
  4672. break;
  4673. case N_MPUSH:
  4674. {
  4675. node_t *l = table_get(list_index(MVARS, -1), node->t->text);
  4676. if (l && (l->tag == N_LIST || l->tag == N_PROGRAM))
  4677. {
  4678. node_t *n = run_mexpr(node->a);
  4679. if (!n)
  4680. break;
  4681. if (IS_EXPR(n))
  4682. {
  4683. if (l->tag == N_PROGRAM)
  4684. n = node1(N_EXPRSTMT, n);
  4685. else
  4686. break;
  4687. }
  4688. list_push(l->l, n);
  4689. }
  4690. }
  4691. break;
  4692. case N_MSTMT:
  4693. r = node->a;
  4694. break;
  4695. case N_MEXPR:
  4696. r = run_mexpr(node->a);
  4697. break;
  4698. default:
  4699. r = node;
  4700. }
  4701. return r;
  4702. }
  4703. list_t *macro_stk;
  4704. size_t expand_depth = 0;
  4705. node_t *run_macro(macro_t *macro, list_t *args)
  4706. {
  4707. if (macro_stk->length >= macro_rlimit)
  4708. return NULL;
  4709. list_push(macro_stk, macro);
  4710. table_t *mvars = list_index(MVARS, -1);
  4711. table_set(mvars, "nil", NULL);
  4712. table_set(mvars, "*", nodel(N_LIST, args));
  4713. if (!macro->variable)
  4714. for (size_t i = 0; i < args->length; i++)
  4715. table_set(mvars, ((token_t *)macro->params->data[i])->text,
  4716. args->data[i]);
  4717. node_t *r = NULL;
  4718. for (size_t i = 0; i < macro->body->length; i++)
  4719. {
  4720. r = run_mnode(macro->body->data[i]);
  4721. if (r)
  4722. break;
  4723. }
  4724. list_pop(macro_stk);
  4725. return r;
  4726. }
  4727. node_t *_expand_mvars(node_t *node, int expr, mvar_expand_err_t *err)
  4728. {
  4729. if (node->tag == N_LITERAL)
  4730. return node;
  4731. if (node->tag == N_MVAR)
  4732. {
  4733. char *name = node->t->text;
  4734. err->mvar = node;
  4735. table_t *mvars = list_index(MVARS, -1);
  4736. if (!table_has(mvars, name))
  4737. {
  4738. err->code = 1;
  4739. return NULL;
  4740. }
  4741. node_t *n = table_get(mvars, name);
  4742. if (n)
  4743. {
  4744. if (expr && !IS_EXPR(n))
  4745. {
  4746. err->code = 2;
  4747. return NULL;
  4748. }
  4749. if (!expr && IS_EXPR(n))
  4750. n = node1(N_EXPRSTMT, n);
  4751. }
  4752. else
  4753. {
  4754. err->code = 3;
  4755. return NULL;
  4756. }
  4757. return n;
  4758. }
  4759. if (node->tag == N_EXPRSTMT)
  4760. {
  4761. node_t *n = _expand_mvars(node->a, 0, err);
  4762. if (err->code != 0)
  4763. return NULL;
  4764. if (!IS_EXPR(n))
  4765. return n;
  4766. node = node_copy(node);
  4767. node->a = n;
  4768. return node;
  4769. }
  4770. else if ((node->tag >= N_ADD && node->tag <= N_BAND) ||
  4771. (node->tag >= N_ASSIGN && node->tag <= N_ASSIGN_SHR) ||
  4772. node->tag == N_DECL)
  4773. {
  4774. node = node_copy(node);
  4775. node->a = _expand_mvars(node->a, 1, err);
  4776. if (err->code != 0)
  4777. return NULL;
  4778. node->b = _expand_mvars(node->b, 1, err);
  4779. if (err->code != 0)
  4780. return NULL;
  4781. return node;
  4782. }
  4783. else if (node->tag == N_PROGRAM || node->tag == N_BLOCK ||
  4784. node->tag == N_LIST || node->tag == N_TUPLE ||
  4785. node->tag == N_COMMA)
  4786. {
  4787. node = node_copy(node);
  4788. node->l = list_copy(node->l);
  4789. for (size_t i = 0; i < node->l->length; i++)
  4790. {
  4791. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  4792. if (err->code != 0)
  4793. return NULL;
  4794. node->l->data[i] = n;
  4795. }
  4796. return node;
  4797. }
  4798. else if (node->tag == N_IF || node->tag == N_IFEXPR)
  4799. {
  4800. node = node_copy(node);
  4801. node->a = _expand_mvars(node->a, 1, err);
  4802. if (err->code != 0)
  4803. return NULL;
  4804. node->b = _expand_mvars(node->b, 1, err);
  4805. if (err->code != 0)
  4806. return NULL;
  4807. if (node->c)
  4808. {
  4809. node->c = _expand_mvars(node->c, 1, err);
  4810. if (err->code != 0)
  4811. return NULL;
  4812. }
  4813. return node;
  4814. }
  4815. else if (node->tag == N_RETURN)
  4816. {
  4817. node = node_copy(node);
  4818. if (node->a)
  4819. {
  4820. node->a = _expand_mvars(node->a, 1, err);
  4821. if (err->code != 0)
  4822. return NULL;
  4823. }
  4824. return node;
  4825. }
  4826. else if (node->tag == N_CALL)
  4827. {
  4828. node = node_copy(node);
  4829. node->a = _expand_mvars(node->a, 1, err);
  4830. if (err->code != 0)
  4831. return NULL;
  4832. node->l = list_copy(node->l);
  4833. for (size_t i = 0; i < node->l->length; i++)
  4834. {
  4835. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  4836. if (err->code != 0)
  4837. return NULL;
  4838. node->l->data[i] = n;
  4839. }
  4840. return node;
  4841. }
  4842. else if (node->tag == N_MACRO_CALL)
  4843. {
  4844. node = node_copy(node);
  4845. node->l = list_copy(node->l);
  4846. for (size_t i = 0; i < node->l->length; i++)
  4847. {
  4848. node_t *n = _expand_mvars(node->l->data[i], 1, err);
  4849. if (err->code != 0)
  4850. return NULL;
  4851. node->l->data[i] = n;
  4852. }
  4853. return node;
  4854. }
  4855. else if (node->tag == N_INC || node->tag == N_DEC || node->tag == N_PINC ||
  4856. node->tag == N_PDEC)
  4857. {
  4858. node = node_copy(node);
  4859. node->a = _expand_mvars(node->a, 1, err);
  4860. if (err->code != 0)
  4861. return NULL;
  4862. return node;
  4863. }
  4864. else if (node->tag == N_TRY)
  4865. {
  4866. node = node_copy(node);
  4867. node->a = _expand_mvars(node->a, node->a->tag != N_PROGRAM, err);
  4868. if (err->code != 0)
  4869. return NULL;
  4870. return node;
  4871. }
  4872. err->code = 4;
  4873. return NULL;
  4874. }
  4875. node_t *expand_mvars(node_t *node, node_t *_node, int expr)
  4876. {
  4877. mvar_expand_err_t err = {NULL, 0};
  4878. node_t *r = _expand_mvars(_node, expr, &err);
  4879. if ((!r || err.code != 0) && err.mvar)
  4880. {
  4881. COMPILE_NOTE("macro expansion failed");
  4882. node = err.mvar;
  4883. }
  4884. if (err.code == 1)
  4885. {
  4886. COMPILE_ERROR("undefined macro variable: '%s'", err.mvar->t->text);
  4887. }
  4888. else if (err.code == 2)
  4889. {
  4890. COMPILE_ERROR(
  4891. "macro variable '%s' expanded to non-expression in expression context",
  4892. err.mvar->t->text);
  4893. }
  4894. else if (err.code == 3)
  4895. {
  4896. COMPILE_ERROR("macro variable '%s' expanded to nil", err.mvar->t->text);
  4897. }
  4898. else if (err.code == 4)
  4899. {
  4900. COMPILE_ERROR("macro variable expansion failed because it is not yet "
  4901. "implemented for this context");
  4902. }
  4903. if (!r)
  4904. COMPILE_ERROR("macro variable expansion failed");
  4905. return r;
  4906. }
  4907. void compile_macro_call(buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  4908. table_t *ltab, list_t *lstk, list_t *sstk, list_t *lbl,
  4909. node_t *node, int expr)
  4910. {
  4911. size_t argc = node->l->length;
  4912. char *name = node->t->text;
  4913. int res = 0;
  4914. macro_t *m = find_macro(name, argc, &res);
  4915. if (!m)
  4916. {
  4917. if (res == 1)
  4918. {
  4919. COMPILE_ERROR("undefined macro: '%s'", name);
  4920. }
  4921. else
  4922. {
  4923. COMPILE_ERROR("no %d-param candidate found for macro: '%s'", argc, name);
  4924. }
  4925. }
  4926. list_push(MVARS, table_new());
  4927. if (macro_stk->length >= macro_rlimit)
  4928. COMPILE_ERROR("recursion depth limit exceeded while expanding macro: '%s'",
  4929. name);
  4930. node_t *r = run_macro(m, node->l);
  4931. if (r)
  4932. {
  4933. r = expand_mvars(node, r, expr);
  4934. if (expr && r->tag == N_EXPRSTMT)
  4935. r = r->a;
  4936. if (r->tag == N_MACRO_CALL)
  4937. {
  4938. list_pop(MVARS);
  4939. if (expand_depth >= macro_rlimit)
  4940. COMPILE_ERROR(
  4941. "recursion depth limit exceeded while expanding macro: '%s'", name);
  4942. expand_depth++;
  4943. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, r, expr);
  4944. expand_depth--;
  4945. return;
  4946. }
  4947. if (expr && !IS_EXPR(r))
  4948. COMPILE_ERROR(
  4949. "macro '%s' expanded to non-expression in expression context", name);
  4950. if (!expr && IS_EXPR(r))
  4951. r = node1(N_EXPRSTMT, r);
  4952. list_push(MACROCALLS, node);
  4953. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, r);
  4954. list_pop(MACROCALLS);
  4955. }
  4956. else
  4957. COMPILE_ERROR("macro '%s' expanded to nil", name);
  4958. list_pop(MVARS);
  4959. }
  4960. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab,
  4961. list_t *lstk, list_t *sstk, list_t *lbl, node_t *node)
  4962. {
  4963. switch (node->tag)
  4964. {
  4965. case N_TOPLEVEL:
  4966. case N_PROGRAM:
  4967. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  4968. break;
  4969. case N_EXPRSTMT:
  4970. if (node->a->tag == N_LITERAL && node->a->t->tag != T_NAME)
  4971. break;
  4972. else if (node->a->tag == N_MACRO_CALL)
  4973. {
  4974. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a, 0);
  4975. break;
  4976. }
  4977. EMIT("(void)(");
  4978. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  4979. EMIT(");");
  4980. break;
  4981. case N_BLOCK:
  4982. LBPUSH();
  4983. CTXPUSH("scope");
  4984. list_push(CONSTANTS, table_new());
  4985. list_push(MACROS, table_new());
  4986. EMIT("qi_new_sticky_scope(state);\n");
  4987. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  4988. EMIT("qi_old_scope(state);");
  4989. list_pop(MACROS);
  4990. list_pop(CONSTANTS);
  4991. CTXPOP();
  4992. LBPOP();
  4993. break;
  4994. case N_LITERAL:
  4995. switch (node->t->tag)
  4996. {
  4997. case T_NUMBER:
  4998. {
  4999. char *number = node->t->text;
  5000. if (strncmp(number, "0o", 2) == 0 || strncmp(number, "0b", 2) == 0)
  5001. {
  5002. buffer_t *buf = buffer_new();
  5003. if (number[1] == 'o')
  5004. buffer_fmt(buf, "0%s", number + 2);
  5005. else
  5006. buffer_fmt(buf, "%d", strtol(number + 2, NULL, 2));
  5007. number = buffer_read(buf);
  5008. }
  5009. else if (number[0] == '0' && number[1] && isdigit(number[1]))
  5010. {
  5011. size_t i;
  5012. for (i = 0; i < strlen(number); i++)
  5013. if (number[i] != '0' || number[i + 1] == '.')
  5014. break;
  5015. number += i;
  5016. }
  5017. EMIT("qi_make_number(state, %s)", number);
  5018. }
  5019. break;
  5020. case T_STRING:
  5021. if (!*(node->t->text))
  5022. {
  5023. EMIT("state->empty_string");
  5024. }
  5025. else
  5026. {
  5027. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  5028. }
  5029. break;
  5030. case T_FSTRING:
  5031. {
  5032. char *text = node->t->text;
  5033. if (!*text)
  5034. {
  5035. EMIT("state->empty_string");
  5036. break;
  5037. }
  5038. list_t *parts = list_new();
  5039. buffer_t *tbuf = buffer_new();
  5040. for (size_t i = 0; i < strlen(text); i++)
  5041. {
  5042. char c = text[i];
  5043. if (c == '$' && text[i + 1] == '$')
  5044. {
  5045. buffer_append(tbuf, '$');
  5046. i++;
  5047. continue;
  5048. }
  5049. else if (c == '$' && text[i + 1] == '{')
  5050. {
  5051. i += 2;
  5052. buffer_t *tbuf2 = buffer_new();
  5053. while (text[i] && text[i] != '}')
  5054. buffer_append(tbuf2, text[i++]);
  5055. if (text[i] != '}')
  5056. {
  5057. i--;
  5058. buffer_appends(tbuf, "${");
  5059. buffer_appendb(tbuf, tbuf2);
  5060. continue;
  5061. }
  5062. if (tbuf->size > 0)
  5063. list_push(parts, nodeb(tbuf));
  5064. tbuf = buffer_new();
  5065. char *source = unescape(buffer_read(tbuf2));
  5066. list_t *pair = list_new();
  5067. buffer_t *fname = buffer_new();
  5068. size_t line, col;
  5069. (void)traverse(GETSRC(node->fi), node->pos, &line, &col);
  5070. buffer_fmt(fname, "<fstring at %s:%zu:%zu>", GETFNAME(node->fi), line,
  5071. col);
  5072. list_push(pair, buffer_read(fname));
  5073. list_push(pair, source);
  5074. list_push(FILES, pair);
  5075. list_t *tokens = tokenize(source);
  5076. size_t pos = 0;
  5077. node_t *n = parse_expr(tokens, &pos);
  5078. if (pos != tokens->length - 1)
  5079. COMPILE_ERROR("unconsumed input in f-expr");
  5080. list_push(parts, n);
  5081. }
  5082. else
  5083. buffer_append(tbuf, c);
  5084. }
  5085. if (tbuf->size > 0)
  5086. list_push(parts, nodeb(tbuf));
  5087. tbuf = buffer_new();
  5088. NEWGID();
  5089. buffer_fmt(tbuf,
  5090. "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  5091. PREFIX, gid);
  5092. buffer_fmt(tbuf, "qi_value_t *str = state->empty_string;\n");
  5093. for (size_t i = 0; i < parts->length; i++)
  5094. {
  5095. node_t *part = parts->data[i];
  5096. buffer_fmt(tbuf, "str = qi_add(state, str, ");
  5097. if (part->tag == N_BUFFER)
  5098. buffer_fmt(tbuf, "qi_make_string(state, \"%s\")",
  5099. buffer_read(part->buf));
  5100. else
  5101. {
  5102. buffer_fmt(tbuf, "qi_to_string(state, ");
  5103. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, part);
  5104. buffer_fmt(tbuf, ")");
  5105. }
  5106. buffer_fmt(tbuf, ");\n");
  5107. }
  5108. buffer_fmt(tbuf, "return str;\n}\n");
  5109. buffer_appendb(gbuf, tbuf);
  5110. EMIT("__%s%d(state)", PREFIX, gid);
  5111. }
  5112. break;
  5113. case T_USTRING:
  5114. EMIT("qi_call(state, qi_get(state, \"ustr\"), "
  5115. "qi_list_push(qi_list_make(), qi_make_string(state, \"%s\")))",
  5116. node->t->text);
  5117. break;
  5118. case T_BSTRING:
  5119. EMIT("qi_make_bytes(state, (unsigned char *)\"%s\", %d)", node->t->text,
  5120. node->t->z);
  5121. break;
  5122. case T_NAME:
  5123. {
  5124. char *name = node->t->text;
  5125. node_t *n = const_get(name);
  5126. if (n)
  5127. {
  5128. node_t *r = mexpr_eval(n);
  5129. if (r != NULL)
  5130. {
  5131. if (r->tag == N_EXPRSTMT)
  5132. r = r->a;
  5133. if (IS_EXPR(r))
  5134. n = r;
  5135. }
  5136. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  5137. }
  5138. else
  5139. EMIT("qi_get(state, \"%s\")", name);
  5140. }
  5141. break;
  5142. case T_TRUE:
  5143. EMIT("state->_true");
  5144. break;
  5145. case T_FALSE:
  5146. EMIT("state->_false");
  5147. break;
  5148. case T_NIL:
  5149. EMIT("state->nil");
  5150. break;
  5151. default:
  5152. COMPILE_ERROR("not yet implemented");
  5153. }
  5154. break;
  5155. case N_COMMA:
  5156. EMIT("(");
  5157. for (size_t i = 0; i < node->l->length; i++)
  5158. {
  5159. if (i != 0)
  5160. EMIT(", ");
  5161. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l->data[i]);
  5162. }
  5163. EMIT(")");
  5164. break;
  5165. case N_LIST:
  5166. EMIT("qi_make_list(state, ");
  5167. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  5168. EMIT(")");
  5169. break;
  5170. case N_LISTGEN:
  5171. {
  5172. NEWGID();
  5173. buffer_t *tbuf = buffer_new();
  5174. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  5175. PREFIX, gid);
  5176. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  5177. buffer_t *bbuf = buffer_new();
  5178. CTXPUSH("scope");
  5179. buffer_fmt(tbuf, "qi_new_scope(state);\n");
  5180. if (node->b)
  5181. {
  5182. buffer_fmt(bbuf, "if (_qi_truthy(state, ");
  5183. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  5184. buffer_fmt(bbuf, ")) {\n");
  5185. }
  5186. for (size_t i = 0; i < node->a->b->l->length; i++)
  5187. {
  5188. buffer_fmt(bbuf, "qi_list_push(list, ");
  5189. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl,
  5190. node->a->b->l->data[i]);
  5191. buffer_fmt(bbuf, ");\n");
  5192. }
  5193. if (node->b)
  5194. buffer_fmt(bbuf, "}\n");
  5195. node->a->b = nodeb(bbuf);
  5196. node->a->t2 = NULL;
  5197. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5198. CTXPOP();
  5199. buffer_fmt(tbuf, "qi_old_scope(state);\n");
  5200. buffer_fmt(tbuf, "return qi_make_list(state, list);\n}\n");
  5201. buffer_appendb(gbuf, tbuf);
  5202. EMIT("__%s%d(state)", PREFIX, gid);
  5203. }
  5204. break;
  5205. case N_TABLEGEN:
  5206. {
  5207. NEWGID();
  5208. buffer_t *tbuf = buffer_new();
  5209. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  5210. PREFIX, gid);
  5211. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  5212. buffer_t *bbuf = buffer_new();
  5213. CTXPUSH("scope");
  5214. buffer_fmt(tbuf, "qi_new_scope(state);\n");
  5215. if (node->b)
  5216. {
  5217. buffer_fmt(bbuf, "if (_qi_truthy(state, ");
  5218. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  5219. buffer_fmt(bbuf, ")) {\n");
  5220. }
  5221. for (size_t i = 0; i < node->a->b->l->length; i++)
  5222. {
  5223. list_t *pair = node->a->b->l->data[i];
  5224. buffer_fmt(bbuf, "qi_table_set(table, qi_to_string(state, ");
  5225. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  5226. buffer_fmt(bbuf, ")->value.string, ");
  5227. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  5228. buffer_fmt(bbuf, ");\n");
  5229. }
  5230. if (node->b)
  5231. buffer_fmt(bbuf, "}\n");
  5232. node->a->b = nodeb(bbuf);
  5233. node->a->t2 = NULL;
  5234. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5235. CTXPOP();
  5236. buffer_fmt(tbuf, "qi_old_scope(state);\n");
  5237. buffer_fmt(tbuf, "return qi_make_table(state, table);\n}\n");
  5238. buffer_appendb(gbuf, tbuf);
  5239. EMIT("__%s%d(state)", PREFIX, gid);
  5240. }
  5241. break;
  5242. case N_TUPLE:
  5243. EMIT("qi_make_tuple(state, ");
  5244. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  5245. EMIT(")");
  5246. break;
  5247. case N_NILTUPLE:
  5248. EMIT("state->empty_tuple");
  5249. break;
  5250. case N_TABLE:
  5251. EMIT("qi_make_table(state, ");
  5252. compile_pairs(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  5253. EMIT(")");
  5254. break;
  5255. case N_CALL:
  5256. if (DEBUG)
  5257. {
  5258. EMIT("qi_call_debug(state, ");
  5259. }
  5260. else
  5261. {
  5262. EMIT("qi_call(state, ");
  5263. }
  5264. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5265. EMIT(", ");
  5266. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  5267. if (DEBUG)
  5268. buffer_fmt(buf, ", __debugData[%d]", insert_debug(node));
  5269. EMIT(")");
  5270. break;
  5271. case N_MEMBER:
  5272. EMIT("qi_index(state, ");
  5273. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5274. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  5275. break;
  5276. case N_INDEX:
  5277. EMIT("qi_index(state, ");
  5278. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5279. EMIT(", ");
  5280. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  5281. EMIT(")");
  5282. break;
  5283. case N_SLICE:
  5284. {
  5285. NEWGID();
  5286. buffer_t *tbuf = buffer_new();
  5287. buffer_fmt(tbuf, "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  5288. PREFIX, gid);
  5289. if (node->b && node->c)
  5290. {
  5291. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  5292. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  5293. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5294. buffer_fmt(tbuf, ";\n");
  5295. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  5296. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  5297. buffer_fmt(tbuf, ";\n");
  5298. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  5299. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  5300. buffer_fmt(tbuf, ";\n");
  5301. }
  5302. else if (node->b)
  5303. {
  5304. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(2);\n");
  5305. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  5306. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5307. buffer_fmt(tbuf, ";\n");
  5308. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  5309. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  5310. buffer_fmt(tbuf, ";\n");
  5311. }
  5312. else
  5313. {
  5314. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  5315. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  5316. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5317. buffer_fmt(tbuf, ";\n");
  5318. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = state->zero;\n");
  5319. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  5320. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  5321. buffer_fmt(tbuf, ";\n");
  5322. }
  5323. buffer_fmt(tbuf,
  5324. "return qi_call(state, qi_get(state, \"__slice\"), pargs);\n");
  5325. buffer_fmt(tbuf, "}\n");
  5326. buffer_appendb(gbuf, tbuf);
  5327. EMIT("__%s%d(state)", PREFIX, gid);
  5328. }
  5329. break;
  5330. case N_DECL:
  5331. case N_ASSIGN:
  5332. if (node->a->tag == N_LIST)
  5333. {
  5334. if (node->a->l->length < 2)
  5335. COMPILE_ERROR("illegal unpack assignment left-hand side");
  5336. NEWGID();
  5337. buffer_t *tbuf = buffer_new();
  5338. buffer_fmt(tbuf,
  5339. "inline static qi_value_t *__%s%d(qi_state_t *state) {\n",
  5340. PREFIX, gid);
  5341. char *varname = tempvar();
  5342. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  5343. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  5344. buffer_fmt(tbuf, ";\n");
  5345. for (size_t i = 0; i < node->a->l->length; i++)
  5346. {
  5347. if (node->tag == N_DECL)
  5348. {
  5349. DECLIN(tbuf, (node_t *)node->a->l->data[i],
  5350. buffer_fmt(tbuf,
  5351. "qi_index(state, %s, qi_make_number(state, %d))",
  5352. varname, i));
  5353. }
  5354. else
  5355. {
  5356. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i],
  5357. buffer_fmt(tbuf,
  5358. "qi_index(state, %s, qi_make_number(state, %d))",
  5359. varname, i),
  5360. false);
  5361. }
  5362. buffer_fmt(tbuf, ";\n");
  5363. }
  5364. buffer_fmt(tbuf, "return %s;\n}\n", varname);
  5365. buffer_appendb(gbuf, tbuf);
  5366. EMIT("__%s%d(state)", PREFIX, gid);
  5367. break;
  5368. }
  5369. else if (node->a->tag == N_TUPLE)
  5370. {
  5371. if (node->a->l->length < 2)
  5372. COMPILE_ERROR("illegal multiple assignment left-hand side");
  5373. if (node->b->tag != N_TUPLE || node->b->l->length < 2 ||
  5374. node->a->l->length != node->b->l->length)
  5375. COMPILE_ERROR("illegal multiple assignment right-hand side");
  5376. NEWGID();
  5377. buffer_t *tbuf = buffer_new();
  5378. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX,
  5379. gid);
  5380. list_t *vals = list_new();
  5381. for (size_t i = 0; i < node->b->l->length; i++)
  5382. {
  5383. char *varname = tempvar();
  5384. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  5385. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl,
  5386. node->b->l->data[i]);
  5387. buffer_fmt(tbuf, ";\n");
  5388. list_push(vals, varname);
  5389. }
  5390. for (size_t i = 0; i < node->a->l->length; i++)
  5391. {
  5392. char *varname = vals->data[i];
  5393. if (node->tag == N_DECL)
  5394. {
  5395. DECLIN(tbuf, (node_t *)node->a->l->data[i],
  5396. buffer_fmt(tbuf, "%s", varname));
  5397. }
  5398. else
  5399. {
  5400. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i],
  5401. buffer_fmt(tbuf, "%s", varname), false);
  5402. }
  5403. buffer_fmt(tbuf, ";\n");
  5404. }
  5405. buffer_fmt(tbuf, "return %s;\n}\n", vals->data[vals->length - 1]);
  5406. buffer_appendb(gbuf, tbuf);
  5407. EMIT("__%s%d(state)", PREFIX, gid);
  5408. break;
  5409. }
  5410. if (node->tag == N_DECL)
  5411. {
  5412. DECL(node->a,
  5413. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5414. }
  5415. else
  5416. {
  5417. ASSIGN(node->a,
  5418. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5419. }
  5420. break;
  5421. case N_ASSIGN_ADD:
  5422. COMPASSIGN(node->a, "add",
  5423. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5424. break;
  5425. case N_ASSIGN_SUB:
  5426. COMPASSIGN(node->a, "sub",
  5427. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5428. break;
  5429. case N_ASSIGN_MUL:
  5430. COMPASSIGN(node->a, "mul",
  5431. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5432. break;
  5433. case N_ASSIGN_DIV:
  5434. COMPASSIGN(node->a, "div",
  5435. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5436. break;
  5437. case N_ASSIGN_IDIV:
  5438. COMPASSIGN(node->a, "idiv",
  5439. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5440. break;
  5441. case N_ASSIGN_MOD:
  5442. COMPASSIGN(node->a, "mod",
  5443. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5444. break;
  5445. case N_ASSIGN_POW:
  5446. COMPASSIGN(node->a, "pow",
  5447. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5448. break;
  5449. case N_ASSIGN_BOR:
  5450. COMPASSIGN(node->a, "bor",
  5451. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5452. break;
  5453. case N_ASSIGN_BAND:
  5454. COMPASSIGN(node->a, "band",
  5455. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5456. break;
  5457. case N_ASSIGN_XOR:
  5458. COMPASSIGN(node->a, "xor",
  5459. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5460. break;
  5461. case N_ASSIGN_SHL:
  5462. COMPASSIGN(node->a, "shl",
  5463. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5464. break;
  5465. case N_ASSIGN_SHR:
  5466. COMPASSIGN(node->a, "shr",
  5467. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  5468. break;
  5469. case N_INC:
  5470. COMPASSIGN(node->a, "add", EMIT("state->one"));
  5471. break;
  5472. case N_DEC:
  5473. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  5474. break;
  5475. case N_PINC:
  5476. COMPASSIGNP(node->a, "add", EMIT("state->one"));
  5477. break;
  5478. case N_PDEC:
  5479. COMPASSIGNP(node->a, "sub", EMIT("state->one"));
  5480. break;
  5481. case N_VAR:
  5482. case N_LET:
  5483. table_iterate(node->h, {
  5484. EMIT("qi_%s(state, \"%s\", ", node->tag == N_LET ? "decl_const" : "decl",
  5485. entry.key);
  5486. if (entry.value)
  5487. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, entry.value);
  5488. else
  5489. EMIT("state->nil");
  5490. EMIT(");\n");
  5491. });
  5492. break;
  5493. case N_VARUNPACK:
  5494. case N_LETUNPACK:
  5495. {
  5496. char *varname = tempvar();
  5497. EMIT("qi_value_t *%s = ", varname);
  5498. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5499. EMIT(";\n");
  5500. for (size_t i = 0; i < node->l->length; i++)
  5501. EMIT("%s(state, \"%s\", qi_index(state, %s, qi_make_number(state, "
  5502. "%d)));\n",
  5503. node->tag == N_VARUNPACK ? "qi_decl" : "qi_decl_const",
  5504. node->l->data[i], varname, i);
  5505. }
  5506. break;
  5507. case N_CONST:
  5508. case N_ENUM:
  5509. break;
  5510. case N_IF:
  5511. CTXPUSH("scope");
  5512. EMIT("qi_new_scope(state);\n");
  5513. EMIT("if (_qi_truthy(state, ");
  5514. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5515. EMIT(")) {\n");
  5516. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  5517. if (node->c)
  5518. {
  5519. EMIT("} else {\n");
  5520. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  5521. }
  5522. EMIT("}\n");
  5523. CTXPOP();
  5524. EMIT("qi_old_scope(state);\n");
  5525. break;
  5526. case N_SWITCH:
  5527. {
  5528. NEWGID();
  5529. CTXPUSH("scope");
  5530. EMIT("qi_new_scope(state);\n");
  5531. if (node->t2)
  5532. {
  5533. if (table_get(ltab, node->t2->text))
  5534. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  5535. int_stack_t *triple = stack_new();
  5536. stack_push(triple, 1);
  5537. stack_push(triple, gid);
  5538. stack_push(triple, scope_index(ctx));
  5539. table_set(ltab, node->t2->text, triple);
  5540. }
  5541. char *varname = tempvar();
  5542. EMIT("qi_value_t *%s = ", varname);
  5543. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5544. EMIT(";\n");
  5545. for (size_t i = 0; i < node->l->length; i++)
  5546. {
  5547. list_t *pair = node->l->data[i];
  5548. if (!pair->data[0])
  5549. continue;
  5550. char *label = tempvar();
  5551. EMIT("if (_qi_equals(state, %s, ", varname);
  5552. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  5553. EMIT(")) goto %s;\n", label);
  5554. pair->data[0] = label;
  5555. }
  5556. EMIT("goto __default%d;\n", gid);
  5557. SPUSH(gid);
  5558. CTXPUSH("switch");
  5559. int has_default = 0;
  5560. for (size_t i = 0; i < node->l->length; i++)
  5561. {
  5562. list_t *pair = node->l->data[i];
  5563. char *label = pair->data[0];
  5564. node_t *block = pair->data[1];
  5565. if (!label)
  5566. {
  5567. EMIT("__default%d:;\n", gid);
  5568. has_default = 1;
  5569. }
  5570. else
  5571. {
  5572. EMIT("%s:;\n", label);
  5573. }
  5574. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, block);
  5575. }
  5576. CTXPOP();
  5577. CTXPOP();
  5578. SPOP();
  5579. if (!has_default)
  5580. {
  5581. EMIT("__default%d:;\n", gid);
  5582. }
  5583. EMIT("__break%d:;\n", gid);
  5584. EMIT("qi_old_scope(state);\n");
  5585. }
  5586. break;
  5587. case N_FOR:
  5588. {
  5589. NEWGID();
  5590. CTXPUSH("scope");
  5591. EMIT("qi_new_scope(state);\n");
  5592. if (node->t2)
  5593. {
  5594. if (table_get(ltab, node->t2->text))
  5595. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  5596. int_stack_t *triple = stack_new();
  5597. stack_push(triple, 0);
  5598. stack_push(triple, gid);
  5599. stack_push(triple, scope_index(ctx));
  5600. table_set(ltab, node->t2->text, triple);
  5601. }
  5602. if (!node->a)
  5603. {
  5604. EMIT("for (;;) {\n");
  5605. }
  5606. else if (node->a && !node->b)
  5607. {
  5608. EMIT("while (_qi_truthy(state, ");
  5609. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5610. EMIT(")) {\n");
  5611. }
  5612. else
  5613. {
  5614. node_t *a = node->a;
  5615. if (IS_EXPR(a))
  5616. a = node1(N_EXPRSTMT, a);
  5617. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, a);
  5618. EMIT("while (_qi_truthy(state, ");
  5619. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  5620. EMIT(")) {\n");
  5621. }
  5622. CTXPUSH("scope");
  5623. EMIT("qi_new_scope(state);\n");
  5624. LPUSH(gid);
  5625. CTXPUSH("for");
  5626. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->d);
  5627. EMIT("__continue%d:;\n", gid);
  5628. if (node->c)
  5629. {
  5630. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  5631. EMIT(";\n");
  5632. }
  5633. CTXPOP();
  5634. LPOP();
  5635. CTXPOP();
  5636. EMIT("qi_old_scope(state);\n");
  5637. EMIT("}\n");
  5638. EMIT("goto __exit%d;\n", gid);
  5639. EMIT("__break%d:;\n", gid);
  5640. EMIT("qi_old_scope(state);\n");
  5641. EMIT("__exit%d:;\n", gid);
  5642. CTXPOP();
  5643. EMIT("qi_old_scope(state);\n");
  5644. }
  5645. break;
  5646. case N_FOROF:
  5647. case N_FOROFVAR:
  5648. case N_FOROFUNPACK:
  5649. case N_FOROFVARUNPACK:
  5650. {
  5651. NEWGID();
  5652. CTXPUSH("scope");
  5653. EMIT("qi_new_scope(state);\n");
  5654. if (node->t2)
  5655. {
  5656. if (table_get(ltab, node->t2->text))
  5657. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  5658. int_stack_t *triple = stack_new();
  5659. stack_push(triple, 0);
  5660. stack_push(triple, gid);
  5661. stack_push(triple, scope_index(ctx));
  5662. table_set(ltab, node->t2->text, triple);
  5663. }
  5664. char *varname = tempvar();
  5665. EMIT("qi_value_t *%s = qi_iter(state, ", varname);
  5666. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5667. EMIT(");\n");
  5668. if (node->tag == N_FOROFVAR && strcmp(node->t->text, "_") != 0)
  5669. {
  5670. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->t->text);
  5671. }
  5672. else if (node->tag == N_FOROFVARUNPACK)
  5673. {
  5674. for (size_t i = 0; i < node->l->length; i++)
  5675. if (strcmp(node->l->data[i], "_") != 0)
  5676. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->l->data[i]);
  5677. }
  5678. EMIT("while (!qi_iter_end(state, %s)) {\n", varname);
  5679. EMIT("qi_value_t *el = qi_iter_next(state, %s);\n", varname);
  5680. if (node->tag == N_FOROFUNPACK || node->tag == N_FOROFVARUNPACK)
  5681. {
  5682. for (size_t i = 0; i < node->l->length; i++)
  5683. if (strcmp(node->l->data[i], "_") == 0)
  5684. {
  5685. EMIT("(void)(qi_index(state, el, "
  5686. "qi_make_number(state, %d)));\n",
  5687. i);
  5688. }
  5689. else
  5690. {
  5691. EMIT("qi_set(state, false, \"%s\", qi_index(state, "
  5692. "el, qi_make_number(state, %d)));\n",
  5693. node->l->data[i], i);
  5694. }
  5695. }
  5696. else
  5697. {
  5698. if (strcmp(node->t->text, "_") != 0)
  5699. {
  5700. EMIT("qi_set(state, false, \"%s\", el);\n",
  5701. node->t->text);
  5702. }
  5703. }
  5704. CTXPUSH("scope");
  5705. EMIT("qi_new_scope(state);\n");
  5706. LPUSH(gid);
  5707. CTXPUSH("for");
  5708. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  5709. CTXPOP();
  5710. LPOP();
  5711. EMIT("__continue%d:;\n", gid);
  5712. CTXPOP();
  5713. EMIT("qi_old_scope(state);\n");
  5714. EMIT("}\n");
  5715. EMIT("goto __exit%d;\n", gid);
  5716. EMIT("__break%d:;\n", gid);
  5717. EMIT("qi_old_scope(state);\n");
  5718. EMIT("__exit%d:;\n", gid);
  5719. CTXPOP();
  5720. EMIT("qi_old_scope(state);\n");
  5721. }
  5722. break;
  5723. case N_BREAK:
  5724. {
  5725. if (!INCTX("for") && !INCTX("switch"))
  5726. COMPILE_ERROR("break outside of a loop or a switch");
  5727. if (node->t)
  5728. {
  5729. if (node->t->tag == T_NUMBER)
  5730. {
  5731. unsigned int offset = abs(atoi(node->t->text)) + 1;
  5732. if (offset < 2 || offset > lstk->length)
  5733. COMPILE_ERROR("%d is not a valid break loop offset", offset - 1);
  5734. int_stack_t *pair = lstk->data[lstk->length - offset];
  5735. size_t scopes_k = count_scopes(ctx, pair->data[1]);
  5736. for (size_t i = 0; i < scopes_k; i++)
  5737. {
  5738. EMIT("qi_old_scope(state);\n");
  5739. }
  5740. EMIT("goto __break%d;", pair->data[0]);
  5741. }
  5742. else
  5743. {
  5744. char *label = node->t->text;
  5745. int_stack_t *triple = table_get(ltab, label);
  5746. if (!triple)
  5747. COMPILE_ERROR("undefined loop label: '%s'", label);
  5748. size_t scopes_k = count_scopes(ctx, triple->data[2]);
  5749. for (size_t i = 0; i < scopes_k; i++)
  5750. {
  5751. EMIT("qi_old_scope(state);\n");
  5752. }
  5753. EMIT("goto __break%d;", triple->data[1]);
  5754. }
  5755. break;
  5756. }
  5757. size_t gid;
  5758. int_stack_t *pair;
  5759. if (in_switch(ctx))
  5760. {
  5761. pair = sstk->data[sstk->length - 1];
  5762. gid = pair->data[0];
  5763. }
  5764. else
  5765. {
  5766. pair = lstk->data[lstk->length - 1];
  5767. gid = pair->data[0];
  5768. }
  5769. size_t scopes_k = count_scopes(ctx, pair->data[1]);
  5770. for (size_t i = 0; i < scopes_k; i++)
  5771. {
  5772. EMIT("qi_old_scope(state);\n");
  5773. }
  5774. EMIT("goto __break%d;", gid);
  5775. }
  5776. break;
  5777. case N_CONTINUE:
  5778. {
  5779. if (!INCTX("for"))
  5780. COMPILE_ERROR("continue outside of a loop");
  5781. if (node->t)
  5782. {
  5783. if (node->t->tag == T_NUMBER)
  5784. {
  5785. unsigned int offset = abs(atoi(node->t->text)) + 1;
  5786. if (offset < 2 || offset > lstk->length)
  5787. COMPILE_ERROR("%d is not a valid break loop offset", offset - 1);
  5788. int_stack_t *pair = lstk->data[lstk->length - offset];
  5789. size_t scopes_k = count_scopes(ctx, pair->data[1]);
  5790. for (size_t i = 0; i < scopes_k; i++)
  5791. {
  5792. EMIT("qi_old_scope(state);\n");
  5793. }
  5794. EMIT("goto __continue%d;", pair->data[0]);
  5795. }
  5796. else
  5797. {
  5798. char *label = node->t->text;
  5799. int_stack_t *triple = table_get(ltab, label);
  5800. if (!triple)
  5801. COMPILE_ERROR("undefined loop label: '%s'", label);
  5802. if (triple->data[0])
  5803. COMPILE_ERROR("continue on a switch loop label: '%s'", label);
  5804. size_t scopes_k = count_scopes(ctx, triple->data[2]);
  5805. for (size_t i = 0; i < scopes_k; i++)
  5806. {
  5807. EMIT("qi_old_scope(state);\n");
  5808. }
  5809. EMIT("goto __continue%d;", triple->data[1]);
  5810. }
  5811. break;
  5812. }
  5813. int_stack_t *pair = lstk->data[lstk->length - 1];
  5814. size_t gid = pair->data[0];
  5815. size_t scopes_k = count_scopes(ctx, pair->data[1]);
  5816. for (size_t i = 0; i < scopes_k; i++)
  5817. {
  5818. EMIT("qi_old_scope(state);\n");
  5819. }
  5820. EMIT("goto __continue%d;", gid);
  5821. }
  5822. break;
  5823. case N_DEFER:
  5824. {
  5825. NEWGID();
  5826. buffer_t *tbuf = buffer_new();
  5827. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  5828. LBPUSH();
  5829. CTXPUSH("gap");
  5830. list_push(CONSTANTS, table_new());
  5831. list_push(MACROS, table_new());
  5832. compile_node(gbuf, tbuf, ctx, table_new(), list_new(), list_new(), lbl,
  5833. node->a);
  5834. list_pop(MACROS);
  5835. list_pop(CONSTANTS);
  5836. CTXPOP();
  5837. LBPOP();
  5838. buffer_fmt(tbuf, "\n}\n");
  5839. buffer_appendb(gbuf, tbuf);
  5840. EMIT("qi_add_defer(state, -1, __%s%d);", PREFIX, gid);
  5841. }
  5842. break;
  5843. case N_RETURN:
  5844. {
  5845. if (!INCTX("func"))
  5846. COMPILE_ERROR("return outside of a function");
  5847. char *varname = NULL;
  5848. if (node->a)
  5849. {
  5850. varname = tempvar();
  5851. EMIT("qi_value_t *%s = ", varname);
  5852. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5853. EMIT(";\n");
  5854. }
  5855. for (size_t i = 0; i < SCOPESK; i++)
  5856. EMIT("qi_old_scope(state);\n");
  5857. for (size_t i = 0; i < TRAPSK; i++)
  5858. EMIT("qi_unset_trap(state, trap);\n");
  5859. EMIT("return %s;", varname ? varname : "state->nil");
  5860. }
  5861. break;
  5862. case N_FUNCDEF:
  5863. break;
  5864. case N_CLASS:
  5865. break;
  5866. case N_PASS:
  5867. break;
  5868. case N_DEL:
  5869. EMIT("qi_del(state, ");
  5870. if (node->a->tag == N_INDEX)
  5871. {
  5872. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  5873. EMIT(", ");
  5874. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->b);
  5875. }
  5876. else if (node->a->tag == N_MEMBER)
  5877. {
  5878. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a->a);
  5879. EMIT(", qi_make_string(state, \"%s\")", node->a->t->text);
  5880. }
  5881. else
  5882. {
  5883. // COMPILE_ERROR("not a index/member expression");
  5884. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5885. EMIT(", NULL");
  5886. }
  5887. EMIT(");");
  5888. break;
  5889. case N_WITH:
  5890. {
  5891. NEWGID();
  5892. char *varname = tempvar();
  5893. buffer_fmt(gbuf, "qi_value_t *%s;\n", varname);
  5894. buffer_t *tbuf = buffer_new();
  5895. buffer_fmt(tbuf, "void __%s%d(qi_state_t *state) {\n", PREFIX, gid);
  5896. buffer_fmt(tbuf,
  5897. "qi_call(state, qi_index(state, %s, qi_make_string(state, "
  5898. "\"__leave\")), qi_list_push(qi_list_make(), %s));\n",
  5899. varname, varname);
  5900. buffer_fmt(tbuf, "}\n");
  5901. buffer_appendb(gbuf, tbuf);
  5902. EMIT("%s = ", varname);
  5903. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5904. EMIT(";\n");
  5905. EMIT("qi_call(state, qi_index(state, %s, qi_make_string(state, "
  5906. "\"__enter\")), qi_list_push(qi_list_make(), %s));\n",
  5907. varname, varname);
  5908. CTXPUSH("scope");
  5909. EMIT("qi_new_scope(state);\n");
  5910. EMIT("qi_add_local_defer(state, 0, __%s%d);\n", PREFIX, gid);
  5911. EMIT("qi_decl(state, \"%s\", %s);\n", node->t->text, varname);
  5912. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  5913. CTXPOP();
  5914. EMIT("qi_old_scope(state);\n");
  5915. }
  5916. break;
  5917. case N_THROW:
  5918. if (!node->a)
  5919. {
  5920. EMIT("qi_throw(state, state->nil);");
  5921. }
  5922. else if (DEBUG)
  5923. {
  5924. char *varname = tempvar();
  5925. EMIT("qi_value_t *%s = ", varname);
  5926. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5927. EMIT(";\n");
  5928. emit_debug(buf, node);
  5929. EMIT("qi_throw(state, %s);", varname);
  5930. }
  5931. else
  5932. {
  5933. EMIT("qi_throw(state, ");
  5934. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  5935. EMIT(");");
  5936. }
  5937. break;
  5938. case N_TRY:
  5939. {
  5940. int is_block = node->a->tag == N_PROGRAM;
  5941. NEWGID();
  5942. buffer_t *tbuf = buffer_new();
  5943. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  5944. char *varname1 = tempvar();
  5945. char *varname2 = tempvar();
  5946. if (!is_block)
  5947. buffer_fmt(tbuf, "qi_value_t *%s = state->nil;\n", varname1);
  5948. buffer_fmt(tbuf, "qi_value_t *%s = state->nil;\n", varname2);
  5949. buffer_fmt(tbuf, "qi_try(state, {\n");
  5950. if (!is_block)
  5951. buffer_fmt(tbuf, "%s = ", varname1);
  5952. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  5953. if (is_block)
  5954. buffer_fmt(tbuf, "}, {\n");
  5955. else
  5956. buffer_fmt(tbuf, ";\n}, {\n");
  5957. buffer_fmt(tbuf, "%s = trap->value;\n", varname2);
  5958. buffer_fmt(tbuf, "}, NULL);\n");
  5959. if (is_block)
  5960. buffer_fmt(tbuf, "return %s;\n", varname2);
  5961. else
  5962. {
  5963. char *varname3 = tempvar();
  5964. buffer_fmt(tbuf, "qi_list_t *%s = qi_list_make_n(2);\n", varname3);
  5965. buffer_fmt(tbuf, "qi_list_data(%s, 0) = %s;\n", varname3, varname1);
  5966. buffer_fmt(tbuf, "qi_list_data(%s, 1) = %s;\n", varname3, varname2);
  5967. buffer_fmt(tbuf, "return qi_make_tuple(state, %s);\n", varname3);
  5968. }
  5969. buffer_fmt(tbuf, "}\n");
  5970. buffer_appendb(gbuf, tbuf);
  5971. EMIT("__%s%d(state)", PREFIX, gid);
  5972. }
  5973. break;
  5974. case N_LABEL:
  5975. {
  5976. int_stack_t *pair = table_get(list_index(lbl, -1), node->t->text);
  5977. EMIT("__label%d:;", pair->data[0]);
  5978. }
  5979. break;
  5980. case N_GOTO:
  5981. {
  5982. char *label = node->t->text;
  5983. int_stack_t *pair = table_get(list_index(lbl, -1), label);
  5984. if (!pair)
  5985. COMPILE_ERROR("undefined label: '%s'", label);
  5986. size_t offset = pair->data[1];
  5987. if (offset >= ctx->length)
  5988. COMPILE_ERROR("cannot goto inwards");
  5989. size_t scopes_k = count_scopes(ctx, offset);
  5990. for (size_t i = 0; i < scopes_k; i++)
  5991. {
  5992. EMIT("qi_old_scope(state);\n");
  5993. }
  5994. EMIT("goto __label%d;", pair->data[0]);
  5995. }
  5996. break;
  5997. case N_REQUIRE:
  5998. for (size_t i = 0; i < node->l->length; i++)
  5999. {
  6000. token_t *t = node->l->data[i];
  6001. char *path = unescape(t->text);
  6002. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, path) < 0)
  6003. COMPILE_ERROR("'%s' is not a valid file path or a builtin library name",
  6004. path);
  6005. }
  6006. break;
  6007. case N_IFEXPR:
  6008. EMIT("(_qi_truthy(state, ");
  6009. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  6010. EMIT(")? ");
  6011. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  6012. EMIT(": ");
  6013. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  6014. EMIT(")");
  6015. break;
  6016. case N_SWITCHEXPR:
  6017. {
  6018. NEWGID();
  6019. buffer_t *tbuf = buffer_new();
  6020. char *varname1 = tempvar();
  6021. char *varname2 = tempvar();
  6022. char *labelname = tempvar();
  6023. buffer_fmt(tbuf, "qi_value_t *__%s%d(qi_state_t *state) {\n", PREFIX, gid);
  6024. buffer_fmt(tbuf, "qi_value_t *%s = state->nil;\n", varname1);
  6025. buffer_fmt(tbuf, "qi_value_t *%s = ", varname2);
  6026. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  6027. buffer_fmt(tbuf, ";\n");
  6028. for (size_t i = 0; i < node->l->length; i++)
  6029. {
  6030. list_t *pair = node->l->data[i];
  6031. buffer_fmt(tbuf, "if (_qi_equals(state, %s, ", varname2);
  6032. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  6033. buffer_fmt(tbuf, ")) {\n");
  6034. buffer_fmt(tbuf, "%s = ", varname1);
  6035. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  6036. buffer_fmt(tbuf, ";\n");
  6037. buffer_fmt(tbuf, "goto %s;\n}\n", labelname);
  6038. }
  6039. if (node->b)
  6040. {
  6041. buffer_fmt(tbuf, "%s = ", varname1);
  6042. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  6043. buffer_fmt(tbuf, ";\n");
  6044. }
  6045. buffer_fmt(tbuf, "%s: return %s;\n", labelname, varname1);
  6046. buffer_fmt(tbuf, "}\n");
  6047. buffer_appendb(gbuf, tbuf);
  6048. EMIT("__%s%d(state)", PREFIX, gid);
  6049. }
  6050. break;
  6051. case N_FUNCEXPR:
  6052. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  6053. break;
  6054. case N_EQUALS:
  6055. BINOP("equals");
  6056. break;
  6057. case N_NOTEQUALS:
  6058. BINOP("not_equals");
  6059. break;
  6060. case N_IS:
  6061. BINOP("is");
  6062. break;
  6063. case N_NOTIS:
  6064. BINOP("not_is");
  6065. break;
  6066. case N_IN:
  6067. BINOP("in");
  6068. break;
  6069. case N_NOTIN:
  6070. BINOP("not_in");
  6071. break;
  6072. case N_LT:
  6073. BINOP("lt");
  6074. break;
  6075. case N_GT:
  6076. BINOP("gt");
  6077. break;
  6078. case N_LE:
  6079. BINOP("le");
  6080. break;
  6081. case N_GE:
  6082. BINOP("ge");
  6083. break;
  6084. case N_ADD:
  6085. BINOP("add");
  6086. break;
  6087. case N_SUB:
  6088. BINOP("sub");
  6089. break;
  6090. case N_MUL:
  6091. BINOP("mul");
  6092. break;
  6093. case N_DIV:
  6094. BINOP("div");
  6095. break;
  6096. case N_IDIV:
  6097. BINOP("idiv");
  6098. break;
  6099. case N_MOD:
  6100. BINOP("mod");
  6101. break;
  6102. case N_POW:
  6103. BINOP("pow");
  6104. break;
  6105. case N_SHL:
  6106. BINOP("shl");
  6107. break;
  6108. case N_SHR:
  6109. BINOP("shr");
  6110. break;
  6111. case N_XOR:
  6112. BINOP("xor");
  6113. break;
  6114. case N_BOR:
  6115. BINOP("bor");
  6116. break;
  6117. case N_BAND:
  6118. BINOP("band");
  6119. break;
  6120. case N_LOGOR:
  6121. BINOP("or");
  6122. break;
  6123. case N_LOGAND:
  6124. BINOP("and");
  6125. break;
  6126. case N_NEGATE:
  6127. UNOP("negate");
  6128. break;
  6129. case N_UNARY_PLUS:
  6130. UNOP("unary_plus");
  6131. break;
  6132. case N_NOT:
  6133. UNOP("not");
  6134. break;
  6135. case N_BNOT:
  6136. UNOP("bnot");
  6137. break;
  6138. case N_REFERENCE:
  6139. EMIT("qi_make_ref(state, \"%s\")", node->t->text);
  6140. break;
  6141. case N_DEREFERENCE:
  6142. EMIT("qi_deref(state, ");
  6143. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  6144. EMIT(")");
  6145. break;
  6146. case N_MACRO_CALL:
  6147. compile_macro_call(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, 1);
  6148. break;
  6149. case N_MVAR:
  6150. COMPILE_ERROR("macro variable outside of a macro");
  6151. case N_INLINE:
  6152. {
  6153. char *text = unescape(node->t->text);
  6154. if (text[0] == '#')
  6155. {
  6156. EMIT("%s", text);
  6157. }
  6158. else if (text[0] && (text[strlen(text) - 1] == '{' || text[strlen(text) - 1] == '}'))
  6159. {
  6160. EMIT("%s", text);
  6161. }
  6162. else
  6163. {
  6164. EMIT("%s;", text);
  6165. }
  6166. }
  6167. break;
  6168. case N_HEADER:
  6169. buffer_fmt(HBUF, "%s\n", unescape(node->t->text));
  6170. break;
  6171. case N_INCLUDE:
  6172. buffer_fmt(HBUF, "#include <%s>\n", unescape(node->t->text));
  6173. break;
  6174. case N_BUFFER:
  6175. buffer_appendb(buf, node->buf);
  6176. break;
  6177. default:
  6178. COMPILE_ERROR("not yet implemented");
  6179. }
  6180. }
  6181. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx,
  6182. table_t *ltab, list_t *lstk, list_t *sstk, list_t *lbl)
  6183. {
  6184. node_t *n = parse(source);
  6185. if (NEEDS_UTF8 && !is_required("utf8"))
  6186. {
  6187. NEEDS_UTF8 = 0;
  6188. require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, "utf8");
  6189. }
  6190. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  6191. }
  6192. char *escape(char *s)
  6193. {
  6194. buffer_t *buf = buffer_new();
  6195. while (*s)
  6196. {
  6197. if (*s == '\\' || *s == '"')
  6198. buffer_append(buf, '\\');
  6199. buffer_append(buf, *s++);
  6200. }
  6201. return buffer_read(buf);
  6202. }
  6203. char *compile(char *source, list_t *required)
  6204. {
  6205. list_t *ctx = list_new();
  6206. list_push(ctx, "top");
  6207. table_t *ltab = table_new();
  6208. list_t *lstk = list_new();
  6209. list_t *sstk = list_new();
  6210. list_t *lbl = list_new();
  6211. LBPUSH();
  6212. buffer_t *gbuf = buffer_new();
  6213. buffer_t *buf = buffer_new();
  6214. compile_into("const __QIC = \"" QIC_VER "\"", gbuf, buf, ctx, ltab, lstk,
  6215. sstk, lbl);
  6216. compile_into("macro E(x) {\n$set r E(x)\n$if r = nil\n$x\n$else\n$r\n$endif}",
  6217. gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  6218. if (required && required->length)
  6219. for (size_t i = 0; i < required->length; i++)
  6220. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl,
  6221. required->data[i]) < 0)
  6222. {
  6223. fprintf(
  6224. stderr,
  6225. "fatal: '%s' is not a valid file path or a builtin library name\n",
  6226. (char *)required->data[i]);
  6227. exit(1);
  6228. }
  6229. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  6230. buffer_t *rbuf = buffer_new();
  6231. buffer_appends(rbuf, "#include <qirt.h>\n");
  6232. if (DEBUG && DEBUGDATA->length)
  6233. {
  6234. buffer_fmt(rbuf, "static const char *__debugData[%d] = {\n",
  6235. DEBUGDATA->length);
  6236. for (size_t i = 0; i < DEBUGDATA->length; i++)
  6237. buffer_fmt(rbuf, "\"%s\",\n", escape(DEBUGDATA->data[i]));
  6238. buffer_fmt(rbuf, "};\n");
  6239. }
  6240. buffer_appendb(rbuf, HBUF);
  6241. buffer_appendb(rbuf, gbuf);
  6242. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  6243. buffer_fmt(rbuf, "if (qi_rt_version() < %luUL) {\n", LIBQIRT_VER);
  6244. buffer_fmt(rbuf, " fprintf(stderr, \"fatal: unsupported libqirt version\\n\");\n");
  6245. buffer_fmt(rbuf, " abort();\n");
  6246. buffer_fmt(rbuf, "}\n\n");
  6247. buffer_appends(rbuf, "qi_state_t *state;\n");
  6248. if (DEBUG)
  6249. buffer_appends(rbuf, "qi_state_init_debug(&state);\n");
  6250. else
  6251. buffer_appends(rbuf, "qi_state_init(&state);\n");
  6252. buffer_appends(rbuf, "qi_list_t *args = qi_list_make();\n");
  6253. buffer_appends(rbuf, "for (int i = 0; i < argc; i++)\n");
  6254. buffer_appends(rbuf,
  6255. " qi_list_push(args, qi_make_string(state, argv[i]));\n");
  6256. buffer_appends(
  6257. rbuf, "qi_decl_const(state, \"ARGS\", qi_make_list(state, args));\n");
  6258. buffer_appendb(rbuf, buf);
  6259. buffer_appends(rbuf, "qi_old_scope(state);\n");
  6260. buffer_appends(rbuf, "qi_finalize();\n");
  6261. buffer_appends(rbuf, "return 0;\n");
  6262. buffer_appends(rbuf, "}\n");
  6263. return buffer_read(rbuf);
  6264. }
  6265. char *compile_file(char *filename, FILE *fd, list_t *required)
  6266. {
  6267. buffer_t *buf = buffer_new();
  6268. for (;;)
  6269. {
  6270. char line[512];
  6271. if (!fgets(line, sizeof(line), fd))
  6272. break;
  6273. buffer_appends(buf, line);
  6274. }
  6275. char *source = buffer_read(buf);
  6276. list_t *pair = list_new();
  6277. list_push(pair, filename);
  6278. list_push(pair, source);
  6279. list_push(FILES, pair);
  6280. char *out = compile(source, required);
  6281. list_pop(FILES);
  6282. return out;
  6283. }
  6284. int main(int argc, char **argv)
  6285. {
  6286. YES = nodet(N_LITERAL, token(T_STRING, "yes"));
  6287. DEBUGDATA = list_new();
  6288. FUNCNAMES = list_new();
  6289. FILES = list_new();
  6290. REQUIRED = list_new();
  6291. CONSTANTS = list_new();
  6292. list_push(CONSTANTS, table_new());
  6293. MACROS = list_new();
  6294. list_push(MACROS, table_new());
  6295. macro_stk = list_new();
  6296. HBUF = buffer_new();
  6297. MVARS = list_new();
  6298. MACROCALLS = list_new();
  6299. genmathlib();
  6300. char tmp[512];
  6301. char *out;
  6302. char *main = NULL;
  6303. char *outf = NULL;
  6304. list_t *required = NULL;
  6305. int readstdin = 0;
  6306. for (size_t i = 1; i < argc; i++)
  6307. {
  6308. if (*argv[i] == '-')
  6309. {
  6310. if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--debug") == 0)
  6311. DEBUG = 1;
  6312. else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--stdin") == 0)
  6313. readstdin = 1;
  6314. else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--prefix") == 0)
  6315. {
  6316. if (i + 1 >= argc)
  6317. {
  6318. fprintf(stderr,
  6319. "fatal: missing argument after '-p/--prefix' parameter\n");
  6320. return 1;
  6321. }
  6322. PREFIX = argv[++i];
  6323. }
  6324. else if (strcmp(argv[i], "-o") == 0 ||
  6325. strcmp(argv[i], "--output") == 0)
  6326. {
  6327. if (i + 1 >= argc)
  6328. {
  6329. fprintf(stderr,
  6330. "fatal: missing argument after '-o/--output' parameter\n");
  6331. return 1;
  6332. }
  6333. outf = argv[++i];
  6334. }
  6335. else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0 ||
  6336. strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-v") == 0 ||
  6337. strcmp(argv[i], "--version") == 0)
  6338. {
  6339. fprintf(stderr, "qilang compiler, " QIC_VER "\n");
  6340. fprintf(
  6341. stderr,
  6342. "usage: %s [-dsh] [-p prefix] [-o out.c] [input0.qi input1.qi ... inputN.qi]\n",
  6343. argv[0]);
  6344. fprintf(stderr, "-h --help\tprint this message and exit\n");
  6345. fprintf(stderr, "-d --debug\tenable debug mode\n");
  6346. fprintf(stderr, "-s --stdin\tread stdin as input\n");
  6347. fprintf(stderr, "-p --prefix\tset prefix for generated C names\n");
  6348. fprintf(stderr,
  6349. "-o --output\toutput generated C code to the specified file\n");
  6350. return 0;
  6351. }
  6352. else
  6353. {
  6354. fprintf(stderr, "fatal: unknown commandline argument: '%s'\n", argv[i]);
  6355. return 1;
  6356. }
  6357. continue;
  6358. }
  6359. if (!readstdin && !main)
  6360. main = argv[i];
  6361. else
  6362. {
  6363. if (!required)
  6364. required = list_new();
  6365. list_push(required, argv[i]);
  6366. }
  6367. }
  6368. if (!PREFIX)
  6369. {
  6370. const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  6371. srand(time(NULL));
  6372. PREFIX = malloc_checked(sizeof(char) * 9);
  6373. PREFIX[8] = 0;
  6374. for (size_t i = 0; i < 8; i++)
  6375. PREFIX[i] =
  6376. chars[(size_t)((double)rand() / RAND_MAX * (sizeof(chars) - 1))];
  6377. }
  6378. if (readstdin || !main)
  6379. out = compile_file("<stdin>", stdin, required);
  6380. else
  6381. {
  6382. FILE *fd;
  6383. if (is_directory(main))
  6384. {
  6385. snprintf(tmp, sizeof(tmp), "%s/main.qi", main);
  6386. fd = fopen(tmp, "rb");
  6387. }
  6388. else
  6389. fd = fopen(main, "rb");
  6390. if (!fd)
  6391. {
  6392. fprintf(stderr, "fatal: unable to open file: '%s'\n", main);
  6393. return 1;
  6394. }
  6395. list_push(REQUIRED, main);
  6396. out = compile_file(main, fd, required);
  6397. fclose(fd);
  6398. }
  6399. if (outf && strcmp(outf, "-") != 0)
  6400. {
  6401. FILE *fd = fopen(outf, "wb");
  6402. if (!fd)
  6403. {
  6404. fprintf(stderr, "fatal: unable to open output file: '%s'\n", outf);
  6405. return 1;
  6406. }
  6407. fwrite(out, sizeof(char), strlen(out), fd);
  6408. fclose(fd);
  6409. }
  6410. else
  6411. fwrite(out, sizeof(char), strlen(out), stdout);
  6412. return 0;
  6413. }