qic.c 128 KB

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