qic.c 181 KB

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