qic.c 115 KB

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