qic.c 143 KB

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