qic.c 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdarg.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. size_t GID = 0;
  7. typedef struct {
  8. void **data;
  9. size_t length;
  10. } list_t;
  11. list_t *list_new(void) {
  12. list_t *list = malloc(sizeof(list_t));
  13. list->data = NULL;
  14. list->length = 0;
  15. return list;
  16. }
  17. void list_push(list_t *l, void *v) {
  18. size_t i = l->length++;
  19. l->data = realloc(l->data, l->length * sizeof(void *));
  20. l->data[i] = v;
  21. }
  22. void *list_pop(list_t *l) {
  23. if (!l->length)
  24. return NULL;
  25. return l->data[--l->length];
  26. }
  27. void *list_index(list_t *l, ssize_t index) {
  28. if (!l->length)
  29. return NULL;
  30. if (index < 0)
  31. index += ((ssize_t)l->length);
  32. if (index < 0 || index >= l->length)
  33. return NULL;
  34. return l->data[index];
  35. }
  36. void list_set(list_t *l, ssize_t index, void *v) {
  37. if (!l->length)
  38. return;
  39. if (index < 0)
  40. index += ((ssize_t)l->length);
  41. if (index < 0 || index >= l->length)
  42. return;
  43. l->data[index] = v;
  44. }
  45. typedef struct {
  46. size_t *data;
  47. size_t length;
  48. } stack_t;
  49. stack_t *stack_new(void) {
  50. stack_t *stack = malloc(sizeof(list_t));
  51. stack->data = NULL;
  52. stack->length = 0;
  53. return stack;
  54. }
  55. void stack_push(stack_t *l, size_t v) {
  56. size_t i = l->length++;
  57. l->data = realloc(l->data, l->length * sizeof(size_t));
  58. l->data[i] = v;
  59. }
  60. size_t stack_pop(stack_t *l) {
  61. if (!l->length)
  62. return 0;
  63. return l->data[--l->length];
  64. }
  65. struct entry_t {
  66. char *key;
  67. void *value;
  68. };
  69. struct table_t {
  70. struct entry_t *entries;
  71. size_t used;
  72. size_t capacity;
  73. };
  74. typedef struct entry_t entry_t;
  75. typedef struct table_t table_t;
  76. table_t *table_new() {
  77. table_t *table = malloc(sizeof(table_t));
  78. table->used = 0;
  79. table->capacity = 32;
  80. table->entries = calloc(table->capacity, sizeof(entry_t));
  81. return table;
  82. }
  83. unsigned long ht_hash(const char* key) {
  84. unsigned long hash = 5381;
  85. int c;
  86. while ((c = *key++))
  87. hash = ((hash << 5) + hash) + c;
  88. return hash;
  89. }
  90. void *table_get(table_t *table, char *key) {
  91. if (!table->used)
  92. return NULL;
  93. unsigned long hash = ht_hash(key);
  94. size_t index = hash % table->capacity;
  95. size_t i = index;
  96. while (table->entries[i].key) {
  97. if (strcmp(table->entries[i].key, key) == 0)
  98. return table->entries[i].value;
  99. i++;
  100. if (i >= table->capacity)
  101. i = 0;
  102. if (i == index)
  103. break;
  104. }
  105. return NULL;
  106. }
  107. static void table_entry_set(entry_t *entries, char *key, void *value, size_t capacity, size_t *used) {
  108. unsigned long hash = ht_hash(key);
  109. size_t index = hash % capacity;
  110. size_t i = index;
  111. while (entries[i].key) {
  112. if (strcmp(entries[i].key, key) == 0) {
  113. entries[i].value = value;
  114. return;
  115. }
  116. i++;
  117. if (i >= capacity)
  118. i = 0;
  119. if (i == index)
  120. break;
  121. }
  122. if (used)
  123. (*used)++;
  124. entries[i].key = key;
  125. entries[i].value = value;
  126. }
  127. table_t *table_set(table_t *table, char *key, void *value) {
  128. if (table->used >= table->capacity) {
  129. size_t capacity = table->capacity + 32;
  130. entry_t *entries = calloc(capacity, sizeof(entry_t));
  131. for (size_t i = 0; i < table->capacity; i++) {
  132. entry_t entry = table->entries[i];
  133. if (entry.key)
  134. table_entry_set(entries, entry.key, entry.value, capacity, NULL);
  135. }
  136. table->entries = entries;
  137. table->capacity = capacity;
  138. }
  139. table_entry_set(table->entries, key, value, table->capacity, &table->used);
  140. return table;
  141. }
  142. #define table_iterate(table, code) \
  143. { \
  144. if ((table)->used) { \
  145. size_t i = 0; \
  146. while (i < (table)->capacity) { \
  147. entry_t entry = (table)->entries[i]; \
  148. if (entry.key) { \
  149. code; \
  150. } \
  151. i++; \
  152. } \
  153. } \
  154. }
  155. typedef struct {
  156. char *str;
  157. size_t size;
  158. } buffer_t;
  159. buffer_t *buffer_new(void) {
  160. buffer_t *buf = malloc(sizeof(buffer_t));
  161. buf->str = NULL;
  162. buf->size = 0;
  163. return buf;
  164. }
  165. void buffer_append(buffer_t *buf, char c) {
  166. buf->size++;
  167. buf->str = realloc(buf->str, sizeof(char) * buf->size);
  168. buf->str[buf->size - 1] = c;
  169. }
  170. char *buffer_read(buffer_t *buf) {
  171. if (buf->size == 0 || buf->str[buf->size - 1])
  172. buffer_append(buf, 0);
  173. return buf->str;
  174. }
  175. void buffer_appends(buffer_t *buf, char *s) {
  176. for (size_t i = 0; i < strlen(s); i++)
  177. buffer_append(buf, s[i]);
  178. }
  179. void buffer_appendb(buffer_t *dst, buffer_t *src) {
  180. for (size_t i = 0; i < src->size; i++)
  181. buffer_append(dst, src->str[i]);
  182. }
  183. void buffer_fmt(buffer_t *buf, const char *fmt, ...) {
  184. va_list args;
  185. va_start(args, fmt);
  186. size_t size = vsnprintf(NULL, 0, fmt, args);
  187. char *str = malloc(sizeof(char) * (size + 1));
  188. vsnprintf(str, size + 1, fmt, args);
  189. va_end(args);
  190. buffer_appends(buf, str);
  191. }
  192. typedef struct {
  193. enum {
  194. T_EOF,
  195. T_NUMBER,
  196. T_STRING,
  197. T_FSTRING,
  198. T_NAME,
  199. T_VAR,
  200. T_LET,
  201. T_CONST,
  202. T_UNPACK,
  203. T_IF,
  204. T_ELSE,
  205. T_ELIF,
  206. T_SWITCH,
  207. T_CASE,
  208. T_DEFAULT,
  209. T_FOR,
  210. T_OF,
  211. T_BREAK,
  212. T_CONTINUE,
  213. T_PASS,
  214. T_FUNC,
  215. T_USE,
  216. T_RETURN,
  217. T_DEFER,
  218. T_REQUIRE,
  219. T_TRY,
  220. T_CATCH,
  221. T_THROW,
  222. T_GOTO,
  223. T_CLASS,
  224. T_IS,
  225. T_IN,
  226. T_LPAR,
  227. T_RPAR,
  228. T_LSB,
  229. T_RSB,
  230. T_LCB,
  231. T_RCB,
  232. T_EQUALS,
  233. T_NOTEQUALS,
  234. T_PLUSASSIGN,
  235. T_MINUSASSIGN,
  236. T_SLASHASSIGN,
  237. T_STARASSIGN,
  238. T_SLASHSLASHASSIGN,
  239. T_PERCENTASSIGN,
  240. T_STARSTARASSIGN,
  241. T_BARASSIGN,
  242. T_ANDASSIGN,
  243. T_BARBAR,
  244. T_ANDAND,
  245. T_STARSTAR,
  246. T_PLUSPLUS,
  247. T_MINUSMINUS,
  248. T_SLASHSLASH,
  249. T_PLUS,
  250. T_MINUS,
  251. T_QM,
  252. T_COLON,
  253. T_BAR,
  254. T_AND,
  255. T_LT,
  256. T_LTLT,
  257. T_GT,
  258. T_GTGT,
  259. T_LE,
  260. T_GE,
  261. T_STAR,
  262. T_SLASH,
  263. T_PERCENT,
  264. T_COMMA,
  265. T_DOT,
  266. T_BANG,
  267. T_RAISE,
  268. T_TILDE,
  269. T_AT,
  270. T_INLINE,
  271. T_HEADER,
  272. T_INCLUDE,
  273. T_ASSIGN,
  274. T_SEMI
  275. } tag;
  276. char *text;
  277. size_t fi;
  278. size_t pos;
  279. } token_t;
  280. token_t *token(int tag, char *text) {
  281. token_t *tok = malloc(sizeof(token_t));
  282. tok->tag = tag;
  283. tok->text = text;
  284. return tok;
  285. }
  286. #define TK(tk) (token(T_##tk, NULL))
  287. #define WS() while (source[*pos] == ' ' || source[*pos] == '\t' || source[*pos] == '\n' || source[*pos] == '\r') { (*pos)++; }
  288. void consume_ignored(char *source, size_t *pos) {
  289. WS();
  290. while (source[*pos] == '#') {
  291. (*pos)++;
  292. for (;;) {
  293. if (!source[*pos])
  294. break;
  295. if (source[*pos] == '\n') {
  296. (*pos)++;
  297. break;
  298. }
  299. (*pos)++;
  300. }
  301. WS();
  302. }
  303. }
  304. list_t *FILES;
  305. list_t *REQUIRED;
  306. int is_required(char *path) {
  307. for (size_t i = 0; i < REQUIRED->length; i++)
  308. if (strcmp(REQUIRED->data[i], path) == 0)
  309. return 1;
  310. return 0;
  311. }
  312. void traverse(char *source, size_t pos, size_t *line, size_t *col) {
  313. *line = 1;
  314. *col = 1;
  315. for (size_t i = 0; i < pos; i++) {
  316. if (source[i] == '\n') {
  317. (*line)++;
  318. (*col) = 1;
  319. } else (*col)++;
  320. }
  321. }
  322. void format_error(char *filename, char *source, size_t pos, char *fmt, ...) {
  323. size_t line, col;
  324. traverse(source, pos, &line, &col);
  325. va_list args;
  326. va_start(args, fmt);
  327. fprintf(stderr, "%s (%zu:%zu): ", filename, line, col);
  328. vfprintf(stderr, fmt, args);
  329. fputc('\n', stderr);
  330. va_end(args);
  331. }
  332. #define GETFNAME(fi) ((char *)((list_t *)list_index(FILES, fi))->data[0])
  333. #define GETSRC(fi) ((char *)((list_t *)list_index(FILES, fi))->data[1])
  334. #define LEX_ERROR(fmt, ...) { format_error(GETFNAME(-1), source, *pos, fmt, ##__VA_ARGS__); exit(1); }
  335. token_t *tokenize_string(char *source, size_t *pos) {
  336. char term = source[(*pos)++];
  337. buffer_t *text = buffer_new();
  338. while (source[*pos] != term) {
  339. if (!source[*pos])
  340. LEX_ERROR("unterminated string literal");
  341. char c = source[(*pos)++];
  342. if (c == '\n' && term != '`')
  343. LEX_ERROR("unterminated string literal");
  344. if (term != '`' && c == '\\') {
  345. char nc = source[(*pos)++];
  346. if (!nc)
  347. continue;
  348. switch (nc) {
  349. case 'n':
  350. buffer_appends(text, "\\n");
  351. break;
  352. case 't':
  353. buffer_appends(text, "\\t");
  354. break;
  355. case 'r':
  356. buffer_appends(text, "\\r");
  357. break;
  358. case 'b':
  359. buffer_appends(text, "\\b");
  360. break;
  361. case 'e':
  362. buffer_appends(text, "\\e");
  363. break;
  364. case 's':
  365. buffer_appends(text, " ");
  366. break;
  367. case '"':
  368. buffer_appends(text, "\\\"");
  369. break;
  370. case '\\':
  371. buffer_appends(text, "\\\\");
  372. break;
  373. case '\n':
  374. buffer_appends(text, "\\n");
  375. break;
  376. default:
  377. buffer_append(text, nc);
  378. break;
  379. }
  380. continue;
  381. }
  382. if (c == '"' || c == '\\')
  383. buffer_append(text, '\\');
  384. else if (c == '\n')
  385. buffer_appends(text, "\\n");
  386. buffer_append(text, c);
  387. }
  388. (*pos)++;
  389. return token(T_STRING, buffer_read(text));
  390. }
  391. token_t *next_token(char *source, size_t *pos) {
  392. if (!source[*pos])
  393. return token(T_EOF, NULL);
  394. if (source[*pos] == '"' || source[*pos] == '\'' || source[*pos] == '`')
  395. return tokenize_string(source, pos);
  396. else if (source[*pos] == 'f' && (source[(*pos)+1] == '"' || source[(*pos)+1] == '\'' || source[(*pos)+1] == '`')) {
  397. (*pos)++;
  398. token_t *t = tokenize_string(source, pos);
  399. t->tag = T_FSTRING;
  400. return t;
  401. } else if (source[*pos] == '0' && (source[(*pos)+1] == 'x' || source[(*pos)+1] == 'b' || source[(*pos)+1] == 'o')) {
  402. buffer_t *number = buffer_new();
  403. buffer_append(number, source[(*pos)++]);
  404. char b = source[(*pos)++];
  405. buffer_append(number, b);
  406. while (source[*pos] && strchr(b == 'x' ? "0123456789abcdefABCDEF": b == 'b' ? "01": "01234567", source[*pos]) != NULL)
  407. buffer_append(number, source[(*pos)++]);
  408. if (number->size < 3)
  409. LEX_ERROR("illegal number literal (trailing base)");
  410. return token(T_NUMBER, buffer_read(number));
  411. } else if ((source[*pos] == '.' && isdigit(source[(*pos)+1])) || isdigit(source[*pos])) {
  412. buffer_t *number = buffer_new();
  413. int dot = 0;
  414. int sub = 0;
  415. int skip = 0;
  416. if (source[*pos] == '.') {
  417. buffer_append(number, '0');
  418. skip = 1;
  419. }
  420. do {
  421. if (skip) skip = 0;
  422. else
  423. buffer_append(number, source[(*pos)++]);
  424. if (!dot && source[*pos] == '.') {
  425. buffer_append(number, source[(*pos)++]);
  426. if (!isdigit(source[*pos]))
  427. LEX_ERROR("illegal number literal (missing part after floating point)");
  428. dot = 1;
  429. } else if (!sub && source[*pos] == '_') {
  430. (*pos)++;
  431. if (!isdigit(source[*pos]))
  432. LEX_ERROR("illegal number literal (missing part after underscore)");
  433. sub = 1;
  434. } else if (sub) sub = 0;
  435. } while (isdigit(source[*pos]));
  436. return token(T_NUMBER, buffer_read(number));
  437. } else if (isalpha(source[*pos]) || source[*pos] == '_') {
  438. buffer_t *text = buffer_new();
  439. do {
  440. buffer_append(text, source[(*pos)++]);
  441. } while (isalpha(source[*pos]) || source[*pos] == '_' || isdigit(source[*pos]));
  442. char *name = buffer_read(text);
  443. if (strcmp(name, "var") == 0)
  444. return TK(VAR);
  445. else if (strcmp(name, "let") == 0)
  446. return TK(LET);
  447. else if (strcmp(name, "const") == 0)
  448. return TK(CONST);
  449. else if (strcmp(name, "unpack") == 0)
  450. return TK(UNPACK);
  451. else if (strcmp(name, "if") == 0)
  452. return TK(IF);
  453. else if (strcmp(name, "else") == 0)
  454. return TK(ELSE);
  455. else if (strcmp(name, "elif") == 0)
  456. return TK(ELIF);
  457. else if (strcmp(name, "switch") == 0)
  458. return TK(SWITCH);
  459. else if (strcmp(name, "case") == 0)
  460. return TK(CASE);
  461. else if (strcmp(name, "default") == 0)
  462. return TK(DEFAULT);
  463. else if (strcmp(name, "for") == 0)
  464. return TK(FOR);
  465. else if (strcmp(name, "break") == 0)
  466. return TK(BREAK);
  467. else if (strcmp(name, "continue") == 0)
  468. return TK(CONTINUE);
  469. else if (strcmp(name, "func") == 0)
  470. return TK(FUNC);
  471. else if (strcmp(name, "use") == 0)
  472. return TK(USE);
  473. else if (strcmp(name, "return") == 0)
  474. return TK(RETURN);
  475. else if (strcmp(name, "defer") == 0)
  476. return TK(DEFER);
  477. else if (strcmp(name, "pass") == 0)
  478. return TK(PASS);
  479. else if (strcmp(name, "require") == 0)
  480. return TK(REQUIRE);
  481. else if (strcmp(name, "try") == 0)
  482. return TK(TRY);
  483. else if (strcmp(name, "catch") == 0)
  484. return TK(CATCH);
  485. else if (strcmp(name, "throw") == 0)
  486. return TK(THROW);
  487. else if (strcmp(name, "goto") == 0)
  488. return TK(GOTO);
  489. else if (strcmp(name, "class") == 0)
  490. return TK(CLASS);
  491. else if (strcmp(name, "is") == 0)
  492. return TK(IS);
  493. else if (strcmp(name, "in") == 0)
  494. return TK(IN);
  495. else if (strcmp(name, "of") == 0)
  496. return TK(OF);
  497. else if (strcmp(name, "inline") == 0)
  498. return TK(INLINE);
  499. else if (strcmp(name, "header") == 0)
  500. return TK(HEADER);
  501. else if (strcmp(name, "include") == 0)
  502. return TK(INCLUDE);
  503. return token(T_NAME, name);
  504. } else if (strncmp(&source[*pos], "==", 2) == 0 && ++(*pos) && ++(*pos))
  505. return TK(EQUALS);
  506. else if (strncmp(&source[*pos], "!=", 2) == 0 && ++(*pos) && ++(*pos))
  507. return TK(NOTEQUALS);
  508. else if (strncmp(&source[*pos], "+=", 2) == 0 && ++(*pos) && ++(*pos))
  509. return TK(PLUSASSIGN);
  510. else if (strncmp(&source[*pos], "-=", 2) == 0 && ++(*pos) && ++(*pos))
  511. return TK(MINUSASSIGN);
  512. else if (strncmp(&source[*pos], "*=", 2) == 0 && ++(*pos) && ++(*pos))
  513. return TK(STARASSIGN);
  514. else if (strncmp(&source[*pos], "/=", 2) == 0 && ++(*pos) && ++(*pos))
  515. return TK(SLASHASSIGN);
  516. else if (strncmp(&source[*pos], "//=", 3) == 0 && ++(*pos) && ++(*pos) && ++(*pos))
  517. return TK(SLASHSLASHASSIGN);
  518. else if (strncmp(&source[*pos], "%=", 2) == 0 && ++(*pos) && ++(*pos))
  519. return TK(PERCENTASSIGN);
  520. else if (strncmp(&source[*pos], "**=", 3) == 0 && ++(*pos) && ++(*pos) && ++(*pos))
  521. return TK(STARSTARASSIGN);
  522. else if (strncmp(&source[*pos], "|=", 2) == 0 && ++(*pos) && ++(*pos))
  523. return TK(BARASSIGN);
  524. else if (strncmp(&source[*pos], "&=", 2) == 0 && ++(*pos) && ++(*pos))
  525. return TK(ANDASSIGN);
  526. else if (strncmp(&source[*pos], "||", 2) == 0 && ++(*pos) && ++(*pos))
  527. return TK(BARBAR);
  528. else if (strncmp(&source[*pos], "&&", 2) == 0 && ++(*pos) && ++(*pos))
  529. return TK(ANDAND);
  530. else if (strncmp(&source[*pos], "++", 2) == 0 && ++(*pos) && ++(*pos))
  531. return TK(PLUSPLUS);
  532. else if (strncmp(&source[*pos], "--", 2) == 0 && ++(*pos) && ++(*pos))
  533. return TK(MINUSMINUS);
  534. else if (strncmp(&source[*pos], "//", 2) == 0 && ++(*pos) && ++(*pos))
  535. return TK(SLASHSLASH);
  536. else if (strncmp(&source[*pos], "**", 2) == 0 && ++(*pos) && ++(*pos))
  537. return TK(STARSTAR);
  538. else if (strncmp(&source[*pos], "<<", 2) == 0 && ++(*pos) && ++(*pos))
  539. return TK(LTLT);
  540. else if (strncmp(&source[*pos], ">>", 2) == 0 && ++(*pos) && ++(*pos))
  541. return TK(GTGT);
  542. else if (strncmp(&source[*pos], "<=", 2) == 0 && ++(*pos) && ++(*pos))
  543. return TK(LE);
  544. else if (strncmp(&source[*pos], ">=", 2) == 0 && ++(*pos) && ++(*pos))
  545. return TK(GE);
  546. else if (source[*pos] == '(' && ++(*pos))
  547. return TK(LPAR);
  548. else if (source[*pos] == ')' && ++(*pos))
  549. return TK(RPAR);
  550. else if (source[*pos] == '[' && ++(*pos))
  551. return TK(LSB);
  552. else if (source[*pos] == ']' && ++(*pos))
  553. return TK(RSB);
  554. else if (source[*pos] == '{' && ++(*pos))
  555. return TK(LCB);
  556. else if (source[*pos] == '}' && ++(*pos))
  557. return TK(RCB);
  558. else if (source[*pos] == '+' && ++(*pos))
  559. return TK(PLUS);
  560. else if (source[*pos] == '-' && ++(*pos))
  561. return TK(MINUS);
  562. else if (source[*pos] == '*' && ++(*pos))
  563. return TK(STAR);
  564. else if (source[*pos] == '/' && ++(*pos))
  565. return TK(SLASH);
  566. else if (source[*pos] == '%' && ++(*pos))
  567. return TK(PERCENT);
  568. else if (source[*pos] == '?' && ++(*pos))
  569. return TK(QM);
  570. else if (source[*pos] == ':' && ++(*pos))
  571. return TK(COLON);
  572. else if (source[*pos] == '=' && ++(*pos))
  573. return TK(ASSIGN);
  574. else if (source[*pos] == ';' && ++(*pos))
  575. return TK(SEMI);
  576. else if (source[*pos] == ',' && ++(*pos))
  577. return TK(COMMA);
  578. else if (source[*pos] == '.' && ++(*pos))
  579. return TK(DOT);
  580. else if (source[*pos] == '<' && ++(*pos))
  581. return TK(LT);
  582. else if (source[*pos] == '>' && ++(*pos))
  583. return TK(GT);
  584. else if (source[*pos] == '!' && ++(*pos))
  585. return TK(BANG);
  586. else if (source[*pos] == '|' && ++(*pos))
  587. return TK(BAR);
  588. else if (source[*pos] == '&' && ++(*pos))
  589. return TK(AND);
  590. else if (source[*pos] == '^' && ++(*pos))
  591. return TK(RAISE);
  592. else if (source[*pos] == '~' && ++(*pos))
  593. return TK(TILDE);
  594. else if (source[*pos] == '@' && ++(*pos))
  595. return TK(AT);
  596. LEX_ERROR("unexpected input")
  597. }
  598. list_t *tokenize(char *source) {
  599. size_t pos = 0;
  600. list_t *toks = list_new();
  601. do {
  602. consume_ignored(source, &pos);
  603. size_t tok_pos = pos;
  604. token_t *tok = next_token(source, &pos);
  605. tok->fi = FILES->length-1;
  606. tok->pos = tok_pos;
  607. list_push(toks, tok);
  608. if (tok->tag == T_EOF)
  609. break;
  610. } while (1);
  611. return toks;
  612. }
  613. struct _node_t {
  614. enum {
  615. N_TOPLEVEL,
  616. N_PROGRAM,
  617. N_EXPRSTMT,
  618. N_BLOCK,
  619. N_NOT,
  620. N_NEGATE,
  621. N_BNOT,
  622. N_LITERAL,
  623. N_LIST,
  624. N_LISTGEN,
  625. N_TUPLE,
  626. N_NILTUPLE,
  627. N_TABLE,
  628. N_CALL,
  629. N_STAR,
  630. N_MEMBER,
  631. N_INDEX,
  632. N_SLICE,
  633. N_ADD,
  634. N_SUB,
  635. N_MUL,
  636. N_DIV,
  637. N_IDIV,
  638. N_MOD,
  639. N_POW,
  640. N_SHL,
  641. N_SHR,
  642. N_XOR,
  643. N_BOR,
  644. N_BAND,
  645. N_ASSIGN,
  646. N_ASSIGN_ADD,
  647. N_ASSIGN_SUB,
  648. N_ASSIGN_MUL,
  649. N_ASSIGN_DIV,
  650. N_ASSIGN_IDIV,
  651. N_ASSIGN_MOD,
  652. N_ASSIGN_POW,
  653. N_ASSIGN_BOR,
  654. N_ASSIGN_BAND,
  655. N_EQUALS,
  656. N_NOTEQUALS,
  657. N_IS,
  658. N_IN,
  659. N_NOTIS,
  660. N_NOTIN,
  661. N_LT,
  662. N_GT,
  663. N_LE,
  664. N_GE,
  665. N_INC,
  666. N_DEC,
  667. N_VAR,
  668. N_LET,
  669. N_VARUNPACK,
  670. N_LETUNPACK,
  671. N_CONST,
  672. N_IF,
  673. N_SWITCH,
  674. N_FOR,
  675. N_FOROF,
  676. N_FOROFVAR,
  677. N_FOROFUNPACK,
  678. N_FOROFVARUNPACK,
  679. N_BREAK,
  680. N_CONTINUE,
  681. N_FUNCDEF,
  682. N_RETURN,
  683. N_DEFER,
  684. N_PASS,
  685. N_REQUIRE,
  686. N_TRY,
  687. N_THROW,
  688. N_LABEL,
  689. N_GOTO,
  690. N_CLASS,
  691. N_INLINE,
  692. N_HEADER,
  693. N_INCLUDE,
  694. N_IFEXPR,
  695. N_FUNCEXPR,
  696. N_LOGOR,
  697. N_LOGAND,
  698. N_BUFFER
  699. } tag;
  700. struct _node_t *a;
  701. struct _node_t *b;
  702. struct _node_t *c;
  703. struct _node_t *d;
  704. list_t *l;
  705. table_t *h;
  706. table_t *h2;
  707. token_t *t;
  708. token_t *t2;
  709. buffer_t *buf;
  710. size_t fi;
  711. size_t pos;
  712. };
  713. typedef struct _node_t node_t;
  714. node_t *node_pos(node_t *node, size_t fi, size_t pos) {
  715. node->fi = fi;
  716. node->pos = pos;
  717. return node;
  718. }
  719. node_t *nodet(int tag, token_t *t) {
  720. node_t *node = malloc(sizeof(node_t));
  721. node->tag = tag;
  722. node->t = t;
  723. return node;
  724. }
  725. #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))
  726. node_t *nodel(int tag, list_t *l) {
  727. node_t *node = malloc(sizeof(node_t));
  728. node->tag = tag;
  729. node->l = l;
  730. return node;
  731. }
  732. #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))
  733. node_t *nodetl(int tag, token_t *t, list_t *l) {
  734. node_t *node = malloc(sizeof(node_t));
  735. node->tag = tag;
  736. node->t = t;
  737. node->l = l;
  738. return node;
  739. }
  740. #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))
  741. node_t *nodeh(int tag, table_t *h) {
  742. node_t *node = malloc(sizeof(node_t));
  743. node->tag = tag;
  744. node->h = h;
  745. return node;
  746. }
  747. #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))
  748. node_t *node0(int tag) {
  749. node_t *node = malloc(sizeof(node_t));
  750. node->tag = tag;
  751. return node;
  752. }
  753. #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))
  754. node_t *node1(int tag, node_t *a) {
  755. node_t *node = malloc(sizeof(node_t));
  756. node->tag = tag;
  757. node->a = a;
  758. return node;
  759. }
  760. #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))
  761. node_t *node1l(int tag, node_t *a, list_t *l) {
  762. node_t *node = malloc(sizeof(node_t));
  763. node->tag = tag;
  764. node->a = a;
  765. node->l = l;
  766. return node;
  767. }
  768. #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))
  769. node_t *node1t(int tag, node_t *a, token_t *t) {
  770. node_t *node = malloc(sizeof(node_t));
  771. node->tag = tag;
  772. node->a = a;
  773. node->t = t;
  774. return node;
  775. }
  776. #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))
  777. node_t *node2(int tag, node_t *a, node_t *b) {
  778. node_t *node = malloc(sizeof(node_t));
  779. node->tag = tag;
  780. node->a = a;
  781. node->b = b;
  782. return node;
  783. }
  784. #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))
  785. node_t *node2l(int tag, node_t *a, node_t *b, list_t *l) {
  786. node_t *node = malloc(sizeof(node_t));
  787. node->tag = tag;
  788. node->a = a;
  789. node->b = b;
  790. node->l = l;
  791. return node;
  792. }
  793. #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))
  794. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t) {
  795. node_t *node = malloc(sizeof(node_t));
  796. node->tag = tag;
  797. node->a = a;
  798. node->b = b;
  799. node->t = t;
  800. return node;
  801. }
  802. #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))
  803. node_t *node3(int tag, node_t *a, node_t *b, node_t *c) {
  804. node_t *node = malloc(sizeof(node_t));
  805. node->tag = tag;
  806. node->a = a;
  807. node->b = b;
  808. node->c = c;
  809. return node;
  810. }
  811. #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))
  812. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d) {
  813. node_t *node = malloc(sizeof(node_t));
  814. node->tag = tag;
  815. node->a = a;
  816. node->b = b;
  817. node->c = c;
  818. node->d = d;
  819. return node;
  820. }
  821. #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))
  822. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured, node_t *body) {
  823. node_t *node = malloc(sizeof(node_t));
  824. node->tag = tag;
  825. node->t = name;
  826. node->h = params;
  827. node->h2 = captured;
  828. node->a = body;
  829. return node;
  830. }
  831. #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))
  832. node_t *nodeb(buffer_t *buf) {
  833. node_t *node = malloc(sizeof(node_t));
  834. node->tag = N_BUFFER;
  835. node->buf = buf;
  836. return node;
  837. }
  838. #define LABELLOOP(n)\
  839. node_t *ln = (n);\
  840. ln->t2 = label;
  841. #define AT(tk) (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  842. #define ATP(tk, p) ((*pos)+p < tokens->length && ((token_t *)tokens->data[(*pos)+p])->tag == T_##tk)
  843. #define MATCH(tk) (AT(tk) && ++(*pos))
  844. #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); }
  845. #define EXPECT(tk, s) { if (!MATCH(tk)) PARSE_ERROR("expected %s", (s)); }
  846. node_t *parse_expr(list_t *tokens, size_t *pos);
  847. list_t *parse_sequence(list_t *tokens, size_t *pos, int term) {
  848. list_t *seq = list_new();
  849. do {
  850. if (term != -1 && *pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == term)
  851. break;
  852. if (MATCH(STAR))
  853. list_push(seq, NODE1(STAR, parse_expr(tokens, pos)));
  854. else
  855. list_push(seq, parse_expr(tokens, pos));
  856. } while (MATCH(COMMA));
  857. return seq;
  858. }
  859. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  860. char *unescape(char *s);
  861. node_t *parse_primary(list_t *tokens, size_t *pos) {
  862. if (MATCH(FUNC))
  863. return parse_func(tokens, pos, 1);
  864. else if (MATCH(LPAR)) {
  865. if (MATCH(RPAR))
  866. return NODE0(NILTUPLE);
  867. node_t *a = parse_expr(tokens, pos);
  868. if (MATCH(COMMA)) {
  869. list_t *l = list_new();
  870. list_push(l, a);
  871. if (!AT(RPAR))
  872. do {
  873. node_t *n = parse_expr(tokens, pos);
  874. list_push(l, n);
  875. } while (MATCH(COMMA));
  876. a = NODEL(TUPLE, l);
  877. }
  878. EXPECT(RPAR, ")");
  879. return a;
  880. } else if (MATCH(LSB)) {
  881. list_t *a = parse_sequence(tokens, pos, T_RSB);
  882. node_t *loop = NULL;
  883. if (MATCH(FOR)) {
  884. if (MATCH(LSB)) {
  885. list_t *l = list_new();
  886. do {
  887. if(!AT(NAME))
  888. PARSE_ERROR("expected identifier");
  889. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  890. } while (MATCH(COMMA));
  891. EXPECT(RSB, "]");
  892. EXPECT(OF, "of");
  893. loop = NODE2l(FOROFUNPACK, parse_expr(tokens, pos), NODEL(LIST, a), l);
  894. } else {
  895. if(!AT(NAME))
  896. PARSE_ERROR("expected identifier");
  897. token_t *t = tokens->data[(*pos)++];
  898. EXPECT(OF, "of");
  899. loop = NODE2t(FOROF, parse_expr(tokens, pos), NODEL(LIST, a), t);
  900. }
  901. }
  902. EXPECT(RSB, "]");
  903. if (loop)
  904. return NODE1(LISTGEN, loop);
  905. return NODEL(LIST, a);
  906. } else if (MATCH(LCB)) {
  907. table_t *table = table_new();
  908. do {
  909. if (AT(RCB))
  910. break;
  911. if (!AT(NAME) && !AT(STRING))
  912. PARSE_ERROR("expected identifier or string");
  913. int is_str = AT(STRING);
  914. char *key = ((token_t *)tokens->data[(*pos)++])->text;
  915. EXPECT(COLON, ":");
  916. node_t *val = parse_expr(tokens, pos);
  917. table_set(table, is_str? unescape(key): key, val);
  918. } while (MATCH(COMMA));
  919. EXPECT(RCB, "}");
  920. return NODEH(TABLE, table);
  921. } else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(FSTRING) || MATCH(NAME))
  922. return NODET(LITERAL, tokens->data[(*pos)-1]);
  923. PARSE_ERROR("expected expression");
  924. return NULL;
  925. }
  926. size_t get_lineno(token_t *tok) {
  927. size_t line, col;
  928. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  929. return line;
  930. }
  931. #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)])))
  932. #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])))
  933. node_t *parse_call(list_t *tokens, size_t *pos) {
  934. node_t *a = parse_primary(tokens, pos);
  935. do {
  936. if (!CLIFF && MATCH(LPAR)) {
  937. list_t *b = NULL;
  938. if (!AT(RPAR))
  939. b = parse_sequence(tokens, pos, -1);
  940. EXPECT(RPAR, ")");
  941. a = NODE1l(CALL, a, b);
  942. continue;
  943. } else if (!CLIFF && MATCH(LSB)) {
  944. if (MATCH(COLON)) {
  945. a = NODE3(SLICE, a, NULL, parse_expr(tokens, pos));
  946. EXPECT(RSB, "]");
  947. continue;
  948. }
  949. node_t *b = parse_expr(tokens, pos);
  950. if (MATCH(COLON)) {
  951. node_t *c = NULL;
  952. if (!AT(RSB))
  953. c = parse_expr(tokens, pos);
  954. EXPECT(RSB, "]");
  955. a = NODE3(SLICE, a, b, c);
  956. continue;
  957. }
  958. EXPECT(RSB, "]");
  959. a = NODE2(INDEX, a, b);
  960. continue;
  961. } else if (!CLIFF && MATCH(DOT)) {
  962. if (!AT(NAME))
  963. PARSE_ERROR("expected identifier after .");
  964. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  965. continue;
  966. }
  967. break;
  968. } while (1);
  969. return a;
  970. }
  971. node_t *parse_postfix(list_t *tokens, size_t *pos) {
  972. node_t *a = parse_call(tokens, pos);
  973. if (CLIFF)
  974. return a;
  975. if (MATCH(PLUSPLUS))
  976. return NODE1(INC, a);
  977. else if (MATCH(MINUSMINUS))
  978. return NODE1(DEC, a);
  979. return a;
  980. }
  981. node_t *parse_unary(list_t *tokens, size_t *pos) {
  982. if (MATCH(MINUS)) {
  983. node_t *a = parse_unary(tokens, pos);
  984. return NODE1(NEGATE, a);
  985. } else if (MATCH(BANG)) {
  986. node_t *a = parse_unary(tokens, pos);
  987. return NODE1(NOT, a);
  988. } else if (MATCH(TILDE)) {
  989. node_t *a = parse_unary(tokens, pos);
  990. return NODE1(BNOT, a);
  991. }
  992. return parse_postfix(tokens, pos);
  993. }
  994. node_t *parse_pow(list_t *tokens, size_t *pos) {
  995. node_t *a = parse_unary(tokens, pos);
  996. do {
  997. if (MATCH(STARSTAR)) {
  998. node_t *b = parse_unary(tokens, pos);
  999. a = NODE2(POW, a, b);
  1000. continue;
  1001. }
  1002. break;
  1003. } while (1);
  1004. return a;
  1005. }
  1006. node_t *parse_mul(list_t *tokens, size_t *pos) {
  1007. node_t *a = parse_pow(tokens, pos);
  1008. do {
  1009. if (MATCH(STAR)) {
  1010. node_t *b = parse_pow(tokens, pos);
  1011. a = NODE2(MUL, a, b);
  1012. continue;
  1013. } else if (MATCH(SLASH)) {
  1014. node_t *b = parse_pow(tokens, pos);
  1015. a = NODE2(DIV, a, b);
  1016. continue;
  1017. } else if (MATCH(SLASHSLASH)) {
  1018. node_t *b = parse_pow(tokens, pos);
  1019. a = NODE2(IDIV, a, b);
  1020. continue;
  1021. } else if (MATCH(PERCENT)) {
  1022. node_t *b = parse_pow(tokens, pos);
  1023. a = NODE2(MOD, a, b);
  1024. continue;
  1025. }
  1026. break;
  1027. } while (1);
  1028. return a;
  1029. }
  1030. node_t *parse_add(list_t *tokens, size_t *pos) {
  1031. node_t *a = parse_mul(tokens, pos);
  1032. do {
  1033. if (MATCH(PLUS)) {
  1034. node_t *b = parse_mul(tokens, pos);
  1035. a = NODE2(ADD, a, b);
  1036. continue;
  1037. } else if (MATCH(MINUS)) {
  1038. node_t *b = parse_mul(tokens, pos);
  1039. a = NODE2(SUB, a, b);
  1040. continue;
  1041. }
  1042. break;
  1043. } while (1);
  1044. return a;
  1045. }
  1046. node_t *parse_shift(list_t *tokens, size_t *pos) {
  1047. node_t *a = parse_add(tokens, pos);
  1048. do {
  1049. if (MATCH(LTLT)) {
  1050. node_t *b = parse_add(tokens, pos);
  1051. a = NODE2(SHL, a, b);
  1052. continue;
  1053. } else if (MATCH(GTGT)) {
  1054. node_t *b = parse_add(tokens, pos);
  1055. a = NODE2(SHR, a, b);
  1056. continue;
  1057. }
  1058. break;
  1059. } while (1);
  1060. return a;
  1061. }
  1062. node_t *parse_relation(list_t *tokens, size_t *pos) {
  1063. node_t *a = parse_shift(tokens, pos);
  1064. do {
  1065. if (MATCH(LT)) {
  1066. node_t *b = parse_shift(tokens, pos);
  1067. a = NODE2(LT, a, b);
  1068. continue;
  1069. } else if (MATCH(GT)) {
  1070. node_t *b = parse_shift(tokens, pos);
  1071. a = NODE2(GT, a, b);
  1072. continue;
  1073. } else if (MATCH(LE)) {
  1074. node_t *b = parse_shift(tokens, pos);
  1075. a = NODE2(LE, a, b);
  1076. continue;
  1077. } else if (MATCH(GE)) {
  1078. node_t *b = parse_shift(tokens, pos);
  1079. a = NODE2(GE, a, b);
  1080. continue;
  1081. }
  1082. break;
  1083. } while (1);
  1084. return a;
  1085. }
  1086. node_t *parse_equality(list_t *tokens, size_t *pos) {
  1087. node_t *a = parse_relation(tokens, pos);
  1088. do {
  1089. if (MATCH(EQUALS)) {
  1090. node_t *b = parse_relation(tokens, pos);
  1091. a = NODE2(EQUALS, a, b);
  1092. continue;
  1093. } else if (MATCH(NOTEQUALS)) {
  1094. node_t *b = parse_relation(tokens, pos);
  1095. a = NODE2(NOTEQUALS, a, b);
  1096. continue;
  1097. } else if (MATCH(IS)) {
  1098. node_t *b = parse_relation(tokens, pos);
  1099. a = NODE2(IS, a, b);
  1100. continue;
  1101. } else if (AT(BANG) && ATP(IS, 1)) {
  1102. EXPECT(BANG, "!");
  1103. EXPECT(IS, "is");
  1104. node_t *b = parse_relation(tokens, pos);
  1105. a = NODE2(NOTIS, a, b);
  1106. continue;
  1107. } else if (MATCH(IN)) {
  1108. node_t *b = parse_relation(tokens, pos);
  1109. a = NODE2(IN, a, b);
  1110. continue;
  1111. } else if (AT(BANG) && ATP(IN, 1)) {
  1112. EXPECT(BANG, "!");
  1113. EXPECT(IN, "in");
  1114. node_t *b = parse_relation(tokens, pos);
  1115. a = NODE2(NOTIN, a, b);
  1116. continue;
  1117. }
  1118. break;
  1119. } while (1);
  1120. return a;
  1121. }
  1122. node_t *parse_bitand(list_t *tokens, size_t *pos) {
  1123. node_t *a = parse_equality(tokens, pos);
  1124. while (MATCH(AND)) {
  1125. node_t *b = parse_equality(tokens, pos);
  1126. a = NODE2(BAND, a, b);
  1127. }
  1128. return a;
  1129. }
  1130. node_t *parse_bitxor(list_t *tokens, size_t *pos) {
  1131. node_t *a = parse_bitand(tokens, pos);
  1132. while (MATCH(RAISE)) {
  1133. node_t *b = parse_bitand(tokens, pos);
  1134. a = NODE2(XOR, a, b);
  1135. }
  1136. return a;
  1137. }
  1138. node_t *parse_bitor(list_t *tokens, size_t *pos) {
  1139. node_t *a = parse_bitxor(tokens, pos);
  1140. while (MATCH(BAR)) {
  1141. node_t *b = parse_bitxor(tokens, pos);
  1142. a = NODE2(BOR, a, b);
  1143. }
  1144. return a;
  1145. }
  1146. node_t *parse_logand(list_t *tokens, size_t *pos) {
  1147. node_t *a = parse_bitor(tokens, pos);
  1148. if (MATCH(ANDAND)) {
  1149. node_t *b = parse_logand(tokens, pos);
  1150. return NODE2(LOGAND, a, b);
  1151. }
  1152. return a;
  1153. }
  1154. node_t *parse_logor(list_t *tokens, size_t *pos) {
  1155. node_t *a = parse_logand(tokens, pos);
  1156. if (MATCH(BARBAR)) {
  1157. node_t *b = parse_logor(tokens, pos);
  1158. return NODE2(LOGOR, a, b);
  1159. }
  1160. return a;
  1161. }
  1162. node_t *parse_assignment(list_t *tokens, size_t *pos);
  1163. node_t *parse_conditional(list_t *tokens, size_t *pos) {
  1164. node_t *a = parse_logor(tokens, pos);
  1165. if (MATCH(QM)) {
  1166. node_t *b = parse_assignment(tokens, pos);
  1167. EXPECT(COLON, ":");
  1168. node_t *c = parse_assignment(tokens, pos);
  1169. return NODE3(IFEXPR, a, b, c);
  1170. }
  1171. return a;
  1172. }
  1173. node_t *parse_assignment(list_t *tokens, size_t *pos) {
  1174. node_t *a = parse_conditional(tokens, pos);
  1175. if (MATCH(ASSIGN)) {
  1176. node_t *b = parse_assignment(tokens, pos);
  1177. return NODE2(ASSIGN, a, b);
  1178. } else if (MATCH(PLUSASSIGN)) {
  1179. node_t *b = parse_assignment(tokens, pos);
  1180. return NODE2(ASSIGN_ADD, a, b);
  1181. } else if (MATCH(MINUSASSIGN)) {
  1182. node_t *b = parse_assignment(tokens, pos);
  1183. return NODE2(ASSIGN_SUB, a, b);
  1184. } else if (MATCH(STARASSIGN)) {
  1185. node_t *b = parse_assignment(tokens, pos);
  1186. return NODE2(ASSIGN_MUL, a, b);
  1187. } else if (MATCH(SLASHASSIGN)) {
  1188. node_t *b = parse_assignment(tokens, pos);
  1189. return NODE2(ASSIGN_DIV, a, b);
  1190. } else if (MATCH(SLASHSLASHASSIGN)) {
  1191. node_t *b = parse_assignment(tokens, pos);
  1192. return NODE2(ASSIGN_IDIV, a, b);
  1193. } else if (MATCH(PERCENTASSIGN)) {
  1194. node_t *b = parse_assignment(tokens, pos);
  1195. return NODE2(ASSIGN_MOD, a, b);
  1196. } else if (MATCH(STARSTARASSIGN)) {
  1197. node_t *b = parse_assignment(tokens, pos);
  1198. return NODE2(ASSIGN_POW, a, b);
  1199. } else if (MATCH(BARASSIGN)) {
  1200. node_t *b = parse_assignment(tokens, pos);
  1201. return NODE2(ASSIGN_BOR, a, b);
  1202. }
  1203. return a;
  1204. }
  1205. node_t *parse_expr(list_t *tokens, size_t *pos) {
  1206. return parse_assignment(tokens, pos);
  1207. }
  1208. node_t *parse_stmt(list_t *tokens, size_t *pos);
  1209. node_t *parse_block(list_t *tokens, size_t *pos) {
  1210. EXPECT(LCB, "{");
  1211. list_t *stmts = list_new();
  1212. while (!AT(EOF) && !AT(RCB)) {
  1213. list_push(stmts, parse_stmt(tokens, pos));
  1214. MATCH(SEMI);
  1215. }
  1216. EXPECT(RCB, "}");
  1217. return NODEL(PROGRAM, stmts);
  1218. }
  1219. #define BLOCK() (CLIFF||MATCH(COLON)?parse_stmt(tokens, pos):parse_block(tokens, pos))
  1220. node_t *parse_if(list_t *tokens, size_t *pos) {
  1221. node_t *a = parse_expr(tokens, pos);
  1222. node_t *b = BLOCK();
  1223. node_t *c = NULL;
  1224. if (MATCH(ELSE))
  1225. c = BLOCK();
  1226. else if (MATCH(ELIF))
  1227. c = parse_if(tokens, pos);
  1228. return NODE3(IF, a, b, c);
  1229. }
  1230. node_t *parse_var(list_t *tokens, size_t *pos, int is_let) {
  1231. table_t *h = table_new();
  1232. do {
  1233. if(!AT(NAME))
  1234. PARSE_ERROR("expected identifier");
  1235. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1236. node_t *v = NULL;
  1237. if (is_let) {
  1238. EXPECT(ASSIGN, "=");
  1239. v = parse_expr(tokens, pos);
  1240. } else if (MATCH(ASSIGN))
  1241. v = parse_expr(tokens, pos);
  1242. table_set(h, k, v);
  1243. } while (MATCH(COMMA));
  1244. if (is_let)
  1245. return NODEH(LET, h);
  1246. return NODEH(VAR, h);
  1247. }
  1248. node_t *parse_unpack(list_t *tokens, size_t *pos, int tag) {
  1249. EXPECT(LSB, "[");
  1250. list_t *l = list_new();
  1251. do {
  1252. if(!AT(NAME))
  1253. PARSE_ERROR("expected identifier");
  1254. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1255. } while (MATCH(COMMA));
  1256. EXPECT(RSB, "]");
  1257. EXPECT(ASSIGN, "=");
  1258. node_t *a = parse_expr(tokens, pos);
  1259. if (tag == N_LETUNPACK)
  1260. return NODE1l(LETUNPACK, a, l);
  1261. return NODE1l(VARUNPACK, a, l);
  1262. }
  1263. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr) {
  1264. token_t *name = NULL;
  1265. if (!is_expr) {
  1266. if(!AT(NAME))
  1267. PARSE_ERROR("expected identifier");
  1268. name = tokens->data[(*pos)++];
  1269. }
  1270. table_t *params = NULL;
  1271. if (MATCH(LPAR)) {
  1272. if (!AT(RPAR)) {
  1273. int flag = 0;
  1274. params = table_new();
  1275. size_t argc = 0;
  1276. do {
  1277. if(!AT(NAME))
  1278. PARSE_ERROR("expected identifier");
  1279. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  1280. node_t *r = NULL;
  1281. if (!flag && AT(ASSIGN))
  1282. flag = 1;
  1283. if (flag) {
  1284. EXPECT(ASSIGN, "=");
  1285. r = parse_expr(tokens, pos);
  1286. }
  1287. list_t *pair = list_new();
  1288. size_t *argcp = malloc(sizeof(size_t));
  1289. memcpy(argcp, &argc, sizeof(size_t));
  1290. argc++;
  1291. list_push(pair, argcp);
  1292. list_push(pair, r);
  1293. table_set(params, l, pair);
  1294. } while (MATCH(COMMA));
  1295. }
  1296. EXPECT(RPAR, ")");
  1297. }
  1298. table_t *captured = NULL;
  1299. if (MATCH(USE)) {
  1300. EXPECT(LPAR, "(");
  1301. captured = table_new();
  1302. do {
  1303. if(!AT(NAME))
  1304. PARSE_ERROR("expected identifier");
  1305. token_t *name = tokens->data[(*pos)++];
  1306. table_set(captured, name->text, NODET(LITERAL, name));
  1307. } while (MATCH(COMMA));
  1308. EXPECT(RPAR, ")");
  1309. }
  1310. int colon = AT(COLON);
  1311. node_t *body = !colon && !AT(LCB)? parse_stmt(tokens, pos): BLOCK();
  1312. if (colon && body->tag == N_EXPRSTMT)
  1313. body = NODE1(RETURN, body->a);
  1314. if (is_expr)
  1315. return NODEF(FUNCEXPR, NULL, params, captured, body);
  1316. return NODEF(FUNCDEF, name, params, captured, body);
  1317. }
  1318. node_t *parse_stmt(list_t *tokens, size_t *pos) {
  1319. if (MATCH(LCB)) {
  1320. list_t *stmts = list_new();
  1321. while (!AT(EOF) && !AT(RCB)) {
  1322. node_t *n = parse_stmt(tokens, pos);
  1323. MATCH(SEMI);
  1324. list_push(stmts, n);
  1325. }
  1326. EXPECT(RCB, "}");
  1327. return NODEL(BLOCK, stmts);
  1328. } else if (MATCH(VAR)) {
  1329. if (AT(LSB))
  1330. return parse_unpack(tokens, pos, N_VARUNPACK);
  1331. return parse_var(tokens, pos, 0);
  1332. } else if (MATCH(LET)) {
  1333. if (AT(LSB))
  1334. return parse_unpack(tokens, pos, N_LETUNPACK);
  1335. return parse_var(tokens, pos, 1);
  1336. } else if (MATCH(CONST)) {
  1337. table_t *h = table_new();
  1338. do {
  1339. if(!AT(NAME))
  1340. PARSE_ERROR("expected identifier");
  1341. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1342. if (!(k[0] >= 'A' && k[0] <= 'Z'))
  1343. PARSE_ERROR("compile-time constant identifiers must begin with an uppercase letter, but '%s' does not", k);
  1344. if (table_get(h, k))
  1345. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  1346. EXPECT(ASSIGN, "=");
  1347. node_t *v = parse_expr(tokens, pos);
  1348. table_set(h, k, v);
  1349. } while (MATCH(COMMA));
  1350. return NODEH(CONST, h);
  1351. } else if (MATCH(IF))
  1352. return parse_if(tokens, pos);
  1353. else if (MATCH(SWITCH)) {
  1354. token_t *label = NULL;
  1355. if (MATCH(AT)) {
  1356. if(!AT(NAME))
  1357. PARSE_ERROR("expected identifier");
  1358. label = tokens->data[(*pos)++];
  1359. }
  1360. node_t *a = parse_expr(tokens, pos);
  1361. EXPECT(LCB, "{");
  1362. list_t *cases = list_new();
  1363. for (;;) {
  1364. if (AT(RCB) || AT(DEFAULT)) break;
  1365. EXPECT(CASE, "case");
  1366. node_t *expr = parse_expr(tokens, pos);
  1367. MATCH(COLON);
  1368. list_t *stmts = list_new();
  1369. while (!AT(CASE) && !AT(DEFAULT) && !AT(RCB))
  1370. list_push(stmts, parse_stmt(tokens, pos));
  1371. list_t *pair = list_new();
  1372. list_push(pair, expr);
  1373. list_push(pair, NODEL(PROGRAM, stmts));
  1374. list_push(cases, pair);
  1375. }
  1376. node_t *b = NULL;
  1377. if (MATCH(DEFAULT)) {
  1378. MATCH(COLON);
  1379. list_t *stmts = list_new();
  1380. while (!AT(RCB))
  1381. list_push(stmts, parse_stmt(tokens, pos));
  1382. b = NODEL(PROGRAM, stmts);
  1383. }
  1384. EXPECT(RCB, "}");
  1385. if (!cases->length && !b)
  1386. PARSE_ERROR("empty switch statement");
  1387. LABELLOOP(NODE2l(SWITCH, a, b, cases));
  1388. return ln;
  1389. } else if (MATCH(FOR)) {
  1390. token_t *label = NULL;
  1391. if (MATCH(AT)) {
  1392. if(!AT(NAME))
  1393. PARSE_ERROR("expected identifier");
  1394. label = tokens->data[(*pos)++];
  1395. }
  1396. node_t *a = NULL;
  1397. node_t *b = NULL;
  1398. node_t *c = NULL;
  1399. if (!AT(LCB) && !AT(COLON) && !CLIFF) {
  1400. if (MATCH(LSB)) {
  1401. list_t *l = list_new();
  1402. do {
  1403. if(!AT(NAME))
  1404. PARSE_ERROR("expected identifier");
  1405. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1406. } while (MATCH(COMMA));
  1407. EXPECT(RSB, "]");
  1408. EXPECT(OF, "of");
  1409. a = parse_expr(tokens, pos);
  1410. b = BLOCK();
  1411. LABELLOOP(NODE2l(FOROFUNPACK, a, b, l));
  1412. return ln;
  1413. }
  1414. if (AT(NAME) && ATP(OF, 1)) {
  1415. token_t *t = tokens->data[(*pos)++];
  1416. EXPECT(OF, "of");
  1417. a = parse_expr(tokens, pos);
  1418. b = BLOCK();
  1419. LABELLOOP(NODE2t(FOROF, a, b, t));
  1420. return ln;
  1421. }
  1422. if (MATCH(VAR)) {
  1423. if (MATCH(LSB)) {
  1424. list_t *l = list_new();
  1425. do {
  1426. if(!AT(NAME))
  1427. PARSE_ERROR("expected identifier");
  1428. list_push(l, ((token_t *)tokens->data[(*pos)++])->text);
  1429. } while (MATCH(COMMA));
  1430. EXPECT(RCB, "]");
  1431. EXPECT(OF, "of");
  1432. a = parse_expr(tokens, pos);
  1433. b = BLOCK();
  1434. LABELLOOP(NODE2l(FOROFVARUNPACK, a, b, l));
  1435. return ln;
  1436. }
  1437. if (AT(NAME) && ATP(OF, 1)) {
  1438. token_t *t = tokens->data[(*pos)++];
  1439. EXPECT(OF, "of");
  1440. a = parse_expr(tokens, pos);
  1441. b = BLOCK();
  1442. LABELLOOP(NODE2t(FOROFVAR, a, b, t));
  1443. return ln;
  1444. }
  1445. a = parse_var(tokens, pos, 0);
  1446. EXPECT(SEMI, ";");
  1447. b = parse_expr(tokens, pos);
  1448. EXPECT(SEMI, ";");
  1449. c = parse_expr(tokens, pos);
  1450. } else a = parse_expr(tokens, pos);
  1451. }
  1452. node_t *d = BLOCK();
  1453. LABELLOOP(NODE4(FOR, a, b, c, d));
  1454. return ln;
  1455. } else if (MATCH(BREAK)) {
  1456. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1457. return NODET(BREAK, tokens->data[(*pos)++]);
  1458. return NODE0(BREAK);
  1459. } else if (MATCH(CONTINUE)) {
  1460. if ((AT(NUMBER) || AT(NAME)) && !CLIFF)
  1461. return NODET(CONTINUE, tokens->data[(*pos)++]);
  1462. return NODE0(CONTINUE);
  1463. } else if (MATCH(FUNC))
  1464. return parse_func(tokens, pos, 0);
  1465. else if (MATCH(RETURN)) {
  1466. node_t *a = NULL;
  1467. if (!AT(RCB) && !AT(EOF) && !CLIFF)
  1468. a = parse_expr(tokens, pos);
  1469. return NODE1(RETURN, a);
  1470. } else if (MATCH(DEFER)) {
  1471. node_t *a;
  1472. if (AT(LCB))
  1473. a = BLOCK();
  1474. else a = parse_stmt(tokens, pos);
  1475. return NODE1(DEFER, a);
  1476. } else if (MATCH(PASS)) return NODE0(PASS);
  1477. else if (MATCH(TRY)) {
  1478. node_t *a = BLOCK();
  1479. token_t *t = NULL;
  1480. EXPECT(CATCH, "catch");
  1481. if (!AT(COLON) && !AT(LCB) && !CLIFF) {
  1482. if (!AT(NAME))
  1483. PARSE_ERROR("expected identifier");
  1484. t = tokens->data[(*pos)++];
  1485. }
  1486. node_t *b = BLOCK();
  1487. return NODE2t(TRY, a, b, t);
  1488. } else if (MATCH(THROW)) {
  1489. node_t *a = NULL;
  1490. if (!CLIFF && !AT(COMMA) && !AT(RPAR) && !AT(RCB))
  1491. a = parse_expr(tokens, pos);
  1492. return NODE1(THROW, a);
  1493. } else if (MATCH(GOTO)) {
  1494. if(!AT(NAME))
  1495. PARSE_ERROR("expected identifier");
  1496. token_t *t = tokens->data[(*pos)++];
  1497. return NODET(GOTO, t);
  1498. } else if (AT(NAME) && ATP(COLON, 1) && !CLIFF_AHEAD) {
  1499. token_t *t = tokens->data[(*pos)++];
  1500. EXPECT(COLON, ":");
  1501. return NODET(LABEL, t);
  1502. } else if (MATCH(CLASS)) {
  1503. if(!AT(NAME))
  1504. PARSE_ERROR("expected identifier");
  1505. token_t *t = tokens->data[(*pos)++];
  1506. list_t *l = NULL;
  1507. if (MATCH(LPAR)) {
  1508. l = list_new();
  1509. do {
  1510. if(!AT(NAME))
  1511. PARSE_ERROR("expected identifier");
  1512. token_t *t = tokens->data[(*pos)++];
  1513. list_push(l, t);
  1514. } while (MATCH(COMMA));
  1515. EXPECT(RPAR, ")");
  1516. }
  1517. EXPECT(LCB, "{");
  1518. list_t *triples = list_new();
  1519. for (;;) {
  1520. if (!AT(NAME))
  1521. break;
  1522. list_t *triple = list_new();
  1523. token_t *t = tokens->data[(*pos)++];
  1524. list_push(triple, t);
  1525. if (MATCH(ASSIGN)) {
  1526. list_push(triple, t);
  1527. list_push(triple, parse_expr(tokens, pos));
  1528. } else {
  1529. list_push(triple, NULL);
  1530. list_push(triple, parse_func(tokens, pos, 1));
  1531. }
  1532. list_push(triples, triple);
  1533. }
  1534. EXPECT(RCB, "}");
  1535. list_t *pair = list_new();
  1536. list_push(pair, l);
  1537. list_push(pair, triples);
  1538. return NODETL(CLASS, t, pair);
  1539. } else if (MATCH(INLINE)) {
  1540. if (!AT(STRING))
  1541. PARSE_ERROR("expected string");
  1542. token_t *t = tokens->data[(*pos)++];
  1543. return NODET(INLINE, t);
  1544. }
  1545. node_t *n = parse_expr(tokens, pos);
  1546. return NODE1(EXPRSTMT, n);
  1547. }
  1548. node_t *parse_program(list_t *tokens, size_t *pos) {
  1549. if (AT(EOF))
  1550. PARSE_ERROR("empty program");
  1551. list_t *stmts = list_new();
  1552. int flag = 0;
  1553. while (!AT(EOF) && *pos < tokens->length) {
  1554. node_t *n;
  1555. if (MATCH(REQUIRE)) {
  1556. if (flag)
  1557. PARSE_ERROR("misplaced require statement")
  1558. if (!AT(STRING))
  1559. PARSE_ERROR("expected string");
  1560. token_t *path = tokens->data[(*pos)++];
  1561. n = NODET(REQUIRE, path);
  1562. } else if (MATCH(HEADER)) {
  1563. if (flag)
  1564. PARSE_ERROR("misplaced header statement")
  1565. if (!AT(STRING))
  1566. PARSE_ERROR("expected string");
  1567. token_t *text = tokens->data[(*pos)++];
  1568. n = NODET(HEADER, text);
  1569. } else if (MATCH(INCLUDE)) {
  1570. if (flag)
  1571. PARSE_ERROR("misplaced include statement")
  1572. if (!AT(STRING))
  1573. PARSE_ERROR("expected string");
  1574. token_t *text = tokens->data[(*pos)++];
  1575. n = NODET(INCLUDE, text);
  1576. } else { n = parse_stmt(tokens, pos); flag = 1; }
  1577. MATCH(SEMI);
  1578. list_push(stmts, n);
  1579. }
  1580. return NODEL(TOPLEVEL, stmts);
  1581. }
  1582. node_t *parse(char *source) {
  1583. size_t pos = 0;
  1584. return parse_program(tokenize(source), &pos);
  1585. }
  1586. #define NEWGID() size_t gid = GID++
  1587. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  1588. #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(")"); }
  1589. #define UNOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a); EMIT(")"); }
  1590. #define ASSIGNIN(buf, lhs, rhs) {\
  1591. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) {\
  1592. buffer_fmt(buf, "qi_set(state, false, \"%s\", ", (lhs)->t->text);\
  1593. rhs;\
  1594. buffer_fmt(buf, ")");\
  1595. } else if ((lhs)->tag == N_INDEX) {\
  1596. buffer_fmt(buf, "qi_index_set(state, false, ");\
  1597. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a);\
  1598. buffer_fmt(buf, ", ");\
  1599. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->b);\
  1600. buffer_fmt(buf, ", ");\
  1601. rhs;\
  1602. buffer_fmt(buf, ")");\
  1603. } else if ((lhs)->tag == N_MEMBER) {\
  1604. buffer_fmt(buf, "qi_index_set(state, false, ");\
  1605. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs)->a);\
  1606. buffer_fmt(buf, ", qi_make_string(state, \"%s\"), ", (lhs)->t->text);\
  1607. rhs;\
  1608. buffer_fmt(buf, ")");\
  1609. } else COMPILE_ERROR("illegal assignment left-hand side");\
  1610. }
  1611. #define ASSIGN(lhs, rhs) ASSIGNIN(buf, lhs, rhs)
  1612. #define COMPASSIGN(lhs, s, rhs) {\
  1613. ASSIGN(node->a, {\
  1614. EMIT("qi_%s(state, ", s);\
  1615. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, (lhs));\
  1616. EMIT(", ");\
  1617. rhs;\
  1618. EMIT(")");\
  1619. });\
  1620. }
  1621. #define COMPILE_ERROR(fmt, ...) { format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, ##__VA_ARGS__); exit(1); }
  1622. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, node_t *node);
  1623. char *tempvar() {
  1624. NEWGID();
  1625. char *s = malloc(sizeof(char) * 64);
  1626. snprintf(s, 64, "__temp%zu", gid);
  1627. return s;
  1628. }
  1629. void compile_list(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, list_t *seq) {
  1630. if (!seq || seq->length < 1) {
  1631. EMIT("NULL");
  1632. return;
  1633. }
  1634. int has_star = 0;
  1635. for (size_t i = 0; i < seq->length; i++)
  1636. if (((node_t *)seq->data[i])->tag == N_STAR) {
  1637. has_star = 1; break;
  1638. }
  1639. buffer_t *tbuf = buffer_new();
  1640. NEWGID();
  1641. buffer_fmt(tbuf, "inline static qi_list_t *__list%d(qi_state_t *state) {\n", gid);
  1642. if (has_star)
  1643. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  1644. else
  1645. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make_n(%d);\n", seq->length);
  1646. for (size_t i = 0; i < seq->length; i++) {
  1647. node_t *node = seq->data[i];
  1648. if (!has_star) {
  1649. buffer_fmt(tbuf, "qi_list_data(list, %d) = ", i);
  1650. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  1651. buffer_fmt(tbuf, ";\n");
  1652. continue;
  1653. }
  1654. if (node->tag == N_STAR) {
  1655. char *varname = tempvar();
  1656. buffer_fmt(tbuf, "qi_value_t *%s = qi_iter(state, ", varname);
  1657. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  1658. buffer_fmt(tbuf, ");\n");
  1659. buffer_fmt(tbuf, "for (qi_size_t i = 0; i < %s->value.list->length; i++)\n", varname);
  1660. buffer_fmt(tbuf, "qi_list_push(list, qi_index(state, %s, qi_make_number(state, i)));\n", varname);
  1661. } else {
  1662. buffer_fmt(tbuf, "qi_list_push(list, ");
  1663. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node);
  1664. buffer_fmt(tbuf, ");\n");
  1665. }
  1666. }
  1667. buffer_fmt(tbuf, "return list;\n");
  1668. buffer_fmt(tbuf, "}\n");
  1669. buffer_appendb(gbuf, tbuf);
  1670. EMIT("__list%d(state)", gid);
  1671. }
  1672. void compile_table(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, table_t *table) {
  1673. if (!table || table->used < 1) {
  1674. EMIT("NULL");
  1675. return;
  1676. }
  1677. buffer_t *tbuf = buffer_new();
  1678. NEWGID();
  1679. buffer_fmt(tbuf, "inline static qi_table_t *__table%d(qi_state_t *state) {\n", gid);
  1680. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  1681. table_iterate(table, {
  1682. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  1683. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, entry.value);
  1684. buffer_fmt(tbuf, ");\n");
  1685. });
  1686. buffer_fmt(tbuf, "return table;\n");
  1687. buffer_fmt(tbuf, "}\n");
  1688. buffer_appendb(gbuf, tbuf);
  1689. EMIT("__table%d(state)", gid);
  1690. }
  1691. #define CTXPUSH(s) list_push(ctx, (s))
  1692. #define CTXPOP() list_pop(ctx)
  1693. int in_context(list_t *ctx, char *s) {
  1694. if (!ctx->length)
  1695. return 0;
  1696. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1697. if (strcmp(ctx->data[i], "gap") == 0)
  1698. break;
  1699. else if (strcmp(ctx->data[i], s) == 0)
  1700. return 1;
  1701. }
  1702. return 0;
  1703. }
  1704. int in_switch(list_t *ctx) {
  1705. if (!ctx->length)
  1706. return 0;
  1707. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1708. if (strcmp(ctx->data[i], "gap") == 0 || strcmp(ctx->data[i], "for") == 0)
  1709. break;
  1710. else if (strcmp(ctx->data[i], "switch") == 0)
  1711. return 1;
  1712. }
  1713. return 0;
  1714. }
  1715. size_t count_ctxs(list_t *ctx, char *s) {
  1716. if (!ctx->length)
  1717. return 0;
  1718. size_t k = 0;
  1719. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1720. if (strcmp(ctx->data[i], "gap") == 0)
  1721. break;
  1722. else if (strcmp(ctx->data[i], s) == 0)
  1723. k++;
  1724. }
  1725. return k;
  1726. }
  1727. #define INCTX(s) (in_context(ctx, (s)))
  1728. #define SCOPESK (count_ctxs(ctx, "scope"))
  1729. #define TRAPSK (count_ctxs(ctx, "trap"))
  1730. #define LPUSH(i) stack_push(lstk, (i))
  1731. #define LPOP() stack_pop(lstk)
  1732. #define LID (lstk->data[lstk->length-1])
  1733. #define SPUSH(i) stack_push(sstk, (i))
  1734. #define SPOP() stack_pop(sstk)
  1735. #define SID (sstk->data[sstk->length-1])
  1736. #define LBPUSH() list_push(lbl, table_new())
  1737. #define LBPOP() list_pop(lbl)
  1738. void compile_func(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, node_t *node, char *name) {
  1739. NEWGID();
  1740. buffer_t *tbuf = buffer_new();
  1741. buffer_fmt(tbuf, "qi_value_t *__func%d(qi_state_t *state, qi_size_t pargc, qi_list_t *pargs) {\n", gid);
  1742. LBPUSH();
  1743. CTXPUSH("gap");
  1744. CTXPUSH("func");
  1745. size_t optargc = 0;
  1746. if (node->h) {
  1747. table_iterate(node->h, {
  1748. list_t *pair = entry.value;
  1749. size_t argc = *(size_t *)pair->data[0];
  1750. if (pair->data[1]) {
  1751. optargc++;
  1752. buffer_fmt(tbuf, "qi_decl(state, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ", entry.key, argc+1, argc);
  1753. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, pair->data[1]);
  1754. buffer_fmt(tbuf, ");\n");
  1755. } else
  1756. buffer_fmt(tbuf, "qi_decl(state, \"%s\", qi_list_index(pargs, %d));\n", entry.key, argc);
  1757. argc++;
  1758. });
  1759. }
  1760. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  1761. CTXPOP();
  1762. CTXPOP();
  1763. LBPOP();
  1764. buffer_fmt(tbuf, "return state->nil;\n");
  1765. buffer_fmt(tbuf, "}\n");
  1766. buffer_appendb(gbuf, tbuf);
  1767. tbuf = buffer_new();
  1768. buffer_fmt(tbuf, "qi_make_function(state, \"%s\", %d, __func%d, ", name? name: node->t? node->t->text: "<anon>", !node->h? 0: (node->h->used - optargc), gid);
  1769. compile_table(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->h2);
  1770. buffer_fmt(tbuf, ")");
  1771. if (node->tag == N_FUNCEXPR) {
  1772. buffer_appendb(buf, tbuf);
  1773. return;
  1774. }
  1775. EMIT("qi_set(state, false, \"%s\", ", node->t->text);
  1776. buffer_appendb(buf, tbuf);
  1777. EMIT(");");
  1778. }
  1779. table_t *CONSTANTS;
  1780. void compile_block(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, list_t *block, int toplevel) {
  1781. for (size_t i = 0; i < block->length; i++) {
  1782. node_t *node = block->data[i];
  1783. if (node->tag == N_CONST) {
  1784. if (!toplevel)
  1785. COMPILE_ERROR("const is not on top-level")
  1786. table_iterate(node->h, {
  1787. char *name = entry.key;
  1788. if (table_get(CONSTANTS, name))
  1789. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  1790. table_set(CONSTANTS, name, entry.value);
  1791. });
  1792. } else if (node->tag == N_FUNCDEF) {
  1793. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  1794. EMIT("\n");
  1795. } else if (node->tag == N_CLASS) {
  1796. NEWGID();
  1797. char *name = node->t->text;
  1798. list_t *supers = list_index(node->l, 0);
  1799. list_t *triples = list_index(node->l, 1);
  1800. buffer_t *tbuf = buffer_new();
  1801. buffer_fmt(tbuf, "qi_value_t *__class%d(qi_state_t *state) {\n", gid);
  1802. buffer_fmt(tbuf, "qi_list_t *supers = qi_list_make_n(%d);\n", !supers? 0: supers->length);
  1803. if (supers)
  1804. for (size_t i = 0; i < supers->length; i++) {
  1805. token_t *t = supers->data[i];
  1806. buffer_fmt(tbuf, "qi_list_data(supers, %d) = qi_get(state, \"%s\");\n", i, t->text);
  1807. }
  1808. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  1809. buffer_fmt(tbuf, "qi_table_t *metatable = qi_table_make();\n");
  1810. for (size_t i = 0; i < triples->length; i++) {
  1811. list_t *triple = triples->data[i];
  1812. token_t *t = triple->data[0];
  1813. buffer_t *methodname = buffer_new();
  1814. buffer_fmt(methodname, "%s.%s", name, t->text);
  1815. buffer_fmt(tbuf, "qi_table_set(%s, \"%s\", ", triple->data[1] != NULL? "table": "metatable", t->text);
  1816. if (triple->data[1] == NULL)
  1817. compile_func(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2], buffer_read(methodname));
  1818. else
  1819. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, triple->data[2]);
  1820. buffer_fmt(tbuf, ");\n");
  1821. }
  1822. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(4);\n");
  1823. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = qi_make_string(state, \"%s\");\n", name);
  1824. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = qi_make_list(state, supers);\n");
  1825. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = qi_make_table(state, table);\n");
  1826. buffer_fmt(tbuf, "qi_list_data(pargs, 3) = qi_make_table(state, metatable);\n");
  1827. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, \"__class_wrapper\"), pargs);\n");
  1828. buffer_fmt(tbuf, "}\n");
  1829. buffer_appendb(gbuf, tbuf);
  1830. EMIT("qi_set(state, false, \"%s\", __class%d(state));", name, gid);
  1831. } else if (node->tag == N_LABEL) {
  1832. char *label = node->t->text;
  1833. if (table_get(list_index(lbl, -1), label))
  1834. COMPILE_ERROR("duplicated label: '%s'", label);
  1835. NEWGID();
  1836. size_t *n = malloc(sizeof(size_t));
  1837. memcpy(n, &gid, sizeof(size_t));
  1838. table_set(list_index(lbl, -1), label, n);
  1839. }
  1840. }
  1841. for (size_t i = 0; i < block->length; i++) {
  1842. node_t *n = block->data[i];
  1843. if (n->tag == N_FUNCDEF)
  1844. continue;
  1845. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  1846. EMIT("\n");
  1847. }
  1848. }
  1849. const char *STD[][2] = {
  1850. {"std",
  1851. "func exit(c) {\n"
  1852. " if type(c) != \"number\"\n"
  1853. " throw \"expected first argument to be: number, but got: \" + type(c)\n"
  1854. " inline `qi_exit(state, qi_get(state, \"c\")->value.number)`\n"
  1855. "}\n"
  1856. "func head(l): return l[0]\n"
  1857. "func tail(l): return slice(l, 1)\n"
  1858. "func die(msg, c=1) {\n"
  1859. " fputs(STDERR, str(msg) + \"\\n\")\n"
  1860. " exit(c)\n"
  1861. "}\n"
  1862. "func min(x, y): x < y? x: y\n"
  1863. "func max(x, y): x > y? x: y\n"
  1864. "func reverse(x) {\n"
  1865. " if type(x) !in (\"list\", \"string\", \"bytes\")\n"
  1866. " throw \"expected first argument to be: list, string or bytes, but got: \" + type(x)\n"
  1867. " var r = []\n"
  1868. " for var i = len(x)-1; i >= 0; i--\n"
  1869. " list_push(r, x[i])\n"
  1870. " if type(x) == \"string\"\n"
  1871. " return list_join(r)\n"
  1872. " elif type(x) == \"bytes\"\n"
  1873. " return bytes(r)\n"
  1874. " return r\n"
  1875. "}\n"
  1876. "set_pseudomethod(\"list.reverse\", reverse)\n"
  1877. "set_pseudomethod(\"string.reverse\", reverse)\n"
  1878. "set_pseudomethod(\"bytes.reverse\", reverse)\n"
  1879. "func range(f) {\n"
  1880. " var t, s\n"
  1881. " if len(arguments) >= 3 {\n"
  1882. " t = arguments[1]\n"
  1883. " s = arguments[2]\n"
  1884. " } elif len(arguments) >= 2 {\n"
  1885. " t = arguments[1]\n"
  1886. " s = 1\n"
  1887. " } else {\n"
  1888. " t = f\n"
  1889. " f = 0\n"
  1890. " s = 1\n"
  1891. " }\n"
  1892. " if type(f) != \"number\"\n"
  1893. " throw \"expected first argument to be: number, but got: \" + type(f)\n"
  1894. " if type(t) != \"number\"\n"
  1895. " throw \"expected second argument to be: number, but got: \" + type(t)\n"
  1896. " if type(s) != \"number\"\n"
  1897. " throw \"expected third argument to be: number, but got: \" + type(s)\n"
  1898. " if f > t\n"
  1899. " return reverse(range(t, f, s))\n"
  1900. " var r = []\n"
  1901. " for var i = f; i < t; i += s\n"
  1902. " list_push(r, i)\n"
  1903. " return r\n"
  1904. "}\n"
  1905. "const SEEK_SET = 0, SEEK_CUR = 1, SEEK_END = 2\n"
  1906. "func frewind(file)\n"
  1907. " return file.rewind()\n"
  1908. "func file_read(filename) {\n"
  1909. " let file = fopen(filename, \"r\")\n"
  1910. " defer fclose(file)\n"
  1911. " return str(fread(file, -1))\n"
  1912. "}\n"
  1913. "func file_write(filename, data) {\n"
  1914. " let file = fopen(filename, \"w\")\n"
  1915. " defer fclose(file)\n"
  1916. " fwrite(file, bytes(data))\n"
  1917. "}\n"
  1918. "func is_defined(name) {\n"
  1919. " if type(name) != \"string\"\n"
  1920. " throw \"expected first argument to be: string, but got: \" + type(name)\n"
  1921. " inline `bool b = qi_find(state, qi_get(state, \"name\")->value.string) != NULL`\n"
  1922. " inline `return qi_make_boolean(state, b)`\n"
  1923. "}\n"
  1924. "func list_remove(l, x, first=false) {\n"
  1925. " if type(l) != \"list\"\n"
  1926. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1927. " repeat:\n"
  1928. " for var i = 0; i < len(l); i++\n"
  1929. " if l[i] == x {\n"
  1930. " list_delete(l, i)\n"
  1931. " if first\n"
  1932. " break\n"
  1933. " goto repeat\n"
  1934. " }\n"
  1935. "}\n"
  1936. "set_pseudomethod(\"list.remove\", list_remove)\n"
  1937. "func list_join(l) {\n"
  1938. " if type(l) != \"list\"\n"
  1939. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1940. " var r = \"\"\n"
  1941. " var s\n"
  1942. " if len(arguments) == 1\n"
  1943. " s = \"\"\n"
  1944. " else\n"
  1945. " s = arguments[1]\n"
  1946. " if type(s) != \"string\"\n"
  1947. " throw \"expected second argument to be: string, but got: \" + type(s)\n"
  1948. " var first = true\n"
  1949. " for var x of l {\n"
  1950. " if type(x) != \"string\"\n"
  1951. " throw \"expected sequence item to be: string, but got: \" + type(x)\n"
  1952. " if s != \"\" && !first\n"
  1953. " r += s\n"
  1954. " r += x\n"
  1955. " first = false\n"
  1956. " }\n"
  1957. " return r\n"
  1958. "}\n"
  1959. "set_pseudomethod(\"list.join\", list_join)\n"
  1960. "func list_pop_at(l, i) {\n"
  1961. " if type(l) != \"list\"\n"
  1962. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1963. " if type(i) != \"number\"\n"
  1964. " throw \"expected second argument to be: number, but got: \" + type(i)\n"
  1965. " var x = l[i]\n"
  1966. " list_delete(l, i)\n"
  1967. " return x\n"
  1968. "}\n"
  1969. "set_pseudomethod(\"list.popAt\", list_pop_at)\n"
  1970. "func list_sort(l, cmp=func (x, y): x > y) {\n"
  1971. " if type(l) != \"list\"\n"
  1972. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1973. " if type(cmp) != \"function\"\n"
  1974. " throw \"expected second argument to be: function, but got: \" + type(cmp)\n"
  1975. " if len(l) == 0\n"
  1976. " return l\n"
  1977. " var z = len(l)\n"
  1978. " for var i = 0; i < z - 1; i++\n"
  1979. " for var j = 0; j < z - 1 - i; j++\n"
  1980. " if cmp(l[j], l[j+1]) {\n"
  1981. " let tmp = l[j]\n"
  1982. " l[j] = l[j+1]\n"
  1983. " l[j+1] = tmp\n"
  1984. " }\n"
  1985. " return l\n"
  1986. "}\n"
  1987. "func list_sorted(l, cmp=func (x, y): x > y) {\n"
  1988. " l = list_copy(l)\n"
  1989. " return list_sort(l, cmp)\n"
  1990. "}\n"
  1991. "set_pseudomethod(\"list.sort\", list_sort)\n"
  1992. "set_pseudomethod(\"list.sorted\", list_sorted)\n"
  1993. "func list_shift(l) {\n"
  1994. " if type(l) != \"list\"\n"
  1995. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1996. " if is_empty(l)\n"
  1997. " throw \"shift from empty list\"\n"
  1998. " var a = l[0]\n"
  1999. " list_delete(l, 0)\n"
  2000. " return a\n"
  2001. "}\n"
  2002. "func list_unshift(l, x) {\n"
  2003. " list_insert(l, 0, x)\n"
  2004. "}\n"
  2005. "set_pseudomethod(\"list.shift\", list_shift)\n"
  2006. "set_pseudomethod(\"list.unshift\", list_unshift)\n"
  2007. "func slice(l) {\n"
  2008. " if type(l) !in (\"list\", \"string\", \"bytes\")\n"
  2009. " throw \"expected first argument to be: list, string or bytes, but got: \" + type(l)\n"
  2010. " var r = []\n"
  2011. " if len(arguments) == 2 {\n"
  2012. " var f = arguments[1]\n"
  2013. " if type(f) != \"number\"\n"
  2014. " throw \"expected second argument to be: number, but got: \" + type(f)\n"
  2015. " for var i = f; i < len(l); i++\n"
  2016. " list_push(r, l[i])\n"
  2017. " } elif len(arguments) == 3 {\n"
  2018. " var f = arguments[1], t = arguments[2]\n"
  2019. " if type(f) != \"number\"\n"
  2020. " throw \"expected second argument to be: number, but got: \" + type(f)\n"
  2021. " if type(t) != \"number\"\n"
  2022. " throw \"expected third argument to be: number, but got: \" + type(t)\n"
  2023. " for var i = f; i < len(l) && i <= t; i++\n"
  2024. " list_push(r, l[i])\n"
  2025. " }\n"
  2026. " if type(l) == \"string\"\n"
  2027. " return list_join(r)\n"
  2028. " elif type(l) == \"bytes\"\n"
  2029. " return bytes(r)\n"
  2030. " return r\n"
  2031. "}\n"
  2032. "set_pseudomethod(\"list.slice\", slice)\n"
  2033. "set_pseudomethod(\"string.slice\", slice)\n"
  2034. "set_pseudomethod(\"bytes.slice\", slice)\n"
  2035. "let __slice = slice;\n"
  2036. "func str_startswith(s, p) {\n"
  2037. " if type(s) != \"string\"\n"
  2038. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2039. " if len(s) < len(p)\n"
  2040. " return false\n"
  2041. " return slice(s, 0, len(p)-1) == p\n"
  2042. "}\n"
  2043. "set_pseudomethod(\"string.startsWith\", str_startswith)\n"
  2044. "func str_endswith(s, p) {\n"
  2045. " if type(s) != \"string\"\n"
  2046. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2047. " if len(s) < len(p)\n"
  2048. " return false\n"
  2049. " return slice(s, len(s) - len(p)) == p\n"
  2050. "}\n"
  2051. "set_pseudomethod(\"string.endsWith\", str_endswith)\n"
  2052. "func str_split(s) {\n"
  2053. " if len(arguments) == 1 || arguments[1] == \"\"\n"
  2054. " return list(s)\n"
  2055. " if type(s) != \"string\"\n"
  2056. " throw \"expected first argument to be:!string, but got: \" + type(s)\n"
  2057. " var r = []\n"
  2058. " var d = arguments[1]\n"
  2059. " if type(d) != \"string\"\n"
  2060. " throw \"expected second argument to be: string, but got: \" + type(s)\n"
  2061. " var t = \"\"\n"
  2062. " for var i = 0; i < len(s); i++ {\n"
  2063. " if slice(s, i, i+len(d)-1) == d {\n"
  2064. " list_push(r, t)\n"
  2065. " t = \"\"\n"
  2066. " i += len(d)-1\n"
  2067. " continue\n"
  2068. " }\n"
  2069. " t += s[i]\n"
  2070. " }\n"
  2071. " if t != \"\"\n"
  2072. " list_push(r, t)\n"
  2073. " return r\n"
  2074. "}\n"
  2075. "set_pseudomethod(\"string.split\", str_split)\n"
  2076. "func str_replace(s, w, b) {\n"
  2077. " if type(s) != \"string\"\n"
  2078. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2079. " if type(w) != \"string\"\n"
  2080. " throw \"expected second argument to be: string, but got: \" + type(w)\n"
  2081. " if type(b) != \"string\"\n"
  2082. " throw \"expected third argument to be: string, but got: \" + type(b)\n"
  2083. " var r = \"\"\n"
  2084. " for var i = 0; i < len(s); i++ {\n"
  2085. " if slice(s, i, i+len(w)-1) == w {\n"
  2086. " r += b\n"
  2087. " i += len(w)-1\n"
  2088. " continue\n"
  2089. " }\n"
  2090. " r += s[i]\n"
  2091. " }\n"
  2092. " return r\n"
  2093. "}\n"
  2094. "set_pseudomethod(\"string.replace\", str_replace)\n"
  2095. "func table_keys(t) {\n"
  2096. " if type(t) != \"table\"\n"
  2097. " throw \"expected first argument to be: table, but got: \" + type(t)\n"
  2098. " var r = []\n"
  2099. " for var k of t\n"
  2100. " list_push(r, k)\n"
  2101. " return r\n"
  2102. "}\n"
  2103. "set_pseudomethod(\"table.keys\", table_keys)\n"
  2104. "func table_values(t) {\n"
  2105. " if type(t) != \"table\"\n"
  2106. " throw \"expected first argument to be: table, but got: \" + type(t)\n"
  2107. " var r = []\n"
  2108. " for var k of t\n"
  2109. " list_push(r, t[k])\n" " return r\n"
  2110. "}\n"
  2111. "set_pseudomethod(\"table.values\", table_values)\n"
  2112. "func reduce(f, xs) {\n"
  2113. " if type(f) != \"function\"\n"
  2114. " throw \"expected first argument to be: function, but got: \" + type(f)\n"
  2115. " if type(xs) !in (\"list\", \"tuple\", \"string\", \"bytes\")\n"
  2116. " throw \"expected second argument to be: list, tuple, string or bytes, but got: \" + type(xs)\n"
  2117. " if len(xs) == 0\n"
  2118. " throw \"cannot reduce empty list\"\n"
  2119. " r = xs[0]\n"
  2120. " for var x of slice(xs, 1)\n"
  2121. " r = f(r, x)\n"
  2122. " if type(xs) == \"tuple\"\n"
  2123. " return tuple(r)\n"
  2124. " elif type(xs) == \"string\"\n"
  2125. " return list_join(r)\n"
  2126. " elif type(xs) == \"bytes\"\n"
  2127. " return bytes(r)\n"
  2128. " return r\n"
  2129. "}\n"
  2130. "set_pseudomethod(\"list.reduce\", func (xs, f): reduce(f, xs))\n"
  2131. "set_pseudomethod(\"tuple.reduce\", func (xs, f): reduce(f, xs))\n"
  2132. "set_pseudomethod(\"string.reduce\", func (xs, f): reduce(f, xs))\n"
  2133. "set_pseudomethod(\"bytes.reduce\", func (xs, f): reduce(f, xs))\n"
  2134. "func sum(xs)\n"
  2135. " return reduce(func (x, y): x + y, xs)\n"
  2136. "set_pseudomethod(\"list.sum\", sum)\n"
  2137. "set_pseudomethod(\"tuple.sum\", sum)\n"
  2138. "func product(xs)\n"
  2139. " return reduce(func (x, y): x * y, xs)\n"
  2140. "set_pseudomethod(\"list.product\", product)\n"
  2141. "set_pseudomethod(\"tuple.product\", product)\n"
  2142. "func map(f, xs) {\n"
  2143. " if type(f) != \"function\"\n"
  2144. " throw \"expected first argument to be: function, but got: \" + type(f)\n"
  2145. " if type(xs) !in (\"list\", \"tuple\", \"string\", \"bytes\")\n"
  2146. " throw \"expected second argument to be: list, tuple, string or bytes, but got: \" + type(xs)\n"
  2147. " if len(xs) == 0\n"
  2148. " return xs\n"
  2149. " var r = []\n"
  2150. " for var x of xs\n"
  2151. " list_push(r, f(x))\n"
  2152. " if type(xs) == \"tuple\"\n"
  2153. " return tuple(r)\n"
  2154. " elif type(xs) == \"string\"\n"
  2155. " return list_join(r)\n"
  2156. " elif type(xs) == \"bytes\"\n"
  2157. " return bytes(r)\n"
  2158. " return r\n"
  2159. "}\n"
  2160. "set_pseudomethod(\"list.map\", func (xs, f): map(f, xs))\n"
  2161. "set_pseudomethod(\"tuple.map\", func (xs, f): map(f, xs))\n"
  2162. "set_pseudomethod(\"string.map\", func (xs, f): map(f, xs))\n"
  2163. "set_pseudomethod(\"bytes.map\", func (xs, f): map(f, xs))\n"
  2164. "func filter(f, xs) {\n"
  2165. " if type(f) != \"function\"\n"
  2166. " throw \"expected first argument to be: function, but got: \" + type(f)\n"
  2167. " if type(xs) !in (\"list\", \"tuple\", \"string\", \"bytes\")\n"
  2168. " throw \"expected second argument to be: list, tuple, string or bytes, but got: \" + type(xs)\n"
  2169. " if len(xs) == 0\n"
  2170. " return xs\n"
  2171. " var r = []\n"
  2172. " for var x of xs\n"
  2173. " if f(x)\n"
  2174. " list_push(r, x)\n"
  2175. " if type(xs) == \"tuple\"\n"
  2176. " return tuple(r)\n"
  2177. " elif type(xs) == \"string\"\n"
  2178. " return list_join(r)\n"
  2179. " elif type(xs) == \"bytes\"\n"
  2180. " return bytes(r)\n"
  2181. " return r\n"
  2182. "}\n"
  2183. "set_pseudomethod(\"list.filter\", func (xs, f): filter(f, xs))\n"
  2184. "set_pseudomethod(\"tuple.filter\", func (xs, f): filter(f, xs))\n"
  2185. "set_pseudomethod(\"string.filter\", func (xs, f): filter(f, xs))\n"
  2186. "set_pseudomethod(\"bytes.filter\", func (xs, f): filter(f, xs))\n"
  2187. "func str_index(s, w) {\n"
  2188. " if s == \"\" || w == \"\"\n"
  2189. " return -1\n"
  2190. " if type(s) != \"string\"\n"
  2191. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2192. " if type(w) != \"string\"\n"
  2193. " throw \"expected second argument to be: string, but got: \" + type(w)\n"
  2194. " for var i = 0; i < len(s); i++\n"
  2195. " if len(w) == 1 && s[i] == w\n"
  2196. " return i\n"
  2197. " elif slice(s, i, i+len(w)-1) == w\n"
  2198. " return i\n"
  2199. " return -1\n"
  2200. "}\n"
  2201. "set_pseudomethod(\"string.index\", str_index)\n"
  2202. "func str_lstrip(s, cs=\" \\t\\n\\r\\x0b\\x0c\") {\n"
  2203. " if type(s) != \"string\"\n"
  2204. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2205. " if type(cs) != \"string\"\n"
  2206. " throw \"expected second argument to be: string, but got: \" + type(cs)\n"
  2207. " if s == \"\"\n"
  2208. " return s\n"
  2209. " for var i = 0; s[i] in cs && i < len(s); i++\n"
  2210. " pass\n"
  2211. " return slice(s, i)\n"
  2212. "}\n"
  2213. "set_pseudomethod(\"string.lstrip\", str_lstrip)\n"
  2214. "func str_rstrip(s, cs=\" \\t\\n\\r\\x0b\\x0c\") {\n"
  2215. " if type(s) != \"string\"\n"
  2216. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2217. " if type(cs) != \"string\"\n"
  2218. " throw \"expected second argument to be: string, but got: \" + type(cs)\n"
  2219. " if s == \"\"\n"
  2220. " return s\n"
  2221. " for var k = 0, i = len(s)-1; s[i] in cs && i >= 0; k++\n"
  2222. " i--\n"
  2223. " return slice(s, 0, len(s)-k-1)\n"
  2224. "}\n"
  2225. "set_pseudomethod(\"string.rstrip\", str_rstrip)\n"
  2226. "func str_strip(s, cs=\" \\t\\n\\r\\x0b\\x0c\") {\n"
  2227. " if type(s) != \"string\"\n"
  2228. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2229. " if type(cs) != \"string\"\n"
  2230. " throw \"expected second argument to be: string, but got: \" + type(cs)\n"
  2231. " return str_lstrip(str_rstrip(s, cs), cs)\n"
  2232. "}\n"
  2233. "set_pseudomethod(\"string.strip\", str_strip)\n"
  2234. "func table_get(t, k, d=nil) {\n"
  2235. " if type(t) != \"table\"\n"
  2236. " throw \"expected first argument to be: table, but got: \" + type(t)\n"
  2237. " if type(k) != \"string\"\n"
  2238. " throw \"expected second argument to be: string, but got: \" + type(k)\n"
  2239. " if k !in t\n"
  2240. " return d\n"
  2241. " return t[k]\n"
  2242. "}\n"
  2243. "set_pseudomethod(\"table.get\", table_get)\n"
  2244. "func zip() {\n"
  2245. " if !arguments\n"
  2246. " return []\n"
  2247. " var l = map(len, arguments)\n"
  2248. " l = reduce(min, l)\n"
  2249. " var r = []\n"
  2250. " for var i = 0; i < l; i++ {\n"
  2251. " var t = []\n"
  2252. " for var xs of arguments\n"
  2253. " list_push(t, xs[i])\n"
  2254. " list_push(r, t)\n"
  2255. " }\n"
  2256. " return r\n"
  2257. "}\n"
  2258. "func enumerate(l)\n"
  2259. " if type(l) == \"table\"\n"
  2260. " return zip(table_keys(l), table_values(l))\n"
  2261. " else\n"
  2262. " return zip(range(len(l)), l)\n"
  2263. "func str_toupper(s) {\n"
  2264. " if type(s) != \"string\"\n"
  2265. " throw \"expected first argument to be: string, but got: \" + type(c)\n"
  2266. " return map(func (c): c >= 'a' && c <= 'z'? chr(ord(c) - 32): c, s)\n"
  2267. "}\n"
  2268. "set_pseudomethod(\"string.toupper\", str_toupper)\n"
  2269. "func str_tolower(s) {\n"
  2270. " if type(s) != \"string\"\n"
  2271. " throw \"expected first argument to be: string, but got: \" + type(c)\n"
  2272. " return map(func (c): c >= 'A' && c <= 'Z'? chr(ord(c) + 32): c, s)\n"
  2273. "}\n"
  2274. "set_pseudomethod(\"string.tolower\", str_tolower)\n"
  2275. "func Object(t, p=nil): return p !is nil? set_meta_table(p, get_meta_table(p) + t): set_meta_table({}, t)\n"
  2276. "func is_object(o): return has_meta_table(o)\n"
  2277. "func __class_wrapper(n, p, t, mt): return Object({\n"
  2278. " t: t,\n"
  2279. " mt: mt,\n"
  2280. " super: [],\n"
  2281. " __type: func (this) use (n): return n,\n"
  2282. " __str: func (this) use (n): return \"<class \" + n + \">\",\n"
  2283. " __call: func (this, pargs) use (p) {\n"
  2284. " var t = {}\n"
  2285. " var mt = {}\n"
  2286. " for var other of p {\n"
  2287. " t += other.t\n"
  2288. " mt += other.mt\n"
  2289. " list_push(this.super, other)\n"
  2290. " }\n"
  2291. " if len(this.super) == 1\n"
  2292. " this.super = this.super[0]\n"
  2293. " t += this.t\n"
  2294. " mt += this.mt\n"
  2295. " t.super = this.super\n"
  2296. " obj = set_meta_table(t, mt)\n"
  2297. " if \"constructor\" in mt\n"
  2298. " func_call(mt.constructor, [obj] + pargs)\n"
  2299. " return obj\n"
  2300. " }\n"
  2301. "})\n"
  2302. "func format(s) {\n"
  2303. " if type(s) != \"string\"\n"
  2304. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2305. " var r = \"\"\n"
  2306. " var n = 1\n"
  2307. " for var i = 0; i < len(s); i++\n"
  2308. " switch s[i] {\n"
  2309. " case '_'\n"
  2310. " if i+1 < len(s) && s[i+1] == '_' {\n"
  2311. " r += '_'\n"
  2312. " i++\n"
  2313. " continue\n"
  2314. " }\n"
  2315. " r += repr(arguments[n++])\n"
  2316. " break\n"
  2317. " default\n"
  2318. " r += s[i]\n"
  2319. " }\n"
  2320. " return r\n"
  2321. "}\n"
  2322. "set_pseudomethod(\"string.format\", format)\n"
  2323. "func formatl(s, l) {\n"
  2324. " if type(s) != \"string\"\n"
  2325. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2326. " if type(l) != \"list\"\n"
  2327. " throw \"expected second argument to be: list, but got: \" + type(l)\n"
  2328. " return func_call(str_format, [s] + l)\n"
  2329. "}\n"
  2330. "set_pseudomethod(\"string.formatl\", formatl)\n"
  2331. "func formatd(s, t) {\n"
  2332. " if type(s) != \"string\"\n"
  2333. " throw \"expected first argument to be: string, but got: \" + type(s)\n"
  2334. " var r = \"\"\n"
  2335. " var n = 1\n"
  2336. " for var i = 0; i < len(s); i++\n"
  2337. " switch s[i] {\n"
  2338. " case '{'\n"
  2339. " if i+1 < len(s) && s[i+1] == '{' {\n"
  2340. " r += '{'\n"
  2341. " i++\n"
  2342. " continue\n"
  2343. " }\n"
  2344. " var k = ''\n"
  2345. " i++\n"
  2346. " for i < len(s) && s[i] != '}'\n"
  2347. " k += s[i++]\n"
  2348. " if i >= len(s) || s[i] != '}'\n"
  2349. " throw \"unmatched { in format specifier\"\n"
  2350. " if !k\n"
  2351. " throw \"empty format key\"\n"
  2352. " r += repr(t[k])\n"
  2353. " break\n"
  2354. " default\n"
  2355. " r += s[i]\n"
  2356. " }\n"
  2357. " return r\n"
  2358. "}\n"
  2359. "set_pseudomethod(\"string.formatd\", formatd)\n"
  2360. "func getch() return chr(fgetc(STDIN))\n"
  2361. "func putch(c) fputc(STDOUT, c)\n"
  2362. "func getline()\n"
  2363. " return fgets(STDIN, 256)\n"
  2364. "func input() {\n"
  2365. " if len(arguments) > 0\n"
  2366. " func_call(print, arguments)\n"
  2367. " return str_rstrip(getline(), \"\\n\\r\")\n"
  2368. "}\n"
  2369. "func open(path, mode=\"r\"): fopen(path, mode)\n"
  2370. "func assert(cond, msg=\"assertion failed\")\n"
  2371. " if !cond\n"
  2372. " throw msg\n"
  2373. },
  2374. {"utf8",
  2375. "func utf8_chrlen(s) {\n"
  2376. " s = bytes(s)\n"
  2377. " var z = len(s)\n"
  2378. " if z < 2\n"
  2379. " return z\n"
  2380. " var l = 1\n"
  2381. " for var i = 1; i < z && (s[i] & 0xc0) == 0x80; i++\n"
  2382. " l++\n"
  2383. " return l\n"
  2384. "}\n"
  2385. "func utf8_decode(s) {\n"
  2386. " s = bytes(s)\n"
  2387. " var l = utf8_chrlen(s)\n"
  2388. " if !l\n"
  2389. " throw \"malformed sequence\"\n"
  2390. " var c = (s[0] & ((1 << (8 - l)) - 1)) << (l - 1) * 6\n"
  2391. " for var i = 1; i < l; i++\n"
  2392. " c |= (s[i] & 0x3f) << (l - i - 1) * 6\n"
  2393. " return (c, l)\n"
  2394. "}\n"
  2395. "func utf8_encode(c) {\n"
  2396. " if c <= 0x7f\n"
  2397. " return bytes([c & 0xFF])\n"
  2398. " elif c >= 0x80 && c <= 0x7ff\n"
  2399. " return bytes([0xC0 | ((c >> 6) & 0x1f), 0x80 | (c & 0x3f)])\n"
  2400. " elif c >= 0x800 && c <= 0xfff\n"
  2401. " return bytes([0xe0 | ((c >> 12) & 0xf), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  2402. " elif c >= 0x10000 && c <= 0x10ffff\n"
  2403. " return bytes([0xf0 | ((c >> 18) & 0x7), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)])\n"
  2404. " throw \"malformed codepoint\"\n"
  2405. "}\n"
  2406. },
  2407. {"thread",
  2408. "include `pthread.h`\n"
  2409. "func thread_create(fn, args=[]) {\n"
  2410. " if type(fn) != \"function\"\n"
  2411. " throw \"expected first argument to be: function, but got: \" + type(fn)\n"
  2412. " if type(args) != \"list\"\n"
  2413. " throw \"expected second argument to be: list, but got: \" + type(args)\n"
  2414. " inline `qi_value_t *args = qi_get(state, \"args\")`\n"
  2415. " inline `qi_list_t *list`\n"
  2416. " inline `LOCKED(args, {list = qi_list_copy(args->value.list);})`\n"
  2417. " inline `void *td = qi_thread_create(state, qi_get(state, \"fn\"), list)`\n"
  2418. " inline `qi_decl(state, \"td\", qi_make_data(state, 'T', td))`\n"
  2419. " return Object({\n"
  2420. " __str: func (this): \"<Thread>\",\n"
  2421. " _td: td,\n"
  2422. " joined: false,\n"
  2423. " join: func (this) {\n"
  2424. " if this.joined\n"
  2425. " return\n"
  2426. " var td = this._td\n"
  2427. " inline `qi_value_t *ret = qi_thread_join(state, qi_get_data(state, 'T', qi_get(state, \"td\")))`\n"
  2428. " this.joined = true\n"
  2429. " inline `return ret`\n"
  2430. " }\n"
  2431. " })\n"
  2432. "}\n"
  2433. "func Thread(fn, args=[]): Object({\n"
  2434. " __str: func (this) use (fn, args): format(\"<Thread _ _>\", fn, args),\n"
  2435. " _thread: nil,\n"
  2436. " start: func (this) use (fn, args) {\n"
  2437. " if this._thread !is nil\n"
  2438. " return\n"
  2439. " this._thread = thread_create(fn, args)\n"
  2440. " return this\n"
  2441. " },\n"
  2442. " join: func (this) {\n"
  2443. " if this._thread !is nil\n"
  2444. " return this._thread.join()\n"
  2445. " },\n"
  2446. " is_joined: func (this): this._thread.joined\n"
  2447. "})\n"
  2448. "func Mutex() {\n"
  2449. " inline `void *mutex = qi_mutex_create()`\n"
  2450. " inline `if (!mutex) qi_throw_format(state, \"mutex init failed\")`\n"
  2451. " inline `qi_decl(state, \"mutex\", qi_make_data(state, 'M', mutex))`\n"
  2452. " return Object({\n"
  2453. " __fin: func (this) {\n"
  2454. " mutex = this._mutex\n"
  2455. " this._mutex = nil\n"
  2456. " inline `qi_mutex_destroy(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2457. " },\n"
  2458. " __str: func (this): \"<Mutex>\",\n"
  2459. " _mutex: mutex,\n"
  2460. " lock: func (this) {\n"
  2461. " var mutex = this._mutex\n"
  2462. " inline `qi_mutex_lock(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2463. " },\n"
  2464. " trylock: func (this) {\n"
  2465. " var mutex = this._mutex\n"
  2466. " inline `return qi_make_boolean(state, qi_mutex_trylock(qi_get_data(state, 'M', qi_get(state, \"mutex\"))))`\n"
  2467. " },\n"
  2468. " unlock: func (this) {\n"
  2469. " var mutex = this._mutex\n"
  2470. " inline `qi_mutex_unlock(qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2471. " }\n"
  2472. " })\n"
  2473. "}\n"
  2474. "func Cond() {\n"
  2475. " inline `void *cond = qi_cond_create()`\n"
  2476. " inline `if (!cond) qi_throw_format(state, \"cond init failed\")`\n"
  2477. " inline `qi_decl(state, \"cond\", qi_make_data(state, 'C', cond))`\n"
  2478. " return Object({\n"
  2479. " __fin: func (this) {\n"
  2480. " cond = this._cond\n"
  2481. " this._cond = nil\n"
  2482. " inline `qi_cond_destroy(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2483. " },\n"
  2484. " __str: func (this): \"<Cond>\",\n"
  2485. " _cond: cond,\n"
  2486. " wait: func (this, mutex) {\n"
  2487. " var cond = this._cond\n"
  2488. " mutex = mutex._mutex\n"
  2489. " inline `qi_cond_wait(qi_get_data(state, 'C', qi_get(state, \"cond\")), qi_get_data(state, 'M', qi_get(state, \"mutex\")))`\n"
  2490. " },\n"
  2491. " signal: func (this) {\n"
  2492. " var cond = this._cond\n"
  2493. " inline `qi_cond_signal(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2494. " },\n"
  2495. " broadcast: func (this) {\n"
  2496. " var cond = this._cond\n"
  2497. " inline `qi_cond_broadcast(qi_get_data(state, 'C', qi_get(state, \"cond\")))`\n"
  2498. " }\n"
  2499. " })\n"
  2500. "}\n"
  2501. "func thread_exit(ret=nil)\n"
  2502. " inline `qi_thread_exit(state, qi_get(state, \"ret\"))`\n"
  2503. "func is_main_thread()\n"
  2504. " inline `return qi_make_boolean(state, qi_thread_main())`\n"
  2505. },
  2506. {"str",
  2507. "let STR_LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2508. "let STR_ASCII_LC = \"abcdefghijklmnopqrstuvwxyz\"\n"
  2509. "let STR_ASCII_UC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  2510. "let STR_DIGITS = \"0123456789\"\n"
  2511. "func is_char(c): return type(c) == \"string\" && len(c) == 1\n"
  2512. },
  2513. {"time",
  2514. "include `time.h`\n"
  2515. "include `errno.h`\n"
  2516. "header `#ifdef _WIN32`\n"
  2517. "include `Windows.h`\n"
  2518. "header `#endif`\n"
  2519. "func time() {\n"
  2520. " inline `unsigned long long ts = time(NULL)`\n"
  2521. " inline `return qi_make_number(state, ts)`\n"
  2522. "}\n"
  2523. "func strftime(f, t=time()) {\n"
  2524. " if type(f) != \"string\"\n"
  2525. " throw \"expected first argument to be: string, but got: \" + type(f)\n"
  2526. " if type(t) != \"number\"\n"
  2527. " throw \"expected second argument to be: number, but got: \" + type(t)\n"
  2528. " inline `time_t ts = qi_get(state, \"t\")->value.number`\n"
  2529. " inline `struct tm lt`\n"
  2530. " inline `lt = *localtime(&ts)`\n"
  2531. " inline `char buffer[512]`\n"
  2532. " inline `strftime(buffer, sizeof(buffer), qi_get(state, \"f\")->value.string, &lt)`\n"
  2533. " inline `return qi_make_string_copy(state, buffer)`\n"
  2534. "}\n"
  2535. "func usleep(t) {\n"
  2536. " if type(t) != \"number\"\n"
  2537. " throw \"expected first argument to be: number, but got: \" + type(t)\n"
  2538. " \n"
  2539. " inline `#ifdef _WIN32`\n"
  2540. " inline `Sleep((unsigned long)(qi_get(state, \"t\")->value.number))`\n"
  2541. " inline `#else`\n"
  2542. " inline `unsigned long ms = (unsigned long)(qi_get(state, \"t\")->value.number)`\n"
  2543. " inline `struct timespec ts`\n"
  2544. " inline `ts.tv_sec = ms / 1000`\n"
  2545. " inline `ts.tv_nsec = (ms % 1000) * 1000000`\n"
  2546. " inline `struct timespec r`\n"
  2547. " inline `while (nanosleep(&ts, &r) < 0) if (errno == EINTR) ts = r; else break`\n"
  2548. " inline `#endif`\n"
  2549. "}\n"
  2550. "func sleep(t)\n"
  2551. " usleep(t * 1000)\n"
  2552. },
  2553. {"random",
  2554. "func rand() {\n"
  2555. " inline `return qi_make_number(state, rand())`\n"
  2556. "}\n"
  2557. "func random_int(min, max): return rand() % (max + 1 - min) + min\n"
  2558. "func random_choice(l, k=1) {\n"
  2559. " l = list_copy(list(l))\n"
  2560. " var r = []\n"
  2561. " for _ of range(k)\n"
  2562. " list_push(r, list_pop_at(l, random_int(0, len(l)-1)))\n"
  2563. " return r\n"
  2564. "}\n"
  2565. "func random_pick(l, k=1) {\n"
  2566. " var r = []\n"
  2567. " for _ of range(k)\n"
  2568. " list_push(r, l[random_int(0, len(l)-1)])\n"
  2569. " return r\n"
  2570. "}\n"
  2571. "inline `srand(time(NULL))`\n"
  2572. },
  2573. {"math", NULL},
  2574. {NULL, NULL}
  2575. };
  2576. const struct {
  2577. const char *name;
  2578. const char *fname;
  2579. int arity;
  2580. } MATHFUNCS[] = {
  2581. { "ceil", NULL, 1 },
  2582. { "floor", NULL, 1 },
  2583. { "trunc", NULL, 1 },
  2584. { "round", NULL, 1 },
  2585. { "abs", "fabs", 1 },
  2586. { "exp", NULL, 1 },
  2587. { "sqrt", NULL, 1 },
  2588. { "sinh", NULL, 1 },
  2589. { "cosh", NULL, 1 },
  2590. { "tanh", NULL, 1 },
  2591. { "asinh", NULL, 1 },
  2592. { "acosh", NULL, 1 },
  2593. { "atanh", NULL, 1 },
  2594. { "sin", NULL, 1 },
  2595. { "cos", NULL, 1 },
  2596. { "tan", NULL, 1 },
  2597. { "asin", NULL, 1 },
  2598. { "acos", NULL, 1 },
  2599. { "atan", NULL, 1 },
  2600. { "atan2", NULL, 2 },
  2601. { "hypot", NULL, 2 },
  2602. { NULL, 0 }
  2603. };
  2604. void genmathlib(void) {
  2605. buffer_t *buffer = buffer_new();
  2606. buffer_appends(buffer, "let Math = {\"tau\": 6.283185307179586, \"pi\": 3.141592653589793, \"e\": 2.718281828459045, \"inf\": INFINITY, \"nan\": NAN, ");
  2607. for (size_t i = 0; MATHFUNCS[i].name; i++) {
  2608. if (MATHFUNCS[i].arity == 0)
  2609. buffer_fmt(buffer, "\"%s\": func () { inline `return qi_make_number(state, %s())` }", MATHFUNCS[i].name, MATHFUNCS[i].fname? MATHFUNCS[i].fname: MATHFUNCS[i].name);
  2610. else if (MATHFUNCS[i].arity == 1)
  2611. buffer_fmt(buffer, "\"%s\": func (x) { if type(x) != \"number\" { throw \"expected first argument to be: number, but got: \" + type(x) } inline `double n = %s(qi_get(state, \"x\")->value.number)`; inline `return qi_make_number(state, n)` }", MATHFUNCS[i].name, MATHFUNCS[i].fname? MATHFUNCS[i].fname: MATHFUNCS[i].name);
  2612. else
  2613. buffer_fmt(buffer, "\"%s\": func (x, y) { if type(x) != \"number\" { throw \"expected first argument to be: number, but got: \" + type(x) } if type(y) != \"number\" { throw \"expected second argument to be: number, but got: \" + type(y) } inline `double n = %s(qi_get(state, \"x\")->value.number, qi_get(state, \"y\")->value.number)`; inline `return qi_make_number(state, n)` }", MATHFUNCS[i].name, MATHFUNCS[i].fname? MATHFUNCS[i].fname: MATHFUNCS[i].name);
  2614. if (MATHFUNCS[i + 1].name)
  2615. buffer_append(buffer, ',');
  2616. }
  2617. buffer_append(buffer, '}');
  2618. size_t i;
  2619. for (i = 0; strcmp(STD[i][0], "math") != 0; i++) ;
  2620. STD[i][1] = buffer_read(buffer);
  2621. }
  2622. char *unescape(char *s) {
  2623. buffer_t *buf = buffer_new();
  2624. for (size_t i = 0; i < strlen(s); i++) {
  2625. char c = s[i];
  2626. if (c == '\\') {
  2627. char nc = s[i+1];
  2628. if (!nc)
  2629. continue;
  2630. switch (nc) {
  2631. case 'n':
  2632. buffer_append(buf, '\n');
  2633. break;
  2634. default:
  2635. buffer_append(buf, nc);
  2636. break;
  2637. }
  2638. i++;
  2639. } else buffer_append(buf, c);
  2640. }
  2641. return buffer_read(buf);
  2642. }
  2643. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl);
  2644. int require_once(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, char *path) {
  2645. char *source = NULL;
  2646. for (size_t i = 0; STD[i][0]; i++) {
  2647. if (strcmp(path, STD[i][0]) == 0) {
  2648. source = (char *)STD[i][1];
  2649. break;
  2650. }
  2651. }
  2652. if (is_required(path))
  2653. return 1;
  2654. if (!source) {
  2655. FILE *fd = fopen(path, "rb");
  2656. if (!fd)
  2657. return -1;
  2658. buffer_t *fbuf = buffer_new();
  2659. for (;;) {
  2660. char line[512];
  2661. if (!fgets(line, sizeof(line), fd))
  2662. break;
  2663. buffer_appends(fbuf, line);
  2664. }
  2665. source = buffer_read(fbuf);
  2666. path = realpath(path, NULL);
  2667. }
  2668. list_t *pair = list_new();
  2669. list_push(pair, path);
  2670. list_push(pair, source);
  2671. list_push(FILES, pair);
  2672. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  2673. list_pop(FILES);
  2674. list_push(REQUIRED, path);
  2675. return 0;
  2676. }
  2677. buffer_t *HBUF;
  2678. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl, node_t *node) {
  2679. switch (node->tag) {
  2680. case N_TOPLEVEL: case N_PROGRAM:
  2681. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l, node->tag == N_TOPLEVEL);
  2682. break;
  2683. case N_EXPRSTMT:
  2684. EMIT("(void)(");
  2685. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2686. EMIT(");");
  2687. break;
  2688. case N_BLOCK:
  2689. LBPUSH();
  2690. CTXPUSH("scope");
  2691. EMIT("qi_new_scope(state);\n");
  2692. compile_block(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l, 0);
  2693. EMIT("qi_old_scope(state);");
  2694. CTXPOP();
  2695. LBPOP();
  2696. break;
  2697. case N_LITERAL:
  2698. switch (node->t->tag) {
  2699. case T_NUMBER: {
  2700. char *number = node->t->text;
  2701. if (strncmp(number, "0o", 2) == 0 || strncmp(number, "0b", 2) == 0) {
  2702. buffer_t *buf = buffer_new();
  2703. if (number[1] == 'o')
  2704. buffer_fmt(buf, "0%s", number + 2);
  2705. else
  2706. buffer_fmt(buf, "%d", strtol(number + 2, NULL, 2));
  2707. number = buffer_read(buf);
  2708. } else if (number[0] == '0' && number[1] && isdigit(number[1])) {
  2709. size_t i;
  2710. for (i = 0; i < strlen(number); i++)
  2711. if (number[i] != '0' || number[i+1] == '.')
  2712. break;
  2713. number += i;
  2714. }
  2715. EMIT("qi_make_number(state, %s)", number);
  2716. } break;
  2717. case T_STRING:
  2718. if (!*(node->t->text)) {
  2719. EMIT("state->empty_string");
  2720. } else {
  2721. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  2722. }
  2723. break;
  2724. case T_FSTRING: {
  2725. char *text = node->t->text;
  2726. if (!*text) {
  2727. EMIT("state->empty_string");
  2728. break;
  2729. }
  2730. list_t *parts = list_new();
  2731. buffer_t *tbuf = buffer_new();
  2732. for (size_t i = 0; i < strlen(text); i++) {
  2733. char c = text[i];
  2734. if (c == '$' && text[i+1] == '$') {
  2735. buffer_append(tbuf, '$');
  2736. i++;
  2737. continue;
  2738. } else if (c == '$' && text[i+1] == '{') {
  2739. i += 2;
  2740. buffer_t *tbuf2 = buffer_new();
  2741. while (text[i] && text[i] != '}')
  2742. buffer_append(tbuf2, text[i++]);
  2743. if (text[i] != '}') {
  2744. i--;
  2745. buffer_appends(tbuf, "${");
  2746. buffer_appendb(tbuf, tbuf2);
  2747. continue;
  2748. }
  2749. if (tbuf->size > 0)
  2750. list_push(parts, nodeb(tbuf));
  2751. tbuf = buffer_new();
  2752. char *source = buffer_read(tbuf2);
  2753. list_t *pair = list_new();
  2754. list_push(pair, "<fstring>");
  2755. list_push(pair, source);
  2756. list_push(FILES, pair);
  2757. size_t pos = 0;
  2758. node_t *n = parse_expr(tokenize(source), &pos);
  2759. list_push(parts, n);
  2760. } else buffer_append(tbuf, c);
  2761. }
  2762. if (tbuf->size > 0)
  2763. list_push(parts, nodeb(tbuf));
  2764. tbuf = buffer_new();
  2765. NEWGID();
  2766. buffer_fmt(tbuf, "inline static qi_value_t *__fstring%d(qi_state_t *state) {\n", gid);
  2767. buffer_fmt(tbuf, "qi_value_t *str = state->empty_string;\n");
  2768. for (size_t i = 0; i < parts->length; i++) {
  2769. node_t *part = parts->data[i];
  2770. buffer_fmt(tbuf, "str = qi_add(state, str, ");
  2771. if (part->tag == N_BUFFER)
  2772. buffer_fmt(tbuf, "qi_make_string(state, \"%s\")", buffer_read(part->buf));
  2773. else {
  2774. buffer_fmt(tbuf, "qi_to_string(state, ");
  2775. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, part);
  2776. buffer_fmt(tbuf, ")");
  2777. }
  2778. buffer_fmt(tbuf, ");\n");
  2779. }
  2780. buffer_fmt(tbuf, "return str;\n}\n");
  2781. buffer_appendb(gbuf, tbuf);
  2782. EMIT("__fstring%d(state)", gid);
  2783. } break;
  2784. case T_NAME: {
  2785. char *name = node->t->text;
  2786. node_t *n = table_get(CONSTANTS, name);
  2787. if (n)
  2788. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  2789. else
  2790. EMIT("qi_get(state, \"%s\")", name);
  2791. } break;
  2792. default:
  2793. COMPILE_ERROR("not yet implemented");
  2794. }
  2795. break;
  2796. case N_LIST:
  2797. EMIT("qi_make_list(state, ");
  2798. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  2799. EMIT(")");
  2800. break;
  2801. case N_LISTGEN: {
  2802. NEWGID();
  2803. buffer_t *tbuf = buffer_new();
  2804. buffer_fmt(tbuf, "inline static qi_value_t *__listgen%d(qi_state_t *state) {\n", gid);
  2805. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  2806. buffer_t *bbuf = buffer_new();
  2807. for (size_t i = 0; i < node->a->b->l->length; i++) {
  2808. buffer_fmt(bbuf, "qi_list_push(list, ");
  2809. compile_node(gbuf, bbuf, ctx, ltab, lstk, sstk, lbl, node->a->b->l->data[i]);
  2810. buffer_fmt(bbuf, ");\n");
  2811. }
  2812. node->a->b = nodeb(bbuf);
  2813. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2814. buffer_fmt(tbuf, "return qi_make_list(state, list);\n}\n");
  2815. buffer_appendb(gbuf, tbuf);
  2816. EMIT("__listgen%d(state)", gid);
  2817. } break;
  2818. case N_TUPLE:
  2819. EMIT("qi_make_tuple(state, ");
  2820. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  2821. EMIT(")");
  2822. break;
  2823. case N_NILTUPLE: EMIT("state->empty_tuple"); break;
  2824. case N_TABLE:
  2825. EMIT("qi_make_table(state, ");
  2826. compile_table(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->h);
  2827. EMIT(")");
  2828. break;
  2829. case N_CALL:
  2830. EMIT("qi_call(state, ");
  2831. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2832. EMIT(", ");
  2833. compile_list(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->l);
  2834. EMIT(")");
  2835. break;
  2836. case N_MEMBER:
  2837. EMIT("qi_index(state, ");
  2838. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2839. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  2840. break;
  2841. case N_INDEX:
  2842. EMIT("qi_index(state, ");
  2843. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2844. EMIT(", ");
  2845. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  2846. EMIT(")");
  2847. break;
  2848. case N_SLICE: {
  2849. NEWGID();
  2850. buffer_t *tbuf = buffer_new();
  2851. buffer_fmt(tbuf, "inline static qi_value_t *__slice%d(qi_state_t *state) {\n", gid);
  2852. if (node->b && node->c) {
  2853. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  2854. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  2855. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2856. buffer_fmt(tbuf, ";\n");
  2857. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  2858. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  2859. buffer_fmt(tbuf, ";\n");
  2860. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  2861. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  2862. buffer_fmt(tbuf, ";\n");
  2863. } else if (node->b) {
  2864. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(2);\n");
  2865. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  2866. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2867. buffer_fmt(tbuf, ";\n");
  2868. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = ");
  2869. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  2870. buffer_fmt(tbuf, ";\n");
  2871. } else {
  2872. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(3);\n");
  2873. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = ");
  2874. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  2875. buffer_fmt(tbuf, ";\n");
  2876. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = state->zero;\n");
  2877. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = ");
  2878. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->c);
  2879. buffer_fmt(tbuf, ";\n");
  2880. }
  2881. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, \"__slice\"), pargs);\n");
  2882. buffer_fmt(tbuf, "}\n");
  2883. buffer_appendb(gbuf, tbuf);
  2884. EMIT("__slice%d(state)", gid);
  2885. } break;
  2886. case N_ASSIGN:
  2887. if (node->a->tag == N_LIST) {
  2888. if (node->a->l->length < 2)
  2889. COMPILE_ERROR("illegal unpack assignment left-hand side");
  2890. NEWGID();
  2891. buffer_t *tbuf = buffer_new();
  2892. buffer_fmt(tbuf, "inline static qi_value_t *__assign%d(qi_state_t *state) {\n", gid);
  2893. char *varname = tempvar();
  2894. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  2895. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b);
  2896. buffer_fmt(tbuf, ";\n");
  2897. for (size_t i = 0; i < node->a->l->length; i++) {
  2898. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i], buffer_fmt(tbuf, "qi_index(state, %s, qi_make_number(state, %d))", varname, i));
  2899. buffer_fmt(tbuf, ";\n");
  2900. }
  2901. buffer_fmt(tbuf, "return %s;\n}\n", varname);
  2902. buffer_appendb(gbuf, tbuf);
  2903. EMIT("__assign%d(state)", gid);
  2904. break;
  2905. } else if (node->a->tag == N_TUPLE) {
  2906. if (node->a->l->length < 2)
  2907. COMPILE_ERROR("illegal multiple assignment left-hand side");
  2908. if (node->b->tag != N_TUPLE || node->b->l->length < 2 || node->a->l->length != node->b->l->length)
  2909. COMPILE_ERROR("illegal multiple assignment right-hand side");
  2910. NEWGID();
  2911. buffer_t *tbuf = buffer_new();
  2912. buffer_fmt(tbuf, "qi_value_t *__assign%d(qi_state_t *state) {\n", gid);
  2913. list_t *vals = list_new();
  2914. for (size_t i = 0; i < node->b->l->length; i++) {
  2915. char *varname = tempvar();
  2916. buffer_fmt(tbuf, "qi_value_t *%s = ", varname);
  2917. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->b->l->data[i]);
  2918. buffer_fmt(tbuf, ";\n");
  2919. list_push(vals, varname);
  2920. }
  2921. for (size_t i = 0; i < node->a->l->length; i++) {
  2922. char *varname = vals->data[i];
  2923. ASSIGNIN(tbuf, (node_t *)node->a->l->data[i], buffer_fmt(tbuf, "%s", varname));
  2924. buffer_fmt(tbuf, ";\n");
  2925. }
  2926. buffer_fmt(tbuf, "return %s;\n}\n", vals->data[vals->length-1]);
  2927. buffer_appendb(gbuf, tbuf);
  2928. EMIT("__assign%d(state)", gid);
  2929. break;
  2930. }
  2931. ASSIGN(node->a, compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b));
  2932. break;
  2933. case N_ASSIGN_ADD: COMPASSIGN(node->a, "add", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2934. case N_ASSIGN_SUB: COMPASSIGN(node->a, "sub", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2935. case N_ASSIGN_MUL: COMPASSIGN(node->a, "mul", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2936. case N_ASSIGN_DIV: COMPASSIGN(node->a, "div", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2937. case N_ASSIGN_IDIV: COMPASSIGN(node->a, "idiv", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2938. case N_ASSIGN_MOD: COMPASSIGN(node->a, "mod", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2939. case N_ASSIGN_POW: COMPASSIGN(node->a, "pow", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2940. case N_ASSIGN_BOR: COMPASSIGN(node->a, "bor", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2941. case N_ASSIGN_BAND: COMPASSIGN(node->a, "band", compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b)); break;
  2942. case N_INC:
  2943. COMPASSIGN(node->a, "add", EMIT("state->one"));
  2944. break;
  2945. case N_DEC:
  2946. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  2947. break;
  2948. case N_VAR: case N_LET:
  2949. table_iterate(node->h, {
  2950. EMIT("qi_%s(state, \"%s\", ", node->tag == N_LET? "decl_const": "decl", entry.key);
  2951. if (entry.value)
  2952. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, entry.value);
  2953. else EMIT("state->nil");
  2954. EMIT(");\n");
  2955. });
  2956. break;
  2957. case N_VARUNPACK: case N_LETUNPACK: {
  2958. char *varname = tempvar();
  2959. EMIT("qi_value_t *%s = ", varname);
  2960. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2961. EMIT(";\n");
  2962. for (size_t i = 0; i < node->l->length; i++)
  2963. 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);
  2964. } break;
  2965. case N_CONST:break;
  2966. case N_IF:
  2967. EMIT("if (_qi_truthy(state, ");
  2968. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2969. EMIT(")) {\n");
  2970. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  2971. if (node->c) {
  2972. EMIT("} else {\n");
  2973. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  2974. }
  2975. EMIT("}");
  2976. break;
  2977. case N_SWITCH: {
  2978. NEWGID();
  2979. if (node->t2) {
  2980. if (table_get(ltab, node->t2->text))
  2981. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  2982. stack_t *pair = stack_new();
  2983. stack_push(pair, 1);
  2984. stack_push(pair, gid);
  2985. table_set(ltab, node->t2->text, pair);
  2986. }
  2987. char *varname = tempvar();
  2988. EMIT("qi_value_t *%s = ", varname);
  2989. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  2990. EMIT(";\n");
  2991. for (size_t i = 0; i < node->l->length; i++) {
  2992. list_t *pair = node->l->data[i];
  2993. char *label = tempvar();
  2994. EMIT("if (_qi_equals(state, %s, ", varname);
  2995. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, pair->data[0]);
  2996. EMIT(")) goto %s;\n", label);
  2997. pair->data[0] = label;
  2998. }
  2999. EMIT("goto __default%d;\n", gid);
  3000. SPUSH(gid);
  3001. CTXPUSH("switch");
  3002. for (size_t i = 0; i < node->l->length; i++) {
  3003. list_t *pair = node->l->data[i];
  3004. char *label = pair->data[0];
  3005. node_t *block = pair->data[1];
  3006. EMIT("%s:;\n", label);
  3007. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, block);
  3008. }
  3009. EMIT("__default%d:;\n", gid);
  3010. if (node->b)
  3011. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3012. CTXPOP();
  3013. SPOP();
  3014. EMIT("__break%d:;\n", gid);
  3015. } break;
  3016. case N_FOR: {
  3017. NEWGID();
  3018. if (node->t2) {
  3019. if (table_get(ltab, node->t2->text))
  3020. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  3021. stack_t *pair = stack_new();
  3022. stack_push(pair, 0);
  3023. stack_push(pair, gid);
  3024. table_set(ltab, node->t2->text, pair);
  3025. }
  3026. if (!node->a) {
  3027. EMIT("for (;;) {\n");
  3028. } else if (node->a && !node->b) {
  3029. EMIT("while (_qi_truthy(state, ");
  3030. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3031. EMIT(")) {\n");
  3032. } else {
  3033. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3034. EMIT("while (_qi_truthy(state, ");
  3035. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3036. EMIT(")) {\n");
  3037. }
  3038. LPUSH(gid);
  3039. CTXPUSH("for");
  3040. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->d);
  3041. EMIT("__continue%d:;\n", gid);
  3042. if (node->c) {
  3043. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  3044. EMIT(";\n");
  3045. }
  3046. CTXPOP();
  3047. LPOP();
  3048. EMIT("}\n");
  3049. EMIT("__break%d:;\n", gid);
  3050. } break;
  3051. case N_FOROF: case N_FOROFVAR: case N_FOROFUNPACK: case N_FOROFVARUNPACK: {
  3052. NEWGID();
  3053. if (node->t2) {
  3054. if (table_get(ltab, node->t2->text))
  3055. COMPILE_ERROR("redeclaration of loop label: '%s'", node->t2->text);
  3056. stack_t *pair = stack_new();
  3057. stack_push(pair, 0);
  3058. stack_push(pair, gid);
  3059. table_set(ltab, node->t2->text, pair);
  3060. }
  3061. char *varname = tempvar();
  3062. EMIT("qi_value_t *%s = qi_iter(state, ", varname);
  3063. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3064. EMIT(");\n");
  3065. if (node->tag == N_FOROFVAR) {
  3066. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->t->text);
  3067. } else if (node->tag == N_FOROFVARUNPACK) {
  3068. for (size_t i = 0; i < node->l->length; i++)
  3069. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->l->data[i]);
  3070. }
  3071. EMIT("for (qi_size_t length = _qi_length(state, %s), i = 0; i < length; i++) {\n", varname);
  3072. if (node->tag == N_FOROFUNPACK || node->tag == N_FOROFVARUNPACK) {
  3073. for (size_t i = 0; i < node->l->length; i++)
  3074. 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);
  3075. } else
  3076. EMIT("qi_set(state, false, \"%s\", qi_index(state, %s, qi_make_number(state, i)));\n", node->t->text, varname);
  3077. LPUSH(gid);
  3078. CTXPUSH("for");
  3079. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3080. CTXPOP();
  3081. LPOP();
  3082. EMIT("__continue%d:;\n", gid);
  3083. EMIT("}\n");
  3084. EMIT("__break%d:;\n", gid);
  3085. } break;
  3086. case N_BREAK:
  3087. if (!INCTX("for") && !INCTX("switch"))
  3088. COMPILE_ERROR("break outside of a loop or a switch");
  3089. if (node->t) {
  3090. if (node->t->tag == T_NUMBER) {
  3091. unsigned int offset = abs(atoi(node->t->text)) + 1;
  3092. if (offset < 2 || offset > lstk->length)
  3093. COMPILE_ERROR("%d is not a valid break loop offset", offset-1);
  3094. EMIT("goto __break%d;", lstk->data[lstk->length-offset]);
  3095. } else {
  3096. char *label = node->t->text;
  3097. stack_t *pair = table_get(ltab, label);
  3098. if (!pair)
  3099. COMPILE_ERROR("undefined loop label: '%s'", label);
  3100. EMIT("goto __break%d;", pair->data[1]);
  3101. }
  3102. break;
  3103. }
  3104. EMIT("goto __break%d;", in_switch(ctx)? SID: LID);
  3105. break;
  3106. case N_CONTINUE:
  3107. if (!INCTX("for"))
  3108. COMPILE_ERROR("continue outside of a loop");
  3109. if (node->t) {
  3110. if (node->t->tag == T_NUMBER) {
  3111. unsigned int offset = abs(atoi(node->t->text)) + 1;
  3112. if (offset < 2 || offset > lstk->length)
  3113. COMPILE_ERROR("%d is not a valid break loop offset", offset-1);
  3114. EMIT("goto __continue%d;", lstk->data[lstk->length-offset]);
  3115. } else {
  3116. char *label = node->t->text;
  3117. stack_t *pair = table_get(ltab, label);
  3118. if (pair->data[1])
  3119. COMPILE_ERROR("continue on a switch loop label: '%s'", label);
  3120. if (!pair)
  3121. COMPILE_ERROR("undefined loop label: '%s'", label);
  3122. EMIT("goto __continue%d;", pair->data[1]);
  3123. }
  3124. break;
  3125. }
  3126. EMIT("goto __continue%d;", LID);
  3127. break;
  3128. case N_DEFER: {
  3129. NEWGID();
  3130. buffer_t *tbuf = buffer_new();
  3131. buffer_fmt(tbuf, "void __defer%d(qi_state_t *state) {\n", gid);
  3132. LBPUSH();
  3133. CTXPUSH("gap");
  3134. compile_node(gbuf, tbuf, ctx, ltab, lstk, sstk, lbl, node->a);
  3135. CTXPOP();
  3136. LBPOP();
  3137. buffer_fmt(tbuf, "\n");
  3138. buffer_fmt(tbuf, "}\n");
  3139. buffer_appendb(gbuf, tbuf);
  3140. EMIT("qi_add_defer(state, -1, __defer%d);", gid);
  3141. } break;
  3142. case N_RETURN:
  3143. if (!INCTX("func"))
  3144. COMPILE_ERROR("return outside of a function");
  3145. for (size_t i = 0; i < SCOPESK; i++)
  3146. EMIT("qi_old_scope(state);\n");
  3147. for (size_t i = 0; i < TRAPSK; i++)
  3148. EMIT("qi_unset_trap(state, trap);\n");
  3149. EMIT("return ");
  3150. if (node->a)
  3151. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3152. else EMIT("state->nil");
  3153. EMIT(";");
  3154. break;
  3155. case N_FUNCDEF: break;
  3156. case N_CLASS: break;
  3157. case N_PASS: break;
  3158. case N_TRY:
  3159. EMIT("qi_try(state, {\n");
  3160. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3161. EMIT("}, {\n");
  3162. if (node->t)
  3163. EMIT("qi_decl(state, \"%s\", trap->value);\n", node->t->text);
  3164. CTXPUSH("trap");
  3165. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3166. CTXPOP();
  3167. EMIT("}, NULL);\n");
  3168. break;
  3169. case N_THROW:
  3170. EMIT("qi_throw(state, ");
  3171. if (node->a)
  3172. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3173. else {
  3174. EMIT("state->nil");
  3175. }
  3176. EMIT(");");
  3177. break;
  3178. case N_LABEL: {
  3179. size_t *gid = table_get(list_index(lbl, -1), node->t->text);
  3180. EMIT("__label%d:;", *gid);
  3181. } break;
  3182. case N_GOTO: {
  3183. char *label = node->t->text;
  3184. size_t *gid = table_get(list_index(lbl, -1), label);
  3185. if (!gid)
  3186. COMPILE_ERROR("undefined label: '%s'", label);
  3187. EMIT("goto __label%d;", *gid);
  3188. } break;
  3189. case N_REQUIRE: {
  3190. char *path = unescape(node->t->text);
  3191. if (require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, path) < 0)
  3192. COMPILE_ERROR("'%s' is not a valid file path or a builtin library name", path);
  3193. } break;
  3194. case N_IFEXPR:
  3195. EMIT("(_qi_truthy(state, ");
  3196. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->a);
  3197. EMIT(")? ");
  3198. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->b);
  3199. EMIT(": ");
  3200. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node->c);
  3201. EMIT(")");
  3202. break;
  3203. case N_FUNCEXPR:
  3204. compile_func(gbuf, buf, ctx, ltab, lstk, sstk, lbl, node, NULL);
  3205. break;
  3206. case N_EQUALS:
  3207. BINOP("equals");
  3208. break;
  3209. case N_NOTEQUALS:
  3210. BINOP("not_equals");
  3211. break;
  3212. case N_IS:
  3213. BINOP("is");
  3214. break;
  3215. case N_NOTIS:
  3216. BINOP("not_is");
  3217. break;
  3218. case N_IN:
  3219. BINOP("in");
  3220. break;
  3221. case N_NOTIN:
  3222. BINOP("not_in");
  3223. break;
  3224. case N_LT:
  3225. BINOP("lt");
  3226. break;
  3227. case N_GT:
  3228. BINOP("gt");
  3229. break;
  3230. case N_LE:
  3231. BINOP("le");
  3232. break;
  3233. case N_GE:
  3234. BINOP("ge");
  3235. break;
  3236. case N_ADD:
  3237. BINOP("add");
  3238. break;
  3239. case N_SUB:
  3240. BINOP("sub");
  3241. break;
  3242. case N_MUL:
  3243. BINOP("mul");
  3244. break;
  3245. case N_DIV:
  3246. BINOP("div");
  3247. break;
  3248. case N_IDIV:
  3249. BINOP("idiv");
  3250. break;
  3251. case N_MOD:
  3252. BINOP("mod");
  3253. break;
  3254. case N_POW:
  3255. BINOP("pow");
  3256. break;
  3257. case N_SHL:
  3258. BINOP("shl");
  3259. break;
  3260. case N_SHR:
  3261. BINOP("shr");
  3262. break;
  3263. case N_XOR:
  3264. BINOP("xor");
  3265. break;
  3266. case N_BOR:
  3267. BINOP("bor");
  3268. break;
  3269. case N_BAND:
  3270. BINOP("band");
  3271. break;
  3272. case N_LOGOR:
  3273. BINOP("or");
  3274. break;
  3275. case N_LOGAND:
  3276. BINOP("and");
  3277. break;
  3278. case N_NEGATE:
  3279. UNOP("negate");
  3280. break;
  3281. case N_NOT:
  3282. UNOP("not");
  3283. break;
  3284. case N_BNOT:
  3285. UNOP("bnot");
  3286. break;
  3287. case N_INLINE: {
  3288. char *text = unescape(node->t->text);
  3289. if (text[0] == '#') {
  3290. EMIT("%s", text);
  3291. } else {
  3292. EMIT("%s;", text);
  3293. }
  3294. } break;
  3295. case N_HEADER: buffer_fmt(HBUF, "%s\n", unescape(node->t->text)); break;
  3296. case N_INCLUDE: buffer_fmt(HBUF, "#include <%s>\n", unescape(node->t->text)); break;
  3297. case N_BUFFER: buffer_appendb(buf, node->buf); break;
  3298. default:
  3299. COMPILE_ERROR("not yet implemented");
  3300. }
  3301. }
  3302. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx, table_t *ltab, stack_t *lstk, stack_t *sstk, list_t *lbl) {
  3303. node_t *n = parse(source);
  3304. compile_node(gbuf, buf, ctx, ltab, lstk, sstk, lbl, n);
  3305. }
  3306. char *compile(char *source) {
  3307. list_t *ctx = list_new();
  3308. table_t *ltab = table_new();
  3309. stack_t *lstk = stack_new();
  3310. stack_t *sstk = stack_new();
  3311. list_t *lbl = list_new();
  3312. LBPUSH();
  3313. buffer_t *gbuf = buffer_new();
  3314. buffer_t *buf = buffer_new();
  3315. require_once(gbuf, buf, ctx, ltab, lstk, sstk, lbl, "std");
  3316. compile_into(source, gbuf, buf, ctx, ltab, lstk, sstk, lbl);
  3317. buffer_t *rbuf = buffer_new();
  3318. buffer_appends(rbuf, "#include <qirt.h>\n");
  3319. buffer_appendb(rbuf, HBUF);
  3320. buffer_appendb(rbuf, gbuf);
  3321. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  3322. buffer_appends(rbuf, "qi_state_t *state;\n");
  3323. buffer_appends(rbuf, "qi_state_init(&state);\n");
  3324. buffer_appendb(rbuf, buf);
  3325. buffer_appends(rbuf, "qi_old_scope(state);\n");
  3326. buffer_appends(rbuf, "qi_finalize();\n");
  3327. buffer_appends(rbuf, "return 0;\n");
  3328. buffer_appends(rbuf, "}\n");
  3329. return buffer_read(rbuf);
  3330. }
  3331. char *compile_file(char *filename, FILE *fd) {
  3332. buffer_t *buf = buffer_new();
  3333. for (;;) {
  3334. char line[512];
  3335. if (!fgets(line, sizeof(line), fd))
  3336. break;
  3337. buffer_appends(buf, line);
  3338. }
  3339. char *source = buffer_read(buf);
  3340. list_t *pair = list_new();
  3341. list_push(pair, filename);
  3342. list_push(pair, source);
  3343. list_push(FILES, pair);
  3344. char *out = compile(source);
  3345. list_pop(FILES);
  3346. return out;
  3347. }
  3348. int main(int argc, char **argv) {
  3349. FILES = list_new();
  3350. REQUIRED = list_new();
  3351. CONSTANTS = table_new();
  3352. HBUF = buffer_new();
  3353. genmathlib();
  3354. char *out = compile_file("<stdin>", stdin);
  3355. fwrite(out, sizeof(char), strlen(out), stdout);
  3356. return 0;
  3357. }