qic.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  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. void *p = malloc(sizeof(char) * buf->size);
  167. if (buf->str)
  168. memcpy(p, buf->str, buf->size - 1);
  169. buf->str = p;
  170. buf->str[buf->size - 1] = c;
  171. }
  172. char *buffer_read(buffer_t *buf) {
  173. if (buf->size == 0 || buf->str[buf->size - 1])
  174. buffer_append(buf, 0);
  175. return buf->str;
  176. }
  177. void buffer_appends(buffer_t *buf, char *s) {
  178. for (size_t i = 0; i < strlen(s); i++)
  179. buffer_append(buf, s[i]);
  180. }
  181. void buffer_appendb(buffer_t *dst, buffer_t *src) {
  182. for (size_t i = 0; i < src->size; i++)
  183. buffer_append(dst, src->str[i]);
  184. }
  185. void buffer_fmt(buffer_t *buf, const char *fmt, ...) {
  186. va_list args;
  187. va_start(args, fmt);
  188. size_t size = vsnprintf(NULL, 0, fmt, args);
  189. char *str = malloc(sizeof(char) * (size + 1));
  190. vsnprintf(str, size + 1, fmt, args);
  191. va_end(args);
  192. buffer_appends(buf, str);
  193. }
  194. typedef struct {
  195. enum {
  196. T_EOF,
  197. T_NUMBER,
  198. T_STRING,
  199. T_NAME,
  200. T_VAR,
  201. T_LET,
  202. T_CONST,
  203. T_IF,
  204. T_ELSE,
  205. T_ELIF,
  206. T_SWITCH,
  207. T_CASE,
  208. T_DEFAULT,
  209. T_FOR,
  210. T_OF,
  211. T_BREAK,
  212. T_CONTINUE,
  213. T_PASS,
  214. T_FUNC,
  215. T_USE,
  216. T_RETURN,
  217. T_DEFER,
  218. T_REQUIRE,
  219. T_TRY,
  220. T_CATCH,
  221. T_THROW,
  222. T_GOTO,
  223. T_CLASS,
  224. T_IS,
  225. T_IN,
  226. T_LPAR,
  227. T_RPAR,
  228. T_LSB,
  229. T_RSB,
  230. T_LCB,
  231. T_RCB,
  232. T_EQUALS,
  233. T_NOTEQUALS,
  234. T_PLUSASSIGN,
  235. T_MINUSASSIGN,
  236. T_SLASHASSIGN,
  237. T_STARASSIGN,
  238. T_SLASHSLASHASSIGN,
  239. T_PERCENTASSIGN,
  240. T_BARBAR,
  241. T_ANDAND,
  242. T_STARSTAR,
  243. T_PLUSPLUS,
  244. T_MINUSMINUS,
  245. T_SLASHSLASH,
  246. T_PLUS,
  247. T_MINUS,
  248. T_QM,
  249. T_COLON,
  250. T_BAR,
  251. T_AND,
  252. T_LT,
  253. T_LTLT,
  254. T_GT,
  255. T_GTGT,
  256. T_LE,
  257. T_GE,
  258. T_STAR,
  259. T_SLASH,
  260. T_PERCENT,
  261. T_COMMA,
  262. T_DOT,
  263. T_BANG,
  264. T_RAISE,
  265. T_TILDE,
  266. T_INLINE,
  267. T_ASSIGN,
  268. T_SEMI
  269. } tag;
  270. char *text;
  271. size_t fi;
  272. size_t pos;
  273. } token_t;
  274. token_t *token(int tag, char *text) {
  275. token_t *tok = malloc(sizeof(token_t));
  276. tok->tag = tag;
  277. tok->text = text;
  278. return tok;
  279. }
  280. #define TK(tk) (token(T_##tk, NULL))
  281. #define WS() while (source[*pos] == ' ' || source[*pos] == '\t' || source[*pos] == '\n' || source[*pos] == '\r') { (*pos)++; }
  282. void consume_ignored(char *source, size_t *pos) {
  283. WS();
  284. while (source[*pos] == '#') {
  285. (*pos)++;
  286. for (;;) {
  287. if (!source[*pos])
  288. break;
  289. if (source[*pos] == '\n') {
  290. (*pos)++;
  291. break;
  292. }
  293. (*pos)++;
  294. }
  295. WS();
  296. }
  297. }
  298. list_t *FILES;
  299. list_t *REQUIRED;
  300. int is_required(char *path) {
  301. for (size_t i = 0; i < REQUIRED->length; i++)
  302. if (strcmp(REQUIRED->data[i], path) == 0)
  303. return 1;
  304. return 0;
  305. }
  306. void traverse(char *source, size_t pos, size_t *line, size_t *col) {
  307. *line = 1;
  308. *col = 1;
  309. for (size_t i = 0; i < pos; i++) {
  310. if (source[i] == '\n') {
  311. (*line)++;
  312. (*col) = 1;
  313. } else (*col)++;
  314. }
  315. }
  316. void format_error(char *filename, char *source, size_t pos, char *fmt, ...) {
  317. size_t line, col;
  318. traverse(source, pos, &line, &col);
  319. va_list args;
  320. va_start(args, fmt);
  321. fprintf(stderr, "%s (%zu:%zu): ", filename, line, col);
  322. vfprintf(stderr, fmt, args);
  323. fputc('\n', stderr);
  324. va_end(args);
  325. }
  326. #define GETFNAME(fi) ((char *)((list_t *)list_index(FILES, fi))->data[0])
  327. #define GETSRC(fi) ((char *)((list_t *)list_index(FILES, fi))->data[1])
  328. #define LEX_ERROR(fmt, ...) { format_error(GETFNAME(-1), source, *pos, fmt, ##__VA_ARGS__); exit(1); }
  329. token_t *next_token(char *source, size_t *pos) {
  330. if (!source[*pos])
  331. return token(T_EOF, NULL);
  332. if (source[*pos] == '"' || source[*pos] == '\'' || source[*pos] == '`') {
  333. char term = source[(*pos)++];
  334. buffer_t *text = buffer_new();
  335. while (source[*pos] != term) {
  336. if (!source[*pos])
  337. LEX_ERROR("unterminated string literal");
  338. char c = source[(*pos)++];
  339. if (c == '\n' && term != '`')
  340. LEX_ERROR("unterminated string literal");
  341. if (term != '`' && c == '\\') {
  342. char nc = source[(*pos)++];
  343. if (!nc)
  344. continue;
  345. switch (nc) {
  346. case 'n':
  347. buffer_appends(text, "\\n");
  348. break;
  349. case 't':
  350. buffer_appends(text, "\\t");
  351. break;
  352. case 'r':
  353. buffer_appends(text, "\\r");
  354. break;
  355. case 'b':
  356. buffer_appends(text, "\\b");
  357. break;
  358. case 'e':
  359. buffer_appends(text, "\\e");
  360. break;
  361. case 's':
  362. buffer_appends(text, " ");
  363. break;
  364. case '"':
  365. buffer_appends(text, "\\\"");
  366. break;
  367. case '\\':
  368. buffer_appends(text, "\\\\");
  369. break;
  370. case '\n':
  371. buffer_appends(text, "\\n");
  372. break;
  373. default:
  374. buffer_append(text, nc);
  375. break;
  376. }
  377. continue;
  378. }
  379. if (c == '"' || c == '\\')
  380. buffer_append(text, '\\');
  381. else if (c == '\n')
  382. buffer_appends(text, "\\n");
  383. buffer_append(text, c);
  384. }
  385. (*pos)++;
  386. return token(T_STRING, buffer_read(text));
  387. } else if ((source[*pos] == '.' && isdigit(source[(*pos)+1])) || isdigit(source[*pos])) {
  388. buffer_t *number = buffer_new();
  389. int dot = 0;
  390. int sub = 0;
  391. int skip = 0;
  392. if (source[*pos] == '.') {
  393. buffer_append(number, '0');
  394. skip = 1;
  395. }
  396. do {
  397. if (skip) skip = 0;
  398. else
  399. buffer_append(number, source[(*pos)++]);
  400. if (!dot && source[*pos] == '.') {
  401. buffer_append(number, source[(*pos)++]);
  402. if (!isdigit(source[*pos]))
  403. LEX_ERROR("illegal number literal (missing part after floating point)");
  404. dot = 1;
  405. } else if (!sub && source[*pos] == '_') {
  406. (*pos)++;
  407. if (!isdigit(source[*pos]))
  408. LEX_ERROR("illegal number literal (missing part after underscore)");
  409. sub = 1;
  410. } else if (sub) sub = 0;
  411. } while (isdigit(source[*pos]));
  412. return token(T_NUMBER, buffer_read(number));
  413. } else if (isalpha(source[*pos]) || source[*pos] == '_') {
  414. buffer_t *text = buffer_new();
  415. do {
  416. buffer_append(text, source[(*pos)++]);
  417. } while (isalpha(source[*pos]) || source[*pos] == '_' || isdigit(source[*pos]));
  418. char *name = buffer_read(text);
  419. if (strcmp(name, "var") == 0)
  420. return TK(VAR);
  421. else if (strcmp(name, "let") == 0)
  422. return TK(LET);
  423. else if (strcmp(name, "const") == 0)
  424. return TK(CONST);
  425. else if (strcmp(name, "if") == 0)
  426. return TK(IF);
  427. else if (strcmp(name, "else") == 0)
  428. return TK(ELSE);
  429. else if (strcmp(name, "elif") == 0)
  430. return TK(ELIF);
  431. else if (strcmp(name, "switch") == 0)
  432. return TK(SWITCH);
  433. else if (strcmp(name, "case") == 0)
  434. return TK(CASE);
  435. else if (strcmp(name, "default") == 0)
  436. return TK(DEFAULT);
  437. else if (strcmp(name, "for") == 0)
  438. return TK(FOR);
  439. else if (strcmp(name, "break") == 0)
  440. return TK(BREAK);
  441. else if (strcmp(name, "continue") == 0)
  442. return TK(CONTINUE);
  443. else if (strcmp(name, "func") == 0)
  444. return TK(FUNC);
  445. else if (strcmp(name, "use") == 0)
  446. return TK(USE);
  447. else if (strcmp(name, "return") == 0)
  448. return TK(RETURN);
  449. else if (strcmp(name, "defer") == 0)
  450. return TK(DEFER);
  451. else if (strcmp(name, "pass") == 0)
  452. return TK(PASS);
  453. else if (strcmp(name, "require") == 0)
  454. return TK(REQUIRE);
  455. else if (strcmp(name, "try") == 0)
  456. return TK(TRY);
  457. else if (strcmp(name, "catch") == 0)
  458. return TK(CATCH);
  459. else if (strcmp(name, "throw") == 0)
  460. return TK(THROW);
  461. else if (strcmp(name, "goto") == 0)
  462. return TK(GOTO);
  463. else if (strcmp(name, "class") == 0)
  464. return TK(CLASS);
  465. else if (strcmp(name, "is") == 0)
  466. return TK(IS);
  467. else if (strcmp(name, "in") == 0)
  468. return TK(IN);
  469. else if (strcmp(name, "of") == 0)
  470. return TK(OF);
  471. else if (strcmp(name, "inline") == 0)
  472. return TK(INLINE);
  473. return token(T_NAME, name);
  474. } else if (strncmp(&source[*pos], "==", 2) == 0 && ++(*pos) && ++(*pos))
  475. return TK(EQUALS);
  476. else if (strncmp(&source[*pos], "!=", 2) == 0 && ++(*pos) && ++(*pos))
  477. return TK(NOTEQUALS);
  478. else if (strncmp(&source[*pos], "+=", 2) == 0 && ++(*pos) && ++(*pos))
  479. return TK(PLUSASSIGN);
  480. else if (strncmp(&source[*pos], "-=", 2) == 0 && ++(*pos) && ++(*pos))
  481. return TK(MINUSASSIGN);
  482. else if (strncmp(&source[*pos], "*=", 2) == 0 && ++(*pos) && ++(*pos))
  483. return TK(STARASSIGN);
  484. else if (strncmp(&source[*pos], "/=", 2) == 0 && ++(*pos) && ++(*pos))
  485. return TK(SLASHASSIGN);
  486. else if (strncmp(&source[*pos], "//=", 3) == 0 && ++(*pos) && ++(*pos) && ++(*pos))
  487. return TK(SLASHSLASHASSIGN);
  488. else if (strncmp(&source[*pos], "%=", 2) == 0 && ++(*pos) && ++(*pos))
  489. return TK(PERCENTASSIGN);
  490. else if (strncmp(&source[*pos], "||", 2) == 0 && ++(*pos) && ++(*pos))
  491. return TK(BARBAR);
  492. else if (strncmp(&source[*pos], "&&", 2) == 0 && ++(*pos) && ++(*pos))
  493. return TK(ANDAND);
  494. else if (strncmp(&source[*pos], "++", 2) == 0 && ++(*pos) && ++(*pos))
  495. return TK(PLUSPLUS);
  496. else if (strncmp(&source[*pos], "--", 2) == 0 && ++(*pos) && ++(*pos))
  497. return TK(MINUSMINUS);
  498. else if (strncmp(&source[*pos], "//", 2) == 0 && ++(*pos) && ++(*pos))
  499. return TK(SLASHSLASH);
  500. else if (strncmp(&source[*pos], "**", 2) == 0 && ++(*pos) && ++(*pos))
  501. return TK(STARSTAR);
  502. else if (strncmp(&source[*pos], "<<", 2) == 0 && ++(*pos) && ++(*pos))
  503. return TK(LTLT);
  504. else if (strncmp(&source[*pos], ">>", 2) == 0 && ++(*pos) && ++(*pos))
  505. return TK(GTGT);
  506. else if (strncmp(&source[*pos], "<=", 2) == 0 && ++(*pos) && ++(*pos))
  507. return TK(LE);
  508. else if (strncmp(&source[*pos], ">=", 2) == 0 && ++(*pos) && ++(*pos))
  509. return TK(GE);
  510. else if (source[*pos] == '(' && ++(*pos))
  511. return TK(LPAR);
  512. else if (source[*pos] == ')' && ++(*pos))
  513. return TK(RPAR);
  514. else if (source[*pos] == '[' && ++(*pos))
  515. return TK(LSB);
  516. else if (source[*pos] == ']' && ++(*pos))
  517. return TK(RSB);
  518. else if (source[*pos] == '{' && ++(*pos))
  519. return TK(LCB);
  520. else if (source[*pos] == '}' && ++(*pos))
  521. return TK(RCB);
  522. else if (source[*pos] == '+' && ++(*pos))
  523. return TK(PLUS);
  524. else if (source[*pos] == '-' && ++(*pos))
  525. return TK(MINUS);
  526. else if (source[*pos] == '*' && ++(*pos))
  527. return TK(STAR);
  528. else if (source[*pos] == '/' && ++(*pos))
  529. return TK(SLASH);
  530. else if (source[*pos] == '%' && ++(*pos))
  531. return TK(PERCENT);
  532. else if (source[*pos] == '?' && ++(*pos))
  533. return TK(QM);
  534. else if (source[*pos] == ':' && ++(*pos))
  535. return TK(COLON);
  536. else if (source[*pos] == '=' && ++(*pos))
  537. return TK(ASSIGN);
  538. else if (source[*pos] == ';' && ++(*pos))
  539. return TK(SEMI);
  540. else if (source[*pos] == ',' && ++(*pos))
  541. return TK(COMMA);
  542. else if (source[*pos] == '.' && ++(*pos))
  543. return TK(DOT);
  544. else if (source[*pos] == '<' && ++(*pos))
  545. return TK(LT);
  546. else if (source[*pos] == '>' && ++(*pos))
  547. return TK(GT);
  548. else if (source[*pos] == '!' && ++(*pos))
  549. return TK(BANG);
  550. else if (source[*pos] == '|' && ++(*pos))
  551. return TK(BAR);
  552. else if (source[*pos] == '&' && ++(*pos))
  553. return TK(AND);
  554. else if (source[*pos] == '^' && ++(*pos))
  555. return TK(RAISE);
  556. else if (source[*pos] == '~' && ++(*pos))
  557. return TK(TILDE);
  558. LEX_ERROR("unexpected input")
  559. }
  560. list_t *tokenize(char *source) {
  561. size_t pos = 0;
  562. list_t *toks = list_new();
  563. do {
  564. consume_ignored(source, &pos);
  565. size_t tok_pos = pos;
  566. token_t *tok = next_token(source, &pos);
  567. tok->fi = FILES->length-1;
  568. tok->pos = tok_pos;
  569. list_push(toks, tok);
  570. if (tok->tag == T_EOF)
  571. break;
  572. } while (1);
  573. return toks;
  574. }
  575. struct _node_t {
  576. enum {
  577. N_TOPLEVEL,
  578. N_PROGRAM,
  579. N_EXPRSTMT,
  580. N_BLOCK,
  581. N_NOT,
  582. N_NEGATE,
  583. N_BNOT,
  584. N_LITERAL,
  585. N_LIST,
  586. N_TUPLE,
  587. N_NILTUPLE,
  588. N_TABLE,
  589. N_CALL,
  590. N_MEMBER,
  591. N_INDEX,
  592. N_ADD,
  593. N_SUB,
  594. N_MUL,
  595. N_DIV,
  596. N_IDIV,
  597. N_MOD,
  598. N_POW,
  599. N_SHL,
  600. N_SHR,
  601. N_XOR,
  602. N_BOR,
  603. N_BAND,
  604. N_ASSIGN,
  605. N_ASSIGN_ADD,
  606. N_ASSIGN_SUB,
  607. N_ASSIGN_MUL,
  608. N_ASSIGN_DIV,
  609. N_ASSIGN_IDIV,
  610. N_ASSIGN_MOD,
  611. N_ASSIGN_POW,
  612. N_EQUALS,
  613. N_NOTEQUALS,
  614. N_IS,
  615. N_IN,
  616. N_NOTIS,
  617. N_NOTIN,
  618. N_LT,
  619. N_GT,
  620. N_LE,
  621. N_GE,
  622. N_INC,
  623. N_DEC,
  624. N_VAR,
  625. N_LET,
  626. N_CONST,
  627. N_IF,
  628. N_SWITCH,
  629. N_FOR,
  630. N_FOROF,
  631. N_FOROFVAR,
  632. N_BREAK,
  633. N_CONTINUE,
  634. N_FUNCDEF,
  635. N_RETURN,
  636. N_DEFER,
  637. N_PASS,
  638. N_REQUIRE,
  639. N_TRY,
  640. N_THROW,
  641. N_LABEL,
  642. N_GOTO,
  643. N_CLASS,
  644. N_INLINE,
  645. N_IFEXPR,
  646. N_FUNCEXPR,
  647. N_LOGOR,
  648. N_LOGAND,
  649. } tag;
  650. struct _node_t *a;
  651. struct _node_t *b;
  652. struct _node_t *c;
  653. struct _node_t *d;
  654. list_t *l;
  655. table_t *h;
  656. table_t *h2;
  657. token_t *t;
  658. size_t fi;
  659. size_t pos;
  660. };
  661. typedef struct _node_t node_t;
  662. node_t *node_pos(node_t *node, size_t fi, size_t pos) {
  663. node->fi = fi;
  664. node->pos = pos;
  665. return node;
  666. }
  667. node_t *nodet(int tag, token_t *t) {
  668. node_t *node = malloc(sizeof(node_t));
  669. node->tag = tag;
  670. node->t = t;
  671. return node;
  672. }
  673. #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))
  674. node_t *nodel(int tag, list_t *l) {
  675. node_t *node = malloc(sizeof(node_t));
  676. node->tag = tag;
  677. node->l = l;
  678. return node;
  679. }
  680. #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))
  681. node_t *nodetl(int tag, token_t *t, list_t *l) {
  682. node_t *node = malloc(sizeof(node_t));
  683. node->tag = tag;
  684. node->t = t;
  685. node->l = l;
  686. return node;
  687. }
  688. #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))
  689. node_t *nodeh(int tag, table_t *h) {
  690. node_t *node = malloc(sizeof(node_t));
  691. node->tag = tag;
  692. node->h = h;
  693. return node;
  694. }
  695. #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))
  696. node_t *node0(int tag) {
  697. node_t *node = malloc(sizeof(node_t));
  698. node->tag = tag;
  699. return node;
  700. }
  701. #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))
  702. node_t *node1(int tag, node_t *a) {
  703. node_t *node = malloc(sizeof(node_t));
  704. node->tag = tag;
  705. node->a = a;
  706. return node;
  707. }
  708. #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))
  709. node_t *node1l(int tag, node_t *a, list_t *l) {
  710. node_t *node = malloc(sizeof(node_t));
  711. node->tag = tag;
  712. node->a = a;
  713. node->l = l;
  714. return node;
  715. }
  716. #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))
  717. node_t *node1t(int tag, node_t *a, token_t *t) {
  718. node_t *node = malloc(sizeof(node_t));
  719. node->tag = tag;
  720. node->a = a;
  721. node->t = t;
  722. return node;
  723. }
  724. #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))
  725. node_t *node2(int tag, node_t *a, node_t *b) {
  726. node_t *node = malloc(sizeof(node_t));
  727. node->tag = tag;
  728. node->a = a;
  729. node->b = b;
  730. return node;
  731. }
  732. #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))
  733. node_t *node2l(int tag, node_t *a, node_t *b, list_t *l) {
  734. node_t *node = malloc(sizeof(node_t));
  735. node->tag = tag;
  736. node->a = a;
  737. node->b = b;
  738. node->l = l;
  739. return node;
  740. }
  741. #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))
  742. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t) {
  743. node_t *node = malloc(sizeof(node_t));
  744. node->tag = tag;
  745. node->a = a;
  746. node->b = b;
  747. node->t = t;
  748. return node;
  749. }
  750. #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))
  751. node_t *node3(int tag, node_t *a, node_t *b, node_t *c) {
  752. node_t *node = malloc(sizeof(node_t));
  753. node->tag = tag;
  754. node->a = a;
  755. node->b = b;
  756. node->c = c;
  757. return node;
  758. }
  759. #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))
  760. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d) {
  761. node_t *node = malloc(sizeof(node_t));
  762. node->tag = tag;
  763. node->a = a;
  764. node->b = b;
  765. node->c = c;
  766. node->d = d;
  767. return node;
  768. }
  769. #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))
  770. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured, node_t *body) {
  771. node_t *node = malloc(sizeof(node_t));
  772. node->tag = tag;
  773. node->t = name;
  774. node->h = params;
  775. node->h2 = captured;
  776. node->a = body;
  777. return node;
  778. }
  779. #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))
  780. #define AT(tk) (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  781. #define ATP(tk, p) ((*pos)+p < tokens->length && ((token_t *)tokens->data[(*pos)+p])->tag == T_##tk)
  782. #define MATCH(tk) (AT(tk) && ++(*pos))
  783. #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); }
  784. #define EXPECT(tk, s) { if (!MATCH(tk)) PARSE_ERROR("expected %s", (s)); }
  785. node_t *parse_expr(list_t *tokens, size_t *pos);
  786. list_t *parse_sequence(list_t *tokens, size_t *pos, int term) {
  787. list_t *seq = list_new();
  788. do {
  789. if (term != -1 && *pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == term)
  790. break;
  791. list_push(seq, parse_expr(tokens, pos));
  792. } while (MATCH(COMMA));
  793. return seq;
  794. }
  795. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  796. node_t *parse_primary(list_t *tokens, size_t *pos) {
  797. if (MATCH(FUNC))
  798. return parse_func(tokens, pos, 1);
  799. else if (MATCH(LPAR)) {
  800. if (MATCH(RPAR))
  801. return NODE0(NILTUPLE);
  802. node_t *a = parse_expr(tokens, pos);
  803. if (MATCH(COMMA)) {
  804. list_t *l = list_new();
  805. list_push(l, a);
  806. if (!AT(RPAR))
  807. do {
  808. node_t *n = parse_expr(tokens, pos);
  809. list_push(l, n);
  810. } while (MATCH(COMMA));
  811. a = NODEL(TUPLE, l);
  812. }
  813. EXPECT(RPAR, ")");
  814. return a;
  815. } else if (MATCH(LSB)) {
  816. list_t *a = parse_sequence(tokens, pos, T_RSB);
  817. EXPECT(RSB, "]");
  818. return NODEL(LIST, a);
  819. } else if (MATCH(LCB)) {
  820. table_t *table = table_new();
  821. do {
  822. if (AT(RCB))
  823. break;
  824. if (!AT(NAME) && !AT(STRING))
  825. PARSE_ERROR("expected identifier or string");
  826. char *key = ((token_t *)tokens->data[(*pos)++])->text;
  827. EXPECT(COLON, ":");
  828. node_t *val = parse_expr(tokens, pos);
  829. table_set(table, key, val);
  830. } while (MATCH(COMMA));
  831. EXPECT(RCB, "}");
  832. return NODEH(TABLE, table);
  833. } else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(NAME))
  834. return NODET(LITERAL, tokens->data[(*pos)-1]);
  835. PARSE_ERROR("expected expression");
  836. return NULL;
  837. }
  838. size_t get_lineno(token_t *tok) {
  839. size_t line, col;
  840. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  841. return line;
  842. }
  843. #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)])))
  844. #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])))
  845. node_t *parse_call(list_t *tokens, size_t *pos) {
  846. node_t *a = parse_primary(tokens, pos);
  847. do {
  848. if (!CLIFF && MATCH(LPAR)) {
  849. list_t *b = NULL;
  850. if (!AT(RPAR))
  851. b = parse_sequence(tokens, pos, -1);
  852. EXPECT(RPAR, ")");
  853. a = NODE1l(CALL, a, b);
  854. continue;
  855. } else if (!CLIFF && MATCH(LSB)) {
  856. node_t *b = parse_expr(tokens, pos);
  857. EXPECT(RSB, "]");
  858. a = NODE2(INDEX, a, b);
  859. continue;
  860. } else if (!CLIFF && MATCH(DOT)) {
  861. if (!AT(NAME))
  862. PARSE_ERROR("expected identifier after .");
  863. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  864. continue;
  865. }
  866. break;
  867. } while (1);
  868. return a;
  869. }
  870. node_t *parse_postfix(list_t *tokens, size_t *pos) {
  871. node_t *a = parse_call(tokens, pos);
  872. if (CLIFF)
  873. return a;
  874. if (MATCH(PLUSPLUS))
  875. return NODE1(INC, a);
  876. else if (MATCH(MINUSMINUS))
  877. return NODE1(DEC, a);
  878. return a;
  879. }
  880. node_t *parse_unary(list_t *tokens, size_t *pos) {
  881. if (MATCH(MINUS)) {
  882. node_t *a = parse_unary(tokens, pos);
  883. return NODE1(NEGATE, a);
  884. } else if (MATCH(BANG)) {
  885. node_t *a = parse_unary(tokens, pos);
  886. return NODE1(NOT, a);
  887. } else if (MATCH(TILDE)) {
  888. node_t *a = parse_unary(tokens, pos);
  889. return NODE1(BNOT, a);
  890. }
  891. return parse_postfix(tokens, pos);
  892. }
  893. node_t *parse_pow(list_t *tokens, size_t *pos) {
  894. node_t *a = parse_unary(tokens, pos);
  895. do {
  896. if (MATCH(STARSTAR)) {
  897. node_t *b = parse_unary(tokens, pos);
  898. a = NODE2(POW, a, b);
  899. continue;
  900. }
  901. break;
  902. } while (1);
  903. return a;
  904. }
  905. node_t *parse_mul(list_t *tokens, size_t *pos) {
  906. node_t *a = parse_pow(tokens, pos);
  907. do {
  908. if (MATCH(STAR)) {
  909. node_t *b = parse_pow(tokens, pos);
  910. a = NODE2(MUL, a, b);
  911. continue;
  912. } else if (MATCH(SLASH)) {
  913. node_t *b = parse_pow(tokens, pos);
  914. a = NODE2(DIV, a, b);
  915. continue;
  916. } else if (MATCH(SLASHSLASH)) {
  917. node_t *b = parse_pow(tokens, pos);
  918. a = NODE2(IDIV, a, b);
  919. continue;
  920. } else if (MATCH(PERCENT)) {
  921. node_t *b = parse_pow(tokens, pos);
  922. a = NODE2(MOD, a, b);
  923. continue;
  924. }
  925. break;
  926. } while (1);
  927. return a;
  928. }
  929. node_t *parse_add(list_t *tokens, size_t *pos) {
  930. node_t *a = parse_mul(tokens, pos);
  931. do {
  932. if (MATCH(PLUS)) {
  933. node_t *b = parse_mul(tokens, pos);
  934. a = NODE2(ADD, a, b);
  935. continue;
  936. } else if (MATCH(MINUS)) {
  937. node_t *b = parse_mul(tokens, pos);
  938. a = NODE2(SUB, a, b);
  939. continue;
  940. }
  941. break;
  942. } while (1);
  943. return a;
  944. }
  945. node_t *parse_shift(list_t *tokens, size_t *pos) {
  946. node_t *a = parse_add(tokens, pos);
  947. do {
  948. if (MATCH(LTLT)) {
  949. node_t *b = parse_add(tokens, pos);
  950. a = NODE2(SHL, a, b);
  951. continue;
  952. } else if (MATCH(GTGT)) {
  953. node_t *b = parse_add(tokens, pos);
  954. a = NODE2(SHR, a, b);
  955. continue;
  956. }
  957. break;
  958. } while (1);
  959. return a;
  960. }
  961. node_t *parse_relation(list_t *tokens, size_t *pos) {
  962. node_t *a = parse_shift(tokens, pos);
  963. do {
  964. if (MATCH(LT)) {
  965. node_t *b = parse_shift(tokens, pos);
  966. a = NODE2(LT, a, b);
  967. continue;
  968. } else if (MATCH(GT)) {
  969. node_t *b = parse_shift(tokens, pos);
  970. a = NODE2(GT, a, b);
  971. continue;
  972. } else if (MATCH(LE)) {
  973. node_t *b = parse_shift(tokens, pos);
  974. a = NODE2(LE, a, b);
  975. continue;
  976. } else if (MATCH(GE)) {
  977. node_t *b = parse_shift(tokens, pos);
  978. a = NODE2(GE, a, b);
  979. continue;
  980. }
  981. break;
  982. } while (1);
  983. return a;
  984. }
  985. node_t *parse_equality(list_t *tokens, size_t *pos) {
  986. node_t *a = parse_relation(tokens, pos);
  987. do {
  988. if (MATCH(EQUALS)) {
  989. node_t *b = parse_relation(tokens, pos);
  990. a = NODE2(EQUALS, a, b);
  991. continue;
  992. } else if (MATCH(NOTEQUALS)) {
  993. node_t *b = parse_relation(tokens, pos);
  994. a = NODE2(NOTEQUALS, a, b);
  995. continue;
  996. } else if (MATCH(IS)) {
  997. node_t *b = parse_relation(tokens, pos);
  998. a = NODE2(IS, a, b);
  999. continue;
  1000. } else if (AT(BANG) && ATP(IS, 1)) {
  1001. EXPECT(BANG, "!");
  1002. EXPECT(IS, "is");
  1003. node_t *b = parse_relation(tokens, pos);
  1004. a = NODE2(NOTIS, a, b);
  1005. continue;
  1006. } else if (MATCH(IN)) {
  1007. node_t *b = parse_relation(tokens, pos);
  1008. a = NODE2(IN, a, b);
  1009. continue;
  1010. } else if (AT(BANG) && ATP(IN, 1)) {
  1011. EXPECT(BANG, "!");
  1012. EXPECT(IN, "in");
  1013. node_t *b = parse_relation(tokens, pos);
  1014. a = NODE2(NOTIN, a, b);
  1015. continue;
  1016. }
  1017. break;
  1018. } while (1);
  1019. return a;
  1020. }
  1021. node_t *parse_bitand(list_t *tokens, size_t *pos) {
  1022. node_t *a = parse_equality(tokens, pos);
  1023. while (MATCH(AND)) {
  1024. node_t *b = parse_equality(tokens, pos);
  1025. a = NODE2(BAND, a, b);
  1026. }
  1027. return a;
  1028. }
  1029. node_t *parse_bitxor(list_t *tokens, size_t *pos) {
  1030. node_t *a = parse_bitand(tokens, pos);
  1031. while (MATCH(RAISE)) {
  1032. node_t *b = parse_bitand(tokens, pos);
  1033. a = NODE2(XOR, a, b);
  1034. }
  1035. return a;
  1036. }
  1037. node_t *parse_bitor(list_t *tokens, size_t *pos) {
  1038. node_t *a = parse_bitxor(tokens, pos);
  1039. while (MATCH(BAR)) {
  1040. node_t *b = parse_bitxor(tokens, pos);
  1041. a = NODE2(BOR, a, b);
  1042. }
  1043. return a;
  1044. }
  1045. node_t *parse_logand(list_t *tokens, size_t *pos) {
  1046. node_t *a = parse_bitor(tokens, pos);
  1047. if (MATCH(ANDAND)) {
  1048. node_t *b = parse_logand(tokens, pos);
  1049. return NODE2(LOGAND, a, b);
  1050. }
  1051. return a;
  1052. }
  1053. node_t *parse_logor(list_t *tokens, size_t *pos) {
  1054. node_t *a = parse_logand(tokens, pos);
  1055. if (MATCH(BARBAR)) {
  1056. node_t *b = parse_logor(tokens, pos);
  1057. return NODE2(LOGOR, a, b);
  1058. }
  1059. return a;
  1060. }
  1061. node_t *parse_assignment(list_t *tokens, size_t *pos);
  1062. node_t *parse_conditional(list_t *tokens, size_t *pos) {
  1063. node_t *a = parse_logor(tokens, pos);
  1064. if (MATCH(QM)) {
  1065. node_t *b = parse_assignment(tokens, pos);
  1066. EXPECT(COLON, ":");
  1067. node_t *c = parse_assignment(tokens, pos);
  1068. return NODE3(IFEXPR, a, b, c);
  1069. }
  1070. return a;
  1071. }
  1072. node_t *parse_assignment(list_t *tokens, size_t *pos) {
  1073. node_t *a = parse_conditional(tokens, pos);
  1074. if (MATCH(ASSIGN)) {
  1075. node_t *b = parse_assignment(tokens, pos);
  1076. return NODE2(ASSIGN, a, b);
  1077. } else if (MATCH(PLUSASSIGN)) {
  1078. node_t *b = parse_assignment(tokens, pos);
  1079. return NODE2(ASSIGN_ADD, a, b);
  1080. } else if (MATCH(MINUSASSIGN)) {
  1081. node_t *b = parse_assignment(tokens, pos);
  1082. return NODE2(ASSIGN_SUB, a, b);
  1083. } else if (MATCH(STARASSIGN)) {
  1084. node_t *b = parse_assignment(tokens, pos);
  1085. return NODE2(ASSIGN_MUL, a, b);
  1086. } else if (MATCH(SLASHASSIGN)) {
  1087. node_t *b = parse_assignment(tokens, pos);
  1088. return NODE2(ASSIGN_DIV, a, b);
  1089. } else if (MATCH(SLASHSLASHASSIGN)) {
  1090. node_t *b = parse_assignment(tokens, pos);
  1091. return NODE2(ASSIGN_IDIV, a, b);
  1092. } else if (MATCH(PERCENTASSIGN)) {
  1093. node_t *b = parse_assignment(tokens, pos);
  1094. return NODE2(ASSIGN_MOD, a, b);
  1095. }
  1096. return a;
  1097. }
  1098. node_t *parse_expr(list_t *tokens, size_t *pos) {
  1099. return parse_assignment(tokens, pos);
  1100. }
  1101. node_t *parse_stmt(list_t *tokens, size_t *pos);
  1102. node_t *parse_block(list_t *tokens, size_t *pos) {
  1103. EXPECT(LCB, "{");
  1104. list_t *stmts = list_new();
  1105. while (!AT(EOF) && !AT(RCB))
  1106. list_push(stmts, parse_stmt(tokens, pos));
  1107. EXPECT(RCB, "}");
  1108. return NODEL(PROGRAM, stmts);
  1109. }
  1110. #define BLOCK() (CLIFF||MATCH(COLON)?parse_stmt(tokens, pos):parse_block(tokens, pos))
  1111. node_t *parse_if(list_t *tokens, size_t *pos) {
  1112. node_t *a = parse_expr(tokens, pos);
  1113. node_t *b = BLOCK();
  1114. node_t *c = NULL;
  1115. if (MATCH(ELSE))
  1116. c = BLOCK();
  1117. else if (MATCH(ELIF))
  1118. c = parse_if(tokens, pos);
  1119. return NODE3(IF, a, b, c);
  1120. }
  1121. node_t *parse_var(list_t *tokens, size_t *pos, int is_let) {
  1122. table_t *h = table_new();
  1123. do {
  1124. if(!AT(NAME))
  1125. PARSE_ERROR("expected identifier");
  1126. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1127. node_t *v = NULL;
  1128. if (is_let) {
  1129. EXPECT(ASSIGN, "=");
  1130. v = parse_expr(tokens, pos);
  1131. } else if (MATCH(ASSIGN))
  1132. v = parse_expr(tokens, pos);
  1133. table_set(h, k, v);
  1134. } while (MATCH(COMMA));
  1135. if (is_let)
  1136. return NODEH(LET, h);
  1137. return NODEH(VAR, h);
  1138. }
  1139. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr) {
  1140. token_t *name = NULL;
  1141. if (!is_expr) {
  1142. if(!AT(NAME))
  1143. PARSE_ERROR("expected identifier");
  1144. name = tokens->data[(*pos)++];
  1145. }
  1146. EXPECT(LPAR, "(");
  1147. table_t *params = NULL;
  1148. if (!AT(RPAR)) {
  1149. int flag = 0;
  1150. params = table_new();
  1151. size_t argc = 0;
  1152. do {
  1153. if(!AT(NAME))
  1154. PARSE_ERROR("expected identifier");
  1155. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  1156. node_t *r = NULL;
  1157. if (!flag && AT(ASSIGN))
  1158. flag = 1;
  1159. if (flag) {
  1160. EXPECT(ASSIGN, "=");
  1161. r = parse_expr(tokens, pos);
  1162. }
  1163. list_t *pair = list_new();
  1164. size_t *argcp = malloc(sizeof(size_t));
  1165. memcpy(argcp, &argc, sizeof(size_t));
  1166. argc++;
  1167. list_push(pair, argcp);
  1168. list_push(pair, r);
  1169. table_set(params, l, pair);
  1170. } while (MATCH(COMMA));
  1171. }
  1172. EXPECT(RPAR, ")");
  1173. table_t *captured = NULL;
  1174. if (MATCH(USE)) {
  1175. EXPECT(LPAR, "(");
  1176. captured = table_new();
  1177. do {
  1178. if(!AT(NAME))
  1179. PARSE_ERROR("expected identifier");
  1180. token_t *name = tokens->data[(*pos)++];
  1181. table_set(captured, name->text, NODET(LITERAL, name));
  1182. } while (MATCH(COMMA));
  1183. EXPECT(RPAR, ")");
  1184. }
  1185. int colon = AT(COLON);
  1186. node_t *body = BLOCK();
  1187. if (colon && body->tag == N_EXPRSTMT)
  1188. body = NODE1(RETURN, body->a);
  1189. if (is_expr)
  1190. return NODEF(FUNCEXPR, NULL, params, captured, body);
  1191. return NODEF(FUNCDEF, name, params, captured, body);
  1192. }
  1193. node_t *parse_stmt(list_t *tokens, size_t *pos) {
  1194. if (MATCH(LCB)) {
  1195. list_t *stmts = list_new();
  1196. while (!AT(EOF) && !AT(RCB)) {
  1197. node_t *n = parse_stmt(tokens, pos);
  1198. MATCH(SEMI);
  1199. list_push(stmts, n);
  1200. }
  1201. EXPECT(RCB, "}");
  1202. return NODEL(BLOCK, stmts);
  1203. } else if (MATCH(VAR))
  1204. return parse_var(tokens, pos, 0);
  1205. else if (MATCH(LET))
  1206. return parse_var(tokens, pos, 1);
  1207. else if (MATCH(CONST)) {
  1208. table_t *h = table_new();
  1209. do {
  1210. if(!AT(NAME))
  1211. PARSE_ERROR("expected identifier");
  1212. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  1213. if (!(k[0] >= 'A' && k[0] <= 'Z'))
  1214. PARSE_ERROR("compile-time constant identifiers must begin with an uppercase letter, but '%s' does not", k);
  1215. if (table_get(h, k))
  1216. PARSE_ERROR("duplicated compile-time constant definition: '%s'", k);
  1217. EXPECT(ASSIGN, "=");
  1218. node_t *v = parse_expr(tokens, pos);
  1219. table_set(h, k, v);
  1220. } while (MATCH(COMMA));
  1221. return NODEH(CONST, h);
  1222. } else if (MATCH(IF))
  1223. return parse_if(tokens, pos);
  1224. else if (MATCH(SWITCH)) {
  1225. node_t *a = parse_expr(tokens, pos);
  1226. EXPECT(LCB, "{");
  1227. list_t *cases = list_new();
  1228. for (;;) {
  1229. if (AT(RCB) || AT(DEFAULT)) break;
  1230. EXPECT(CASE, "case");
  1231. node_t *expr = parse_expr(tokens, pos);
  1232. MATCH(COLON);
  1233. list_t *stmts = list_new();
  1234. while (!AT(CASE) && !AT(DEFAULT) && !AT(RCB))
  1235. list_push(stmts, parse_stmt(tokens, pos));
  1236. list_t *pair = list_new();
  1237. list_push(pair, expr);
  1238. list_push(pair, NODEL(PROGRAM, stmts));
  1239. list_push(cases, pair);
  1240. }
  1241. node_t *b = NULL;
  1242. if (MATCH(DEFAULT)) {
  1243. MATCH(COLON);
  1244. list_t *stmts = list_new();
  1245. while (!AT(RCB))
  1246. list_push(stmts, parse_stmt(tokens, pos));
  1247. b = NODEL(PROGRAM, stmts);
  1248. }
  1249. EXPECT(RCB, "}");
  1250. if (!cases->length && !b)
  1251. PARSE_ERROR("empty switch statement");
  1252. return NODE2l(SWITCH, a, b, cases);
  1253. } else if (MATCH(FOR)) {
  1254. node_t *a = NULL;
  1255. node_t *b = NULL;
  1256. node_t *c = NULL;
  1257. if (!AT(LCB) && !AT(COLON) && !CLIFF) {
  1258. if (AT(NAME) && ATP(OF, 1)) {
  1259. token_t *t = tokens->data[(*pos)++];
  1260. EXPECT(OF, "of");
  1261. a = parse_expr(tokens, pos);
  1262. b = BLOCK();
  1263. return NODE2t(FOROF, a, b, t);
  1264. }
  1265. if (MATCH(VAR)) {
  1266. if (AT(NAME) && ATP(OF, 1)) {
  1267. token_t *t = tokens->data[(*pos)++];
  1268. EXPECT(OF, "of");
  1269. a = parse_expr(tokens, pos);
  1270. b = BLOCK();
  1271. return NODE2t(FOROFVAR, a, b, t);
  1272. }
  1273. a = parse_var(tokens, pos, 0);
  1274. EXPECT(SEMI, ";");
  1275. b = parse_expr(tokens, pos);
  1276. EXPECT(SEMI, ";");
  1277. c = parse_expr(tokens, pos);
  1278. } else a = parse_expr(tokens, pos);
  1279. }
  1280. node_t *d = BLOCK();
  1281. return NODE4(FOR, a, b, c, d);
  1282. } else if (MATCH(BREAK)) return NODE0(BREAK);
  1283. else if (MATCH(CONTINUE)) return NODE0(CONTINUE);
  1284. else if (MATCH(FUNC))
  1285. return parse_func(tokens, pos, 0);
  1286. else if (MATCH(RETURN)) {
  1287. node_t *a = NULL;
  1288. if (!AT(RCB) && !AT(EOF) && !CLIFF)
  1289. a = parse_expr(tokens, pos);
  1290. return NODE1(RETURN, a);
  1291. } else if (MATCH(DEFER)) {
  1292. node_t *a;
  1293. if (AT(LCB))
  1294. a = BLOCK();
  1295. else a = parse_stmt(tokens, pos);
  1296. return NODE1(DEFER, a);
  1297. } else if (MATCH(PASS)) return NODE0(PASS);
  1298. else if (MATCH(TRY)) {
  1299. node_t *a = BLOCK();
  1300. token_t *t = NULL;
  1301. EXPECT(CATCH, "catch");
  1302. if (!AT(COLON) && !AT(LCB) && !CLIFF) {
  1303. if (!AT(NAME))
  1304. PARSE_ERROR("expected identifier");
  1305. t = tokens->data[(*pos)++];
  1306. }
  1307. node_t *b = BLOCK();
  1308. return NODE2t(TRY, a, b, t);
  1309. } else if (MATCH(THROW)) {
  1310. node_t *a = NULL;
  1311. if (!CLIFF)
  1312. a = parse_expr(tokens, pos);
  1313. return NODE1(THROW, a);
  1314. } else if (MATCH(GOTO)) {
  1315. if(!AT(NAME))
  1316. PARSE_ERROR("expected identifier");
  1317. token_t *t = tokens->data[(*pos)++];
  1318. return NODET(GOTO, t);
  1319. } else if (AT(NAME) && ATP(COLON, 1) && !CLIFF_AHEAD) {
  1320. token_t *t = tokens->data[(*pos)++];
  1321. EXPECT(COLON, ":");
  1322. return NODET(LABEL, t);
  1323. } else if (MATCH(CLASS)) {
  1324. if(!AT(NAME))
  1325. PARSE_ERROR("expected identifier");
  1326. token_t *t = tokens->data[(*pos)++];
  1327. list_t *l = NULL;
  1328. if (MATCH(LPAR)) {
  1329. l = list_new();
  1330. do {
  1331. if(!AT(NAME))
  1332. PARSE_ERROR("expected identifier");
  1333. token_t *t = tokens->data[(*pos)++];
  1334. list_push(l, t);
  1335. } while (MATCH(COMMA));
  1336. EXPECT(RPAR, ")");
  1337. }
  1338. EXPECT(LCB, "{");
  1339. list_t *triples = list_new();
  1340. for (;;) {
  1341. if (!AT(NAME))
  1342. break;
  1343. list_t *triple = list_new();
  1344. token_t *t = tokens->data[(*pos)++];
  1345. list_push(triple, t);
  1346. if (MATCH(ASSIGN)) {
  1347. list_push(triple, t);
  1348. list_push(triple, parse_expr(tokens, pos));
  1349. } else {
  1350. list_push(triple, NULL);
  1351. list_push(triple, parse_func(tokens, pos, 1));
  1352. }
  1353. list_push(triples, triple);
  1354. }
  1355. EXPECT(RCB, "}");
  1356. list_t *pair = list_new();
  1357. list_push(pair, l);
  1358. list_push(pair, triples);
  1359. return NODETL(CLASS, t, pair);
  1360. } else if (MATCH(INLINE)) {
  1361. if (!AT(STRING))
  1362. PARSE_ERROR("expected string");
  1363. token_t *t = tokens->data[(*pos)++];
  1364. return NODET(INLINE, t);
  1365. }
  1366. node_t *n = parse_expr(tokens, pos);
  1367. return NODE1(EXPRSTMT, n);
  1368. }
  1369. node_t *parse_program(list_t *tokens, size_t *pos) {
  1370. if (AT(EOF))
  1371. PARSE_ERROR("empty program");
  1372. list_t *stmts = list_new();
  1373. int flag = 0;
  1374. while (!AT(EOF) && *pos < tokens->length) {
  1375. node_t *n;
  1376. if (MATCH(REQUIRE)) {
  1377. if (flag)
  1378. PARSE_ERROR("misplaced require statement")
  1379. if (!AT(STRING))
  1380. PARSE_ERROR("expected string");
  1381. token_t *path = tokens->data[(*pos)++];
  1382. n = NODET(REQUIRE, path);
  1383. } else { n = parse_stmt(tokens, pos); flag = 1; }
  1384. MATCH(SEMI);
  1385. list_push(stmts, n);
  1386. }
  1387. return NODEL(TOPLEVEL, stmts);
  1388. }
  1389. node_t *parse(char *source) {
  1390. size_t pos = 0;
  1391. return parse_program(tokenize(source), &pos);
  1392. }
  1393. #define NEWGID() size_t gid = GID++
  1394. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  1395. #define BINOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, lstk, lbl, node->a); EMIT(", "); compile_node(gbuf, buf, ctx, lstk, lbl, node->b); EMIT(")"); }
  1396. #define UNOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, lstk, lbl, node->a); EMIT(")"); }
  1397. #define ASSIGN(lhs, rhs) {\
  1398. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) {\
  1399. EMIT("qi_set(state, false, \"%s\", ", (lhs)->t->text);\
  1400. rhs;\
  1401. EMIT(")");\
  1402. } else if ((lhs)->tag == N_INDEX) {\
  1403. EMIT("qi_index_set(state, false, ");\
  1404. compile_node(gbuf, buf, ctx, lstk, lbl, (lhs)->a);\
  1405. EMIT(", ");\
  1406. compile_node(gbuf, buf, ctx, lstk, lbl, (lhs)->b);\
  1407. EMIT(", ");\
  1408. rhs;\
  1409. EMIT(")");\
  1410. } else if ((lhs)->tag == N_MEMBER) {\
  1411. EMIT("qi_index_set(state, false, ");\
  1412. compile_node(gbuf, buf, ctx, lstk, lbl, (lhs)->a);\
  1413. EMIT(", qi_make_string(state, \"%s\"), ", (lhs)->t->text);\
  1414. rhs;\
  1415. EMIT(")");\
  1416. } else COMPILE_ERROR("illegal assignment left-hand side");\
  1417. }
  1418. #define COMPASSIGN(lhs, s, rhs) {\
  1419. ASSIGN(node->a, {\
  1420. EMIT("qi_%s(state, ", s);\
  1421. compile_node(gbuf, buf, ctx, lstk, lbl, (lhs));\
  1422. EMIT(", ");\
  1423. rhs;\
  1424. EMIT(")");\
  1425. });\
  1426. }
  1427. #define COMPILE_ERROR(fmt, ...) { format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, ##__VA_ARGS__); exit(1); }
  1428. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, node_t *node);
  1429. void compile_list(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, list_t *seq) {
  1430. if (!seq || seq->length < 1) {
  1431. EMIT("NULL");
  1432. return;
  1433. }
  1434. buffer_t *tbuf = buffer_new();
  1435. NEWGID();
  1436. buffer_fmt(tbuf, "inline static qi_list_t *__list%d(qi_state_t *state) {\n", gid);
  1437. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make_n(%d);\n", seq->length);
  1438. for (size_t i = 0; i < seq->length; i++) {
  1439. buffer_fmt(tbuf, "qi_list_data(list, %d) = ", i);
  1440. compile_node(gbuf, tbuf, ctx, lstk, lbl, seq->data[i]);
  1441. buffer_fmt(tbuf, ";\n");
  1442. }
  1443. buffer_fmt(tbuf, "return list;\n");
  1444. buffer_fmt(tbuf, "}\n");
  1445. buffer_appendb(gbuf, tbuf);
  1446. EMIT("__list%d(state)", gid);
  1447. }
  1448. void compile_table(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, table_t *table) {
  1449. if (!table || table->used < 1) {
  1450. EMIT("NULL");
  1451. return;
  1452. }
  1453. buffer_t *tbuf = buffer_new();
  1454. NEWGID();
  1455. buffer_fmt(tbuf, "inline static qi_table_t *__table%d(qi_state_t *state) {\n", gid);
  1456. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  1457. table_iterate(table, {
  1458. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  1459. compile_node(gbuf, tbuf, ctx, lstk, lbl, entry.value);
  1460. buffer_fmt(tbuf, ");\n");
  1461. });
  1462. buffer_fmt(tbuf, "return table;\n");
  1463. buffer_fmt(tbuf, "}\n");
  1464. buffer_appendb(gbuf, tbuf);
  1465. EMIT("__table%d(state)", gid);
  1466. }
  1467. #define CTXPUSH(s) list_push(ctx, (s))
  1468. #define CTXPOP() list_pop(ctx)
  1469. int in_context(list_t *ctx, char *s) {
  1470. if (!ctx->length)
  1471. return 0;
  1472. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1473. if (strcmp(ctx->data[i], "gap") == 0)
  1474. break;
  1475. else if (strcmp(ctx->data[i], s) == 0)
  1476. return 1;
  1477. }
  1478. return 0;
  1479. }
  1480. size_t count_ctxs(list_t *ctx, char *s) {
  1481. if (!ctx->length)
  1482. return 0;
  1483. size_t k = 0;
  1484. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1485. if (strcmp(ctx->data[i], "gap") == 0)
  1486. break;
  1487. else if (strcmp(ctx->data[i], s) == 0)
  1488. k++;
  1489. }
  1490. return k;
  1491. }
  1492. #define INCTX(s) (in_context(ctx, (s)))
  1493. #define SCOPESK (count_ctxs(ctx, "scope"))
  1494. #define TRAPSK (count_ctxs(ctx, "trap"))
  1495. #define LPUSH(i) stack_push(lstk, (i))
  1496. #define LPOP() stack_pop(lstk)
  1497. #define LID (lstk->data[lstk->length-1])
  1498. #define LBPUSH() list_push(lbl, table_new())
  1499. #define LBPOP() list_pop(lbl)
  1500. char *tempvar() {
  1501. NEWGID();
  1502. char *s = malloc(sizeof(char) * 64);
  1503. snprintf(s, 64, "__temp%zu", gid);
  1504. return s;
  1505. }
  1506. void compile_func(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, node_t *node, char *name) {
  1507. NEWGID();
  1508. buffer_t *tbuf = buffer_new();
  1509. buffer_fmt(tbuf, "qi_value_t *__func%d(qi_state_t *state, qi_size_t pargc, qi_list_t *pargs) {\n", gid);
  1510. LBPUSH();
  1511. CTXPUSH("gap");
  1512. CTXPUSH("func");
  1513. size_t optargc = 0;
  1514. if (node->h) {
  1515. table_iterate(node->h, {
  1516. list_t *pair = entry.value;
  1517. size_t argc = *(size_t *)pair->data[0];
  1518. if (pair->data[1]) {
  1519. optargc++;
  1520. buffer_fmt(tbuf, "qi_set(state, false, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ", entry.key, argc+1, argc);
  1521. compile_node(gbuf, tbuf, ctx, lstk, lbl, pair->data[1]);
  1522. buffer_fmt(tbuf, ");\n");
  1523. } else
  1524. buffer_fmt(tbuf, "qi_set(state, false, \"%s\", qi_list_index(pargs, %d));\n", entry.key, argc);
  1525. argc++;
  1526. });
  1527. }
  1528. compile_node(gbuf, tbuf, ctx, lstk, lbl, node->a);
  1529. CTXPOP();
  1530. CTXPOP();
  1531. LBPOP();
  1532. buffer_fmt(tbuf, "return state->nil;\n");
  1533. buffer_fmt(tbuf, "}\n");
  1534. buffer_appendb(gbuf, tbuf);
  1535. tbuf = buffer_new();
  1536. 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);
  1537. compile_table(gbuf, tbuf, ctx, lstk, lbl, node->h2);
  1538. buffer_fmt(tbuf, ")");
  1539. if (node->tag == N_FUNCEXPR) {
  1540. buffer_appendb(buf, tbuf);
  1541. return;
  1542. }
  1543. EMIT("qi_set(state, false, \"%s\", ", node->t->text);
  1544. buffer_appendb(buf, tbuf);
  1545. EMIT(");");
  1546. }
  1547. table_t *CONSTANTS;
  1548. void compile_block(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, list_t *block, int toplevel) {
  1549. for (size_t i = 0; i < block->length; i++) {
  1550. node_t *node = block->data[i];
  1551. if (node->tag == N_CONST) {
  1552. if (!toplevel)
  1553. COMPILE_ERROR("const is not on top-level")
  1554. table_iterate(node->h, {
  1555. char *name = entry.key;
  1556. if (table_get(CONSTANTS, name))
  1557. COMPILE_ERROR("redeclaration of compile-time constant: '%s'", name);
  1558. table_set(CONSTANTS, name, entry.value);
  1559. });
  1560. } else if (node->tag == N_FUNCDEF) {
  1561. compile_func(gbuf, buf, ctx, lstk, lbl, node, NULL);
  1562. EMIT("\n");
  1563. } else if (node->tag == N_CLASS) {
  1564. NEWGID();
  1565. char *name = node->t->text;
  1566. list_t *supers = list_index(node->l, 0);
  1567. list_t *triples = list_index(node->l, 1);
  1568. buffer_t *tbuf = buffer_new();
  1569. buffer_fmt(tbuf, "qi_value_t *__class%d(qi_state_t *state) {\n", gid);
  1570. buffer_fmt(tbuf, "qi_list_t *supers = qi_list_make_n(%d);\n", !supers? 0: supers->length);
  1571. if (supers)
  1572. for (size_t i = 0; i < supers->length; i++) {
  1573. token_t *t = supers->data[i];
  1574. buffer_fmt(tbuf, "qi_list_data(supers, %d) = qi_get(state, \"%s\");\n", i, t->text);
  1575. }
  1576. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  1577. buffer_fmt(tbuf, "qi_table_t *metatable = qi_table_make();\n");
  1578. for (size_t i = 0; i < triples->length; i++) {
  1579. list_t *triple = triples->data[i];
  1580. token_t *t = triple->data[0];
  1581. buffer_t *methodname = buffer_new();
  1582. buffer_fmt(methodname, "%s.%s", name, t->text);
  1583. buffer_fmt(tbuf, "qi_table_set(%s, \"%s\", ", triple->data[1] != NULL? "table": "metatable", t->text);
  1584. if (triple->data[1] == NULL)
  1585. compile_func(gbuf, tbuf, ctx, lstk, lbl, triple->data[2], buffer_read(methodname));
  1586. else
  1587. compile_node(gbuf, tbuf, ctx, lstk, lbl, triple->data[2]);
  1588. buffer_fmt(tbuf, ");\n");
  1589. }
  1590. buffer_fmt(tbuf, "qi_list_t *pargs = qi_list_make_n(4);\n");
  1591. buffer_fmt(tbuf, "qi_list_data(pargs, 0) = qi_make_string(state, \"%s\");\n", name);
  1592. buffer_fmt(tbuf, "qi_list_data(pargs, 1) = qi_make_list(state, supers);\n");
  1593. buffer_fmt(tbuf, "qi_list_data(pargs, 2) = qi_make_table(state, table);\n");
  1594. buffer_fmt(tbuf, "qi_list_data(pargs, 3) = qi_make_table(state, metatable);\n");
  1595. buffer_fmt(tbuf, "return qi_call(state, qi_get(state, \"__class_wrapper\"), pargs);\n");
  1596. buffer_fmt(tbuf, "}\n");
  1597. buffer_appendb(gbuf, tbuf);
  1598. EMIT("qi_set(state, false, \"%s\", __class%d(state));", name, gid);
  1599. } else if (node->tag == N_LABEL) {
  1600. char *label = node->t->text;
  1601. if (table_get(list_index(lbl, -1), label))
  1602. COMPILE_ERROR("duplicated label: '%s'", label);
  1603. NEWGID();
  1604. size_t *n = malloc(sizeof(size_t));
  1605. memcpy(n, &gid, sizeof(size_t));
  1606. table_set(list_index(lbl, -1), label, n);
  1607. }
  1608. }
  1609. for (size_t i = 0; i < block->length; i++) {
  1610. node_t *n = block->data[i];
  1611. if (n->tag == N_FUNCDEF)
  1612. continue;
  1613. compile_node(gbuf, buf, ctx, lstk, lbl, n);
  1614. EMIT("\n");
  1615. }
  1616. }
  1617. const char *STD[][2] = {
  1618. {"std",
  1619. "func exit(c) {\n"
  1620. " if type(c) != \"number\"\n"
  1621. " throw \"expected first argument to be: number, but got: \" + type(c)\n"
  1622. " inline `int code = qi_get(state, \"c\")->value.number`\n"
  1623. " inline `exit(code)`\n"
  1624. "}\n"
  1625. "func head(l): return l[0]\n"
  1626. "func tail(l): return slice(l, 1)\n"
  1627. "func die(msg, c=1) {\n"
  1628. " println(msg)\n"
  1629. " exit(c)\n"
  1630. "}\n"
  1631. "const SEEK_SET = 0, SEEK_CUR = 1, SEEK_END = 2\n"
  1632. "func frewind(file)\n"
  1633. " return file.rewind()\n"
  1634. "func file_read(filename) {\n"
  1635. " let file = fopen(filename, \"r\")\n"
  1636. " defer fclose(file)\n"
  1637. " return str(fread(file, -1))\n"
  1638. "}\n"
  1639. "func file_write(filename, data) {\n"
  1640. " let file = fopen(filename, \"w\")\n"
  1641. " defer fclose(file)\n"
  1642. " fwrite(file, bytes(data))\n"
  1643. "}\n"
  1644. "func is_defined(name) {\n"
  1645. " if type(name) != \"string\"\n"
  1646. " throw \"expected first argument to be: string, but got: \" + type(name)\n"
  1647. " inline `bool b = qi_find(state, qi_get(state, \"name\")->value.string) != NULL`\n"
  1648. " inline `return qi_make_boolean(state, b)`\n"
  1649. "}\n"
  1650. "func list_remove(l, x, first=false) {\n"
  1651. " if type(l) != \"list\"\n"
  1652. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1653. " repeat:\n"
  1654. " for var i = 0; i < len(l); i++\n"
  1655. " if l[i] == x {\n"
  1656. " list_delete(l, i)\n"
  1657. " if first\n"
  1658. " break\n"
  1659. " goto repeat\n"
  1660. " }\n"
  1661. "}\n"
  1662. "set_pseudomethod(\"list.remove\", list_remove)\n"
  1663. "func list_join(l) {\n"
  1664. " if type(l) != \"list\"\n"
  1665. " throw \"expected first argument to be: list, but got: \" + type(l)\n"
  1666. " var r = \"\"\n"
  1667. " var s\n"
  1668. " if len(arguments) == 1\n"
  1669. " s = \"\"\n"
  1670. " else\n"
  1671. " s = arguments[1]\n"
  1672. " if type(s) != \"string\"\n"
  1673. " throw \"expected second argument to be: string, but got: \" + type(s)\n"
  1674. " var first = true\n"
  1675. " for var x of l {\n"
  1676. " if type(x) != \"string\"\n"
  1677. " throw \"expected sequence item to be: string, but got: \" + type(x)\n"
  1678. " if s != \"\" && !first\n"
  1679. " r += s\n"
  1680. " r += x\n"
  1681. " first = false\n"
  1682. " }\n"
  1683. " return r\n"
  1684. "}\n"
  1685. "set_pseudomethod(\"list.join\", list_join)\n"
  1686. "func slice(l) {\n"
  1687. " if type(l) !in (\"list\", \"string\", \"bytes\")\n"
  1688. " throw \"expected first argument to be: list, string or bytes, but got: \" + type(l)\n"
  1689. " var r = []\n"
  1690. " if len(arguments) == 2 {\n"
  1691. " var f = arguments[1]\n"
  1692. " if type(f) != \"number\"\n"
  1693. " throw \"expected second argument to be: number, but got: \" + type(f)\n"
  1694. " for var i = f; i < len(l); i++\n"
  1695. " list_push(r, l[i])\n"
  1696. " } elif len(arguments) == 3 {\n"
  1697. " var f = arguments[1], t = arguments[2]\n"
  1698. " if type(f) != \"number\"\n"
  1699. " throw \"expected second argument to be: number, but got: \" + type(f)\n"
  1700. " if type(t) != \"number\"\n"
  1701. " throw \"expected third argument to be: number, but got: \" + type(t)\n"
  1702. " for var i = f; i < len(l) && i <= t; i++\n"
  1703. " list_push(r, l[i])\n"
  1704. " }\n"
  1705. " if type(l) == \"string\"\n"
  1706. " return list_join(r)\n"
  1707. " elif type(l) == \"bytes\"\n"
  1708. " return bytes(r)\n"
  1709. " return r\n"
  1710. "}\n"
  1711. "set_pseudomethod(\"list.slice\", slice)\n"
  1712. "set_pseudomethod(\"string.slice\", slice)\n"
  1713. "set_pseudomethod(\"bytes.slice\", slice)\n"
  1714. "func Object(t, p=nil): return p !is nil? set_meta_table(p, get_meta_table(p) + t): set_meta_table({}, t)\n"
  1715. "func __class_wrapper(n, p, t, mt): return Object({\n"
  1716. " t: t,\n"
  1717. " mt: mt,\n"
  1718. " super: [],\n"
  1719. " __type: func (this) use (n): return n,\n"
  1720. " __str: func (this) use (n): return \"<class \" + n + \">\",\n"
  1721. " __call: func (this, pargs) use (p) {\n"
  1722. " var t = {}\n"
  1723. " var mt = {}\n"
  1724. " for var other of p {\n"
  1725. " t += other.t\n"
  1726. " mt += other.mt\n"
  1727. " list_push(this.super, other)\n"
  1728. " }\n"
  1729. " if len(this.super) == 1\n"
  1730. " this.super = this.super[0]\n"
  1731. " t += this.t\n"
  1732. " mt += this.mt\n"
  1733. " t.super = this.super\n"
  1734. " obj = set_meta_table(t, mt)\n"
  1735. " if \"constructor\" in mt\n"
  1736. " func_call(mt.constructor, [obj] + pargs)\n"
  1737. " return obj\n"
  1738. " }\n"
  1739. "})\n"
  1740. "inline `srand(time(NULL))`\n"
  1741. },
  1742. {"str",
  1743. "let STR_LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  1744. "let STR_ASCII_LC = \"abcdefghijklmnopqrstuvwxyz\"\n"
  1745. "let STR_ASCII_UC = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n"
  1746. "let STR_DIGITS = \"0123456789\"\n"
  1747. "func is_char(c): return type(c) == \"string\" && len(c) == 1\n"
  1748. },
  1749. {NULL, NULL}
  1750. };
  1751. char *unescape(char *s) {
  1752. buffer_t *buf = buffer_new();
  1753. for (size_t i = 0; i < strlen(s); i++) {
  1754. char c = s[i];
  1755. if (c == '\\') {
  1756. char nc = s[i+1];
  1757. if (!nc)
  1758. continue;
  1759. switch (nc) {
  1760. case 'n':
  1761. buffer_append(buf, '\n');
  1762. break;
  1763. default:
  1764. buffer_append(buf, nc);
  1765. break;
  1766. }
  1767. i++;
  1768. } else buffer_append(buf, c);
  1769. }
  1770. return buffer_read(buf);
  1771. }
  1772. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl);
  1773. int require_once(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, char *path) {
  1774. char *source = NULL;
  1775. for (size_t i = 0; STD[i][0]; i++) {
  1776. if (strcmp(path, STD[i][0]) == 0) {
  1777. source = (char *)STD[i][1];
  1778. break;
  1779. }
  1780. }
  1781. if (is_required(path))
  1782. return 1;
  1783. if (!source) {
  1784. FILE *fd = fopen(path, "rb");
  1785. if (!fd)
  1786. return -1;
  1787. buffer_t *fbuf = buffer_new();
  1788. for (;;) {
  1789. char line[512];
  1790. if (!fgets(line, sizeof(line), fd))
  1791. break;
  1792. buffer_appends(fbuf, line);
  1793. }
  1794. source = buffer_read(fbuf);
  1795. path = realpath(path, NULL);
  1796. }
  1797. list_t *pair = list_new();
  1798. list_push(pair, path);
  1799. list_push(pair, source);
  1800. list_push(FILES, pair);
  1801. compile_into(source, gbuf, buf, ctx, lstk, lbl);
  1802. list_pop(FILES);
  1803. list_push(REQUIRED, path);
  1804. return 0;
  1805. }
  1806. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl, node_t *node) {
  1807. switch (node->tag) {
  1808. case N_TOPLEVEL: case N_PROGRAM:
  1809. compile_block(gbuf, buf, ctx, lstk, lbl, node->l, node->tag == N_TOPLEVEL);
  1810. break;
  1811. case N_EXPRSTMT:
  1812. EMIT("(void)(");
  1813. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1814. EMIT(");");
  1815. break;
  1816. case N_BLOCK:
  1817. LBPUSH();
  1818. CTXPUSH("scope");
  1819. EMIT("qi_new_scope(state);\n");
  1820. compile_block(gbuf, buf, ctx, lstk, lbl, node->l, 0);
  1821. EMIT("qi_old_scope(state);");
  1822. CTXPOP();
  1823. LBPOP();
  1824. break;
  1825. case N_LITERAL:
  1826. switch (node->t->tag) {
  1827. case T_NUMBER:
  1828. EMIT("qi_make_number(state, %s)", node->t->text);
  1829. break;
  1830. case T_STRING:
  1831. if (!*(node->t->text)) {
  1832. EMIT("state->empty_string");
  1833. } else {
  1834. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  1835. }
  1836. break;
  1837. case T_NAME: {
  1838. char *name = node->t->text;
  1839. node_t *n = table_get(CONSTANTS, name);
  1840. if (n)
  1841. compile_node(gbuf, buf, ctx, lstk, lbl, n);
  1842. else
  1843. EMIT("qi_get(state, \"%s\")", name);
  1844. } break;
  1845. default:
  1846. COMPILE_ERROR("not yet implemented");
  1847. }
  1848. break;
  1849. case N_LIST:
  1850. EMIT("qi_make_list(state, ");
  1851. compile_list(gbuf, buf, ctx, lstk, lbl, node->l);
  1852. EMIT(")");
  1853. break;
  1854. case N_TUPLE:
  1855. EMIT("qi_make_tuple(state, ");
  1856. compile_list(gbuf, buf, ctx, lstk, lbl, node->l);
  1857. EMIT(")");
  1858. break;
  1859. case N_NILTUPLE: EMIT("state->empty_tuple"); break;
  1860. case N_TABLE:
  1861. EMIT("qi_make_table(state, ");
  1862. compile_table(gbuf, buf, ctx, lstk, lbl, node->h);
  1863. EMIT(")");
  1864. break;
  1865. case N_CALL:
  1866. EMIT("qi_call(state, ");
  1867. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1868. EMIT(", ");
  1869. compile_list(gbuf, buf, ctx, lstk, lbl, node->l);
  1870. EMIT(")");
  1871. break;
  1872. case N_MEMBER:
  1873. EMIT("qi_index(state, ");
  1874. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1875. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  1876. break;
  1877. case N_INDEX:
  1878. EMIT("qi_index(state, ");
  1879. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1880. EMIT(", ");
  1881. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  1882. EMIT(")");
  1883. break;
  1884. case N_ASSIGN: ASSIGN(node->a, compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1885. case N_ASSIGN_ADD: COMPASSIGN(node->a, "add", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1886. case N_ASSIGN_SUB: COMPASSIGN(node->a, "sub", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1887. case N_ASSIGN_MUL: COMPASSIGN(node->a, "mul", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1888. case N_ASSIGN_DIV: COMPASSIGN(node->a, "div", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1889. case N_ASSIGN_IDIV: COMPASSIGN(node->a, "idiv", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1890. case N_ASSIGN_MOD: COMPASSIGN(node->a, "mod", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1891. case N_ASSIGN_POW: COMPASSIGN(node->a, "pow", compile_node(gbuf, buf, ctx, lstk, lbl, node->b)); break;
  1892. case N_INC:
  1893. COMPASSIGN(node->a, "add", EMIT("state->one"));
  1894. break;
  1895. case N_DEC:
  1896. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  1897. break;
  1898. case N_VAR: case N_LET:
  1899. table_iterate(node->h, {
  1900. EMIT("qi_%s(state, \"%s\", ", node->tag == N_LET? "decl_const": "decl", entry.key);
  1901. if (entry.value)
  1902. compile_node(gbuf, buf, ctx, lstk, lbl, entry.value);
  1903. else EMIT("state->nil");
  1904. EMIT(");\n");
  1905. });
  1906. break;
  1907. case N_CONST:break;
  1908. case N_IF:
  1909. EMIT("if (_qi_truthy(state, ");
  1910. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1911. EMIT(")) {\n");
  1912. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  1913. if (node->c) {
  1914. EMIT("} else {\n");
  1915. compile_node(gbuf, buf, ctx, lstk, lbl, node->c);
  1916. }
  1917. EMIT("}");
  1918. break;
  1919. case N_SWITCH: {
  1920. NEWGID();
  1921. char *varname = tempvar();
  1922. EMIT("qi_value_t *%s = ", varname);
  1923. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1924. EMIT(";\n");
  1925. for (size_t i = 0; i < node->l->length; i++) {
  1926. list_t *pair = node->l->data[i];
  1927. char *label = tempvar();
  1928. EMIT("if (_qi_equals(state, %s, ", varname);
  1929. compile_node(gbuf, buf, ctx, lstk, lbl, pair->data[0]);
  1930. EMIT(")) goto %s;\n", label);
  1931. pair->data[0] = label;
  1932. }
  1933. EMIT("goto __default%d;\n", gid);
  1934. LPUSH(gid);
  1935. CTXPUSH("switch");
  1936. for (size_t i = 0; i < node->l->length; i++) {
  1937. list_t *pair = node->l->data[i];
  1938. char *label = pair->data[0];
  1939. node_t *block = pair->data[1];
  1940. EMIT("%s:;\n", label);
  1941. compile_node(gbuf, buf, ctx, lstk, lbl, block);
  1942. }
  1943. EMIT("__default%d:;\n", gid);
  1944. if (node->b)
  1945. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  1946. CTXPOP();
  1947. LPOP();
  1948. EMIT("__break%d:;\n", gid);
  1949. } break;
  1950. case N_FOR: {
  1951. NEWGID();
  1952. if (!node->a) {
  1953. EMIT("for (;;) {\n");
  1954. } else if (node->a && !node->b) {
  1955. EMIT("while (_qi_truthy(state, ");
  1956. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1957. EMIT(")) {\n");
  1958. } else {
  1959. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1960. EMIT("while (_qi_truthy(state, ");
  1961. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  1962. EMIT(")) {\n");
  1963. }
  1964. LPUSH(gid);
  1965. CTXPUSH("for");
  1966. compile_node(gbuf, buf, ctx, lstk, lbl, node->d);
  1967. if (node->c) {
  1968. compile_node(gbuf, buf, ctx, lstk, lbl, node->c);
  1969. EMIT(";\n");
  1970. }
  1971. CTXPOP();
  1972. LPOP();
  1973. EMIT("__continue%d:;\n", gid);
  1974. EMIT("}\n");
  1975. EMIT("__break%d:;\n", gid);
  1976. } break;
  1977. case N_FOROF: case N_FOROFVAR: {
  1978. NEWGID();
  1979. char *varname = tempvar();
  1980. EMIT("qi_value_t *%s = qi_iter(state, ", varname);
  1981. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  1982. EMIT(");\n");
  1983. if (node->tag == N_FOROFVAR)
  1984. EMIT("qi_decl(state, \"%s\", state->nil);\n", node->t->text);
  1985. EMIT("for (qi_size_t length = _qi_length(state, %s), i = 0; i < length; i++) {\n", varname);
  1986. EMIT("qi_set(state, false, \"%s\", qi_index(state, %s, qi_make_number(state, i)));\n", node->t->text, varname);
  1987. LPUSH(gid);
  1988. CTXPUSH("for");
  1989. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  1990. CTXPOP();
  1991. LPOP();
  1992. EMIT("__continue%d:;\n", gid);
  1993. EMIT("}\n");
  1994. EMIT("__break%d:;\n", gid);
  1995. } break;
  1996. case N_BREAK:
  1997. if (!INCTX("for") && !INCTX("switch"))
  1998. COMPILE_ERROR("break outside of a loop or a switch");
  1999. EMIT("goto __break%d;", LID);
  2000. break;
  2001. case N_CONTINUE:
  2002. if (!INCTX("for"))
  2003. COMPILE_ERROR("continue outside of a loop");
  2004. EMIT("goto __continue%d;", LID);
  2005. break;
  2006. case N_DEFER: {
  2007. NEWGID();
  2008. buffer_t *tbuf = buffer_new();
  2009. buffer_fmt(tbuf, "void __defer%d(qi_state_t *state) {\n", gid);
  2010. LBPUSH();
  2011. CTXPUSH("gap");
  2012. compile_node(gbuf, tbuf, ctx, lstk, lbl, node->a);
  2013. CTXPOP();
  2014. LBPOP();
  2015. buffer_fmt(tbuf, "\n");
  2016. buffer_fmt(tbuf, "}\n");
  2017. buffer_appendb(gbuf, tbuf);
  2018. EMIT("qi_add_defer(state, -1, __defer%d);", gid);
  2019. } break;
  2020. case N_RETURN:
  2021. if (!INCTX("func"))
  2022. COMPILE_ERROR("return outside of a function");
  2023. for (size_t i = 0; i < SCOPESK; i++)
  2024. EMIT("qi_old_scope(state);\n");
  2025. for (size_t i = 0; i < TRAPSK; i++)
  2026. EMIT("qi_unset_trap(state, trap);\n");
  2027. EMIT("return ");
  2028. if (node->a)
  2029. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  2030. else EMIT("state->nil");
  2031. EMIT(";");
  2032. break;
  2033. case N_FUNCDEF: break;
  2034. case N_CLASS: break;
  2035. case N_PASS: break;
  2036. case N_TRY:
  2037. EMIT("qi_try(state, {\n");
  2038. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  2039. EMIT("}, {\n");
  2040. if (node->t)
  2041. EMIT("qi_decl(state, \"%s\", trap->value);\n", node->t->text);
  2042. CTXPUSH("trap");
  2043. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  2044. CTXPOP();
  2045. EMIT("}, NULL);\n");
  2046. break;
  2047. case N_THROW:
  2048. EMIT("qi_throw(state, ");
  2049. if (node->a)
  2050. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  2051. else {
  2052. EMIT("state->nil");
  2053. }
  2054. EMIT(");");
  2055. break;
  2056. case N_LABEL: {
  2057. size_t *gid = table_get(list_index(lbl, -1), node->t->text);
  2058. EMIT("__label%d:;", *gid);
  2059. } break;
  2060. case N_GOTO: {
  2061. char *label = node->t->text;
  2062. size_t *gid = table_get(list_index(lbl, -1), label);
  2063. if (!gid)
  2064. COMPILE_ERROR("undefined label: '%s'", label);
  2065. EMIT("goto __label%d;", *gid);
  2066. } break;
  2067. case N_REQUIRE: {
  2068. char *path = unescape(node->t->text);
  2069. if (require_once(gbuf, buf, ctx, lstk, lbl, path) < 0)
  2070. COMPILE_ERROR("'%s' is not a valid file path or a builtin library name", path);
  2071. } break;
  2072. case N_IFEXPR:
  2073. EMIT("(_qi_truthy(state, ");
  2074. compile_node(gbuf, buf, ctx, lstk, lbl, node->a);
  2075. EMIT(")? ");
  2076. compile_node(gbuf, buf, ctx, lstk, lbl, node->b);
  2077. EMIT(": ");
  2078. compile_node(gbuf, buf, ctx, lstk, lbl, node->c);
  2079. EMIT(")");
  2080. break;
  2081. case N_FUNCEXPR:
  2082. compile_func(gbuf, buf, ctx, lstk, lbl, node, NULL);
  2083. break;
  2084. case N_EQUALS:
  2085. BINOP("equals");
  2086. break;
  2087. case N_NOTEQUALS:
  2088. BINOP("not_equals");
  2089. break;
  2090. case N_IS:
  2091. BINOP("is");
  2092. break;
  2093. case N_NOTIS:
  2094. BINOP("not_is");
  2095. break;
  2096. case N_IN:
  2097. BINOP("in");
  2098. break;
  2099. case N_NOTIN:
  2100. BINOP("not_in");
  2101. break;
  2102. case N_LT:
  2103. BINOP("lt");
  2104. break;
  2105. case N_GT:
  2106. BINOP("gt");
  2107. break;
  2108. case N_LE:
  2109. BINOP("le");
  2110. break;
  2111. case N_GE:
  2112. BINOP("ge");
  2113. break;
  2114. case N_ADD:
  2115. BINOP("add");
  2116. break;
  2117. case N_SUB:
  2118. BINOP("sub");
  2119. break;
  2120. case N_MUL:
  2121. BINOP("mul");
  2122. break;
  2123. case N_DIV:
  2124. BINOP("div");
  2125. break;
  2126. case N_IDIV:
  2127. BINOP("idiv");
  2128. break;
  2129. case N_MOD:
  2130. BINOP("mod");
  2131. break;
  2132. case N_POW:
  2133. BINOP("pow");
  2134. break;
  2135. case N_SHL:
  2136. BINOP("shl");
  2137. break;
  2138. case N_SHR:
  2139. BINOP("shr");
  2140. break;
  2141. case N_XOR:
  2142. BINOP("xor");
  2143. break;
  2144. case N_BOR:
  2145. BINOP("bor");
  2146. break;
  2147. case N_BAND:
  2148. BINOP("band");
  2149. break;
  2150. case N_LOGOR:
  2151. BINOP("or");
  2152. break;
  2153. case N_LOGAND:
  2154. BINOP("and");
  2155. break;
  2156. case N_NEGATE:
  2157. UNOP("negate");
  2158. break;
  2159. case N_NOT:
  2160. UNOP("not");
  2161. break;
  2162. case N_BNOT:
  2163. UNOP("bnot");
  2164. break;
  2165. case N_INLINE: EMIT("%s;", unescape(node->t->text)); break;
  2166. default:
  2167. COMPILE_ERROR("not yet implemented");
  2168. }
  2169. }
  2170. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *lbl) {
  2171. node_t *n = parse(source);
  2172. compile_node(gbuf, buf, ctx, lstk, lbl, n);
  2173. }
  2174. char *compile(char *source) {
  2175. list_t *ctx = list_new();
  2176. stack_t *lstk = stack_new();
  2177. list_t *lbl = list_new();
  2178. LBPUSH();
  2179. buffer_t *gbuf = buffer_new();
  2180. buffer_appends(gbuf, "#include <qirt.h>\n");
  2181. buffer_t *buf = buffer_new();
  2182. require_once(gbuf, buf, ctx, lstk, lbl, "std");
  2183. compile_into(source, gbuf, buf, ctx, lstk, lbl);
  2184. buffer_t *rbuf = buffer_new();
  2185. buffer_appendb(rbuf, gbuf);
  2186. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  2187. buffer_appends(rbuf, "qi_state_t *state;\n");
  2188. buffer_appends(rbuf, "qi_state_init(&state);\n");
  2189. buffer_appendb(rbuf, buf);
  2190. buffer_appends(rbuf, "qi_old_scope(state);\n");
  2191. buffer_appends(rbuf, "qi_finalize();\n");
  2192. buffer_appends(rbuf, "return 0;\n");
  2193. buffer_appends(rbuf, "}\n");
  2194. return buffer_read(rbuf);
  2195. }
  2196. char *compile_file(char *filename, FILE *fd) {
  2197. buffer_t *buf = buffer_new();
  2198. for (;;) {
  2199. char line[512];
  2200. if (!fgets(line, sizeof(line), fd))
  2201. break;
  2202. buffer_appends(buf, line);
  2203. }
  2204. char *source = buffer_read(buf);
  2205. list_t *pair = list_new();
  2206. list_push(pair, filename);
  2207. list_push(pair, source);
  2208. list_push(FILES, pair);
  2209. char *out = compile(source);
  2210. list_pop(FILES);
  2211. return out;
  2212. }
  2213. int main(int argc, char **argv) {
  2214. FILES = list_new();
  2215. REQUIRED = list_new();
  2216. CONSTANTS = table_new();
  2217. char *out = compile_file("<stdin>", stdin);
  2218. fwrite(out, sizeof(char), strlen(out), stdout);
  2219. return 0;
  2220. }