qic.c 132 KB

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