qic.c 102 KB

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