qic.c 111 KB

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