qic.c 142 KB

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