qic.c 148 KB

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