qic.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  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_IF,
  202. T_ELSE,
  203. T_ELIF,
  204. T_FOR,
  205. T_BREAK,
  206. T_CONTINUE,
  207. T_PASS,
  208. T_FUNC,
  209. T_USE,
  210. T_RETURN,
  211. T_DEFER,
  212. T_REQUIRE,
  213. T_TRY,
  214. T_CATCH,
  215. T_THROW,
  216. T_LPAR,
  217. T_RPAR,
  218. T_LSB,
  219. T_RSB,
  220. T_LCB,
  221. T_RCB,
  222. T_EQUALS,
  223. T_PLUSASSIGN,
  224. T_BARBAR,
  225. T_ANDAND,
  226. T_STARSTAR,
  227. T_PLUSPLUS,
  228. T_MINUSMINUS,
  229. T_SLASHSLASH,
  230. T_PLUS,
  231. T_MINUS,
  232. T_QM,
  233. T_COLON,
  234. T_BAR,
  235. T_AND,
  236. T_RAISE,
  237. T_LT,
  238. T_LTLT,
  239. T_GT,
  240. T_GTGT,
  241. T_STAR,
  242. T_SLASH,
  243. T_COMMA,
  244. T_DOT,
  245. T_ASSIGN,
  246. T_SEMI
  247. } tag;
  248. char *text;
  249. size_t fi;
  250. size_t pos;
  251. } token_t;
  252. token_t *token(int tag, char *text) {
  253. token_t *tok = malloc(sizeof(token_t));
  254. tok->tag = tag;
  255. tok->text = text;
  256. return tok;
  257. }
  258. #define TK(tk) (token(T_##tk, NULL))
  259. #define WS() while (source[*pos] == ' ' || source[*pos] == '\t' || source[*pos] == '\n' || source[*pos] == '\r') { (*pos)++; }
  260. void consume_ignored(char *source, size_t *pos) {
  261. WS();
  262. while (source[*pos] == '#') {
  263. (*pos)++;
  264. for (;;) {
  265. if (!source[*pos])
  266. break;
  267. if (source[*pos] == '\n') {
  268. (*pos)++;
  269. break;
  270. }
  271. (*pos)++;
  272. }
  273. WS();
  274. }
  275. }
  276. list_t *FILES;
  277. list_t *REQUIRED;
  278. int is_required(char *path) {
  279. for (size_t i = 0; i < REQUIRED->length; i++)
  280. if (strcmp(REQUIRED->data[i], path) == 0)
  281. return 1;
  282. return 0;
  283. }
  284. void traverse(char *source, size_t pos, size_t *line, size_t *col) {
  285. *line = 1;
  286. *col = 1;
  287. for (size_t i = 0; i < pos; i++) {
  288. if (source[i] == '\n') {
  289. (*line)++;
  290. (*col) = 1;
  291. } else (*col)++;
  292. }
  293. }
  294. void format_error(char *filename, char *source, size_t pos, char *fmt, ...) {
  295. size_t line, col;
  296. traverse(source, pos, &line, &col);
  297. va_list args;
  298. va_start(args, fmt);
  299. fprintf(stderr, "%s (%zu:%zu): ", filename, line, col);
  300. vfprintf(stderr, fmt, args);
  301. fputc('\n', stderr);
  302. va_end(args);
  303. }
  304. #define GETFNAME(fi) ((char *)((list_t *)list_index(FILES, fi))->data[0])
  305. #define GETSRC(fi) ((char *)((list_t *)list_index(FILES, fi))->data[1])
  306. #define LEX_ERROR(fmt, ...) { format_error(GETFNAME(-1), source, *pos, fmt, ##__VA_ARGS__); exit(1); }
  307. token_t *next_token(char *source, size_t *pos) {
  308. if (!source[*pos])
  309. return token(T_EOF, NULL);
  310. if (source[*pos] == '"' || source[*pos] == '\'') {
  311. char term = source[(*pos)++];
  312. buffer_t *text = buffer_new();
  313. while (source[*pos] != term) {
  314. if (!source[*pos])
  315. LEX_ERROR("unterminated string literal");
  316. char c = source[(*pos)++];
  317. if (c == '\\') {
  318. char nc = source[(*pos)++];
  319. if (!nc)
  320. continue;
  321. switch (nc) {
  322. case 'n':
  323. buffer_appends(text, "\\n");
  324. break;
  325. case 't':
  326. buffer_appends(text, "\\t");
  327. break;
  328. case 'r':
  329. buffer_appends(text, "\\r");
  330. break;
  331. case 'b':
  332. buffer_appends(text, "\\b");
  333. break;
  334. case 'e':
  335. buffer_appends(text, "\\e");
  336. break;
  337. case 's':
  338. buffer_appends(text, " ");
  339. break;
  340. case '"':
  341. buffer_appends(text, "\\\"");
  342. break;
  343. case '\\':
  344. buffer_appends(text, "\\\\");
  345. break;
  346. default:
  347. buffer_append(text, nc);
  348. break;
  349. }
  350. continue;
  351. }
  352. if (c == '"' || c == '\\')
  353. buffer_append(text, '\\');
  354. buffer_append(text, c);
  355. }
  356. (*pos)++;
  357. return token(T_STRING, buffer_read(text));
  358. } else if (isdigit(source[*pos])) {
  359. buffer_t *number = buffer_new();
  360. int dot = 0;
  361. int sub = 0;
  362. do {
  363. buffer_append(number, source[(*pos)++]);
  364. if (!dot && source[*pos] == '.') {
  365. buffer_append(number, source[(*pos)++]);
  366. if (!isdigit(source[*pos]))
  367. LEX_ERROR("illegal number literal (missing part after floating point)");
  368. dot = 1;
  369. } else if (!sub && source[*pos] == '.') {
  370. (*pos)++;
  371. sub = 1;
  372. } else if (sub) sub = 0;
  373. } while (isdigit(source[*pos]));
  374. return token(T_NUMBER, buffer_read(number));
  375. } else if (isalpha(source[*pos]) || source[*pos] == '_') {
  376. buffer_t *text = buffer_new();
  377. do {
  378. buffer_append(text, source[(*pos)++]);
  379. } while (isalpha(source[*pos]) || source[*pos] == '_' || isdigit(source[*pos]));
  380. char *name = buffer_read(text);
  381. if (strcmp(name, "var") == 0)
  382. return TK(VAR);
  383. else if (strcmp(name, "if") == 0)
  384. return TK(IF);
  385. else if (strcmp(name, "else") == 0)
  386. return TK(ELSE);
  387. else if (strcmp(name, "elif") == 0)
  388. return TK(ELIF);
  389. else if (strcmp(name, "for") == 0)
  390. return TK(FOR);
  391. else if (strcmp(name, "break") == 0)
  392. return TK(BREAK);
  393. else if (strcmp(name, "continue") == 0)
  394. return TK(CONTINUE);
  395. else if (strcmp(name, "func") == 0)
  396. return TK(FUNC);
  397. else if (strcmp(name, "use") == 0)
  398. return TK(USE);
  399. else if (strcmp(name, "return") == 0)
  400. return TK(RETURN);
  401. else if (strcmp(name, "defer") == 0)
  402. return TK(DEFER);
  403. else if (strcmp(name, "pass") == 0)
  404. return TK(PASS);
  405. else if (strcmp(name, "require") == 0)
  406. return TK(REQUIRE);
  407. else if (strcmp(name, "try") == 0)
  408. return TK(TRY);
  409. else if (strcmp(name, "catch") == 0)
  410. return TK(CATCH);
  411. else if (strcmp(name, "throw") == 0)
  412. return TK(THROW);
  413. return token(T_NAME, name);
  414. } else if (strncmp(&source[*pos], "==", 2) == 0 && ++(*pos) && ++(*pos))
  415. return TK(EQUALS);
  416. else if (strncmp(&source[*pos], "+=", 2) == 0 && ++(*pos) && ++(*pos))
  417. return TK(PLUSASSIGN);
  418. else if (strncmp(&source[*pos], "||", 2) == 0 && ++(*pos) && ++(*pos))
  419. return TK(BARBAR);
  420. else if (strncmp(&source[*pos], "&&", 2) == 0 && ++(*pos) && ++(*pos))
  421. return TK(ANDAND);
  422. else if (strncmp(&source[*pos], "++", 2) == 0 && ++(*pos) && ++(*pos))
  423. return TK(PLUSPLUS);
  424. else if (strncmp(&source[*pos], "--", 2) == 0 && ++(*pos) && ++(*pos))
  425. return TK(MINUSMINUS);
  426. else if (strncmp(&source[*pos], "//", 2) == 0 && ++(*pos) && ++(*pos))
  427. return TK(SLASHSLASH);
  428. else if (strncmp(&source[*pos], "**", 2) == 0 && ++(*pos) && ++(*pos))
  429. return TK(STARSTAR);
  430. else if (source[*pos] == '(' && ++(*pos))
  431. return TK(LPAR);
  432. else if (source[*pos] == ')' && ++(*pos))
  433. return TK(RPAR);
  434. else if (source[*pos] == '[' && ++(*pos))
  435. return TK(LSB);
  436. else if (source[*pos] == ']' && ++(*pos))
  437. return TK(RSB);
  438. else if (source[*pos] == '{' && ++(*pos))
  439. return TK(LCB);
  440. else if (source[*pos] == '}' && ++(*pos))
  441. return TK(RCB);
  442. else if (source[*pos] == '+' && ++(*pos))
  443. return TK(PLUS);
  444. else if (source[*pos] == '-' && ++(*pos))
  445. return TK(MINUS);
  446. else if (source[*pos] == '*' && ++(*pos))
  447. return TK(STAR);
  448. else if (source[*pos] == '/' && ++(*pos))
  449. return TK(SLASH);
  450. else if (source[*pos] == '?' && ++(*pos))
  451. return TK(QM);
  452. else if (source[*pos] == ':' && ++(*pos))
  453. return TK(COLON);
  454. else if (source[*pos] == '=' && ++(*pos))
  455. return TK(ASSIGN);
  456. else if (source[*pos] == ';' && ++(*pos))
  457. return TK(SEMI);
  458. else if (source[*pos] == ',' && ++(*pos))
  459. return TK(COMMA);
  460. else if (source[*pos] == '.' && ++(*pos))
  461. return TK(DOT);
  462. else if (source[*pos] == '<' && ++(*pos))
  463. return TK(LT);
  464. else if (source[*pos] == '>' && ++(*pos))
  465. return TK(GT);
  466. LEX_ERROR("unexpected input")
  467. }
  468. list_t *tokenize(char *source) {
  469. size_t pos = 0;
  470. list_t *toks = list_new();
  471. do {
  472. consume_ignored(source, &pos);
  473. size_t tok_pos = pos;
  474. token_t *tok = next_token(source, &pos);
  475. tok->fi = FILES->length-1;
  476. tok->pos = tok_pos;
  477. list_push(toks, tok);
  478. if (tok->tag == T_EOF)
  479. break;
  480. } while (1);
  481. return toks;
  482. }
  483. struct _node_t {
  484. enum {
  485. N_PROGRAM,
  486. N_EXPRSTMT,
  487. N_BLOCK,
  488. N_NEGATE,
  489. N_LITERAL,
  490. N_LIST,
  491. N_TUPLE,
  492. N_NILTUPLE,
  493. N_TABLE,
  494. N_CALL,
  495. N_MEMBER,
  496. N_INDEX,
  497. N_ADD,
  498. N_SUB,
  499. N_MUL,
  500. N_DIV,
  501. N_IDIV,
  502. N_POW,
  503. N_ASSIGN,
  504. N_ASSIGN_ADD,
  505. N_EQUALS,
  506. N_LT,
  507. N_GT,
  508. N_INC,
  509. N_DEC,
  510. N_VAR,
  511. N_IF,
  512. N_FOR,
  513. N_BREAK,
  514. N_CONTINUE,
  515. N_FUNCDEF,
  516. N_RETURN,
  517. N_DEFER,
  518. N_PASS,
  519. N_REQUIRE,
  520. N_TRY,
  521. N_THROW,
  522. N_IFEXPR,
  523. N_FUNCEXPR,
  524. N_LOGOR,
  525. N_LOGAND,
  526. } tag;
  527. struct _node_t *a;
  528. struct _node_t *b;
  529. struct _node_t *c;
  530. struct _node_t *d;
  531. list_t *l;
  532. table_t *h;
  533. table_t *h2;
  534. token_t *t;
  535. size_t fi;
  536. size_t pos;
  537. };
  538. typedef struct _node_t node_t;
  539. node_t *node_pos(node_t *node, size_t fi, size_t pos) {
  540. node->fi = fi;
  541. node->pos = pos;
  542. return node;
  543. }
  544. node_t *nodet(int tag, token_t *t) {
  545. node_t *node = malloc(sizeof(node_t));
  546. node->tag = tag;
  547. node->t = t;
  548. return node;
  549. }
  550. #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))
  551. node_t *nodel(int tag, list_t *l) {
  552. node_t *node = malloc(sizeof(node_t));
  553. node->tag = tag;
  554. node->l = l;
  555. return node;
  556. }
  557. #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))
  558. node_t *nodeh(int tag, table_t *h) {
  559. node_t *node = malloc(sizeof(node_t));
  560. node->tag = tag;
  561. node->h = h;
  562. return node;
  563. }
  564. #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))
  565. node_t *node0(int tag) {
  566. node_t *node = malloc(sizeof(node_t));
  567. node->tag = tag;
  568. return node;
  569. }
  570. #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))
  571. node_t *node1(int tag, node_t *a) {
  572. node_t *node = malloc(sizeof(node_t));
  573. node->tag = tag;
  574. node->a = a;
  575. return node;
  576. }
  577. #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))
  578. node_t *node1l(int tag, node_t *a, list_t *l) {
  579. node_t *node = malloc(sizeof(node_t));
  580. node->tag = tag;
  581. node->a = a;
  582. node->l = l;
  583. return node;
  584. }
  585. #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))
  586. node_t *node1t(int tag, node_t *a, token_t *t) {
  587. node_t *node = malloc(sizeof(node_t));
  588. node->tag = tag;
  589. node->a = a;
  590. node->t = t;
  591. return node;
  592. }
  593. #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))
  594. node_t *node2(int tag, node_t *a, node_t *b) {
  595. node_t *node = malloc(sizeof(node_t));
  596. node->tag = tag;
  597. node->a = a;
  598. node->b = b;
  599. return node;
  600. }
  601. #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))
  602. node_t *node2t(int tag, node_t *a, node_t *b, token_t *t) {
  603. node_t *node = malloc(sizeof(node_t));
  604. node->tag = tag;
  605. node->a = a;
  606. node->b = b;
  607. node->t = t;
  608. return node;
  609. }
  610. #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))
  611. node_t *node3(int tag, node_t *a, node_t *b, node_t *c) {
  612. node_t *node = malloc(sizeof(node_t));
  613. node->tag = tag;
  614. node->a = a;
  615. node->b = b;
  616. node->c = c;
  617. return node;
  618. }
  619. #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))
  620. node_t *node4(int tag, node_t *a, node_t *b, node_t *c, node_t *d) {
  621. node_t *node = malloc(sizeof(node_t));
  622. node->tag = tag;
  623. node->a = a;
  624. node->b = b;
  625. node->c = c;
  626. node->d = d;
  627. return node;
  628. }
  629. #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))
  630. node_t *nodef(int tag, token_t *name, table_t *params, table_t *captured, node_t *body) {
  631. node_t *node = malloc(sizeof(node_t));
  632. node->tag = tag;
  633. node->t = name;
  634. node->h = params;
  635. node->h2 = captured;
  636. node->a = body;
  637. return node;
  638. }
  639. #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))
  640. #define AT(tk) (*pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == T_##tk)
  641. #define MATCH(tk) (AT(tk) && ++(*pos))
  642. #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); }
  643. #define EXPECT(tk, s) { if (!MATCH(tk)) PARSE_ERROR("expected %s", (s)); }
  644. node_t *parse_expr(list_t *tokens, size_t *pos);
  645. list_t *parse_sequence(list_t *tokens, size_t *pos, int term) {
  646. list_t *seq = list_new();
  647. do {
  648. if (term != -1 && *pos < tokens->length && ((token_t *)tokens->data[*pos])->tag == term)
  649. break;
  650. list_push(seq, parse_expr(tokens, pos));
  651. } while (MATCH(COMMA));
  652. return seq;
  653. }
  654. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr);
  655. node_t *parse_primary(list_t *tokens, size_t *pos) {
  656. if (MATCH(FUNC))
  657. return parse_func(tokens, pos, 1);
  658. else if (MATCH(LPAR)) {
  659. if (MATCH(RPAR))
  660. return NODE0(NILTUPLE);
  661. node_t *a = parse_expr(tokens, pos);
  662. if (MATCH(COMMA)) {
  663. list_t *l = list_new();
  664. list_push(l, a);
  665. if (!AT(RPAR))
  666. do {
  667. node_t *n = parse_expr(tokens, pos);
  668. list_push(l, n);
  669. } while (MATCH(COMMA));
  670. a = NODEL(TUPLE, l);
  671. }
  672. EXPECT(RPAR, ")");
  673. return a;
  674. } else if (MATCH(LSB)) {
  675. list_t *a = parse_sequence(tokens, pos, T_RSB);
  676. EXPECT(RSB, "]");
  677. return NODEL(LIST, a);
  678. } else if (MATCH(LCB)) {
  679. table_t *table = table_new();
  680. do {
  681. if (AT(RCB))
  682. break;
  683. if (!AT(NAME) && !AT(STRING))
  684. PARSE_ERROR("expected identifier or string");
  685. char *key = ((token_t *)tokens->data[(*pos)++])->text;
  686. EXPECT(COLON, ":");
  687. node_t *val = parse_expr(tokens, pos);
  688. table_set(table, key, val);
  689. } while (MATCH(COMMA));
  690. EXPECT(RCB, "}");
  691. return NODEH(TABLE, table);
  692. } else if (MATCH(NUMBER) || MATCH(STRING) || MATCH(NAME))
  693. return NODET(LITERAL, tokens->data[(*pos)-1]);
  694. PARSE_ERROR("expected expression");
  695. return NULL;
  696. }
  697. size_t get_lineno(token_t *tok) {
  698. size_t line, col;
  699. traverse(GETSRC(tok->fi), tok->pos, &line, &col);
  700. return line;
  701. }
  702. #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)])))
  703. node_t *parse_call(list_t *tokens, size_t *pos) {
  704. node_t *a = parse_primary(tokens, pos);
  705. do {
  706. if (!CLIFF && MATCH(LPAR)) {
  707. list_t *b = NULL;
  708. if (!AT(RPAR))
  709. b = parse_sequence(tokens, pos, -1);
  710. EXPECT(RPAR, ")");
  711. a = NODE1l(CALL, a, b);
  712. continue;
  713. } else if (!CLIFF && MATCH(LSB)) {
  714. node_t *b = parse_expr(tokens, pos);
  715. EXPECT(RSB, "]");
  716. a = NODE2(INDEX, a, b);
  717. continue;
  718. } else if (!CLIFF && MATCH(DOT)) {
  719. if (!AT(NAME))
  720. PARSE_ERROR("expected identifier after .");
  721. a = NODE1t(MEMBER, a, tokens->data[(*pos)++]);
  722. continue;
  723. }
  724. break;
  725. } while (1);
  726. return a;
  727. }
  728. node_t *parse_postfix(list_t *tokens, size_t *pos) {
  729. node_t *a = parse_call(tokens, pos);
  730. if (CLIFF)
  731. return a;
  732. if (MATCH(PLUSPLUS))
  733. return NODE1(INC, a);
  734. else if (MATCH(MINUSMINUS))
  735. return NODE1(DEC, a);
  736. return a;
  737. }
  738. node_t *parse_unary(list_t *tokens, size_t *pos) {
  739. if (MATCH(MINUS)) {
  740. node_t *a = parse_unary(tokens, pos);
  741. return NODE1(NEGATE, a);
  742. }
  743. return parse_postfix(tokens, pos);
  744. }
  745. node_t *parse_pow(list_t *tokens, size_t *pos) {
  746. node_t *a = parse_unary(tokens, pos);
  747. do {
  748. if (MATCH(STARSTAR)) {
  749. node_t *b = parse_unary(tokens, pos);
  750. a = NODE2(POW, a, b);
  751. continue;
  752. }
  753. break;
  754. } while (1);
  755. return a;
  756. }
  757. node_t *parse_mul(list_t *tokens, size_t *pos) {
  758. node_t *a = parse_pow(tokens, pos);
  759. do {
  760. if (MATCH(STAR)) {
  761. node_t *b = parse_pow(tokens, pos);
  762. a = NODE2(MUL, a, b);
  763. continue;
  764. } else if (MATCH(SLASH)) {
  765. node_t *b = parse_pow(tokens, pos);
  766. a = NODE2(DIV, a, b);
  767. continue;
  768. } else if (MATCH(SLASHSLASH)) {
  769. node_t *b = parse_pow(tokens, pos);
  770. a = NODE2(IDIV, a, b);
  771. continue;
  772. }
  773. break;
  774. } while (1);
  775. return a;
  776. }
  777. node_t *parse_add(list_t *tokens, size_t *pos) {
  778. node_t *a = parse_mul(tokens, pos);
  779. do {
  780. if (MATCH(PLUS)) {
  781. node_t *b = parse_mul(tokens, pos);
  782. a = NODE2(ADD, a, b);
  783. continue;
  784. } else if (MATCH(MINUS)) {
  785. node_t *b = parse_mul(tokens, pos);
  786. a = NODE2(SUB, a, b);
  787. continue;
  788. }
  789. break;
  790. } while (1);
  791. return a;
  792. }
  793. node_t *parse_shift(list_t *tokens, size_t *pos) {
  794. node_t *a = parse_add(tokens, pos);
  795. return a;
  796. }
  797. node_t *parse_relation(list_t *tokens, size_t *pos) {
  798. node_t *a = parse_shift(tokens, pos);
  799. do {
  800. if (MATCH(LT)) {
  801. node_t *b = parse_shift(tokens, pos);
  802. a = NODE2(LT, a, b);
  803. continue;
  804. } else if (MATCH(GT)) {
  805. node_t *b = parse_shift(tokens, pos);
  806. a = NODE2(GT, a, b);
  807. continue;
  808. }
  809. break;
  810. } while (1);
  811. return a;
  812. }
  813. node_t *parse_equality(list_t *tokens, size_t *pos) {
  814. node_t *a = parse_relation(tokens, pos);
  815. do {
  816. if (MATCH(EQUALS)) {
  817. node_t *b = parse_relation(tokens, pos);
  818. a = NODE2(EQUALS, a, b);
  819. continue;
  820. }
  821. break;
  822. } while (1);
  823. return a;
  824. }
  825. node_t *parse_bitand(list_t *tokens, size_t *pos) {
  826. node_t *a = parse_equality(tokens, pos);
  827. return a;
  828. }
  829. node_t *parse_bitxor(list_t *tokens, size_t *pos) {
  830. node_t *a = parse_bitand(tokens, pos);
  831. return a;
  832. }
  833. node_t *parse_bitor(list_t *tokens, size_t *pos) {
  834. node_t *a = parse_bitxor(tokens, pos);
  835. return a;
  836. }
  837. node_t *parse_logand(list_t *tokens, size_t *pos) {
  838. node_t *a = parse_bitor(tokens, pos);
  839. if (MATCH(ANDAND)) {
  840. node_t *b = parse_logand(tokens, pos);
  841. return NODE2(LOGAND, a, b);
  842. }
  843. return a;
  844. }
  845. node_t *parse_logor(list_t *tokens, size_t *pos) {
  846. node_t *a = parse_logand(tokens, pos);
  847. if (MATCH(BARBAR)) {
  848. node_t *b = parse_logor(tokens, pos);
  849. return NODE2(LOGOR, a, b);
  850. }
  851. return a;
  852. }
  853. node_t *parse_assignment(list_t *tokens, size_t *pos);
  854. node_t *parse_conditional(list_t *tokens, size_t *pos) {
  855. node_t *a = parse_logor(tokens, pos);
  856. if (MATCH(QM)) {
  857. node_t *b = parse_assignment(tokens, pos);
  858. EXPECT(COLON, ":");
  859. node_t *c = parse_assignment(tokens, pos);
  860. return NODE3(IFEXPR, a, b, c);
  861. }
  862. return a;
  863. }
  864. node_t *parse_assignment(list_t *tokens, size_t *pos) {
  865. node_t *a = parse_conditional(tokens, pos);
  866. if (MATCH(ASSIGN)) {
  867. node_t *b = parse_assignment(tokens, pos);
  868. return NODE2(ASSIGN, a, b);
  869. } else if (MATCH(PLUSASSIGN)) {
  870. node_t *b = parse_assignment(tokens, pos);
  871. return NODE2(ASSIGN_ADD, a, b);
  872. }
  873. return a;
  874. }
  875. node_t *parse_expr(list_t *tokens, size_t *pos) {
  876. return parse_assignment(tokens, pos);
  877. }
  878. node_t *parse_stmt(list_t *tokens, size_t *pos);
  879. node_t *parse_block(list_t *tokens, size_t *pos) {
  880. EXPECT(LCB, "{");
  881. list_t *stmts = list_new();
  882. while (!AT(EOF) && !AT(RCB))
  883. list_push(stmts, parse_stmt(tokens, pos));
  884. EXPECT(RCB, "}");
  885. return NODEL(PROGRAM, stmts);
  886. }
  887. #define BLOCK() (MATCH(COLON)?parse_stmt(tokens, pos):parse_block(tokens, pos))
  888. node_t *parse_if(list_t *tokens, size_t *pos) {
  889. node_t *a = parse_expr(tokens, pos);
  890. node_t *b = BLOCK();
  891. node_t *c = NULL;
  892. if (MATCH(ELSE))
  893. c = BLOCK();
  894. else if (MATCH(ELIF))
  895. c = parse_if(tokens, pos);
  896. return NODE3(IF, a, b, c);
  897. }
  898. node_t *parse_var(list_t *tokens, size_t *pos) {
  899. table_t *h = table_new();
  900. do {
  901. if(!AT(NAME))
  902. PARSE_ERROR("expected identifier");
  903. char *k = ((token_t *)tokens->data[(*pos)++])->text;
  904. node_t *v = NULL;
  905. if (MATCH(ASSIGN))
  906. v = parse_expr(tokens, pos);
  907. table_set(h, k, v);
  908. } while (MATCH(COMMA));
  909. return NODEH(VAR, h);
  910. }
  911. node_t *parse_func(list_t *tokens, size_t *pos, int is_expr) {
  912. token_t *name = NULL;
  913. if (!is_expr) {
  914. if(!AT(NAME))
  915. PARSE_ERROR("expected identifier");
  916. name = tokens->data[(*pos)++];
  917. }
  918. EXPECT(LPAR, "(");
  919. table_t *params = NULL;
  920. if (!AT(RPAR)) {
  921. int flag = 0;
  922. params = table_new();
  923. size_t argc = 0;
  924. do {
  925. if(!AT(NAME))
  926. PARSE_ERROR("expected identifier");
  927. char *l = ((token_t *)tokens->data[(*pos)++])->text;
  928. node_t *r = NULL;
  929. if (!flag && AT(ASSIGN))
  930. flag = 1;
  931. if (flag) {
  932. EXPECT(ASSIGN, "=");
  933. r = parse_expr(tokens, pos);
  934. }
  935. list_t *pair = list_new();
  936. size_t *argcp = malloc(sizeof(size_t));
  937. memcpy(argcp, &argc, sizeof(size_t));
  938. argc++;
  939. list_push(pair, argcp);
  940. list_push(pair, r);
  941. table_set(params, l, pair);
  942. } while (MATCH(COMMA));
  943. }
  944. EXPECT(RPAR, ")");
  945. table_t *captured = NULL;
  946. if (MATCH(USE)) {
  947. EXPECT(RPAR, "(");
  948. captured = table_new();
  949. do {
  950. if(!AT(NAME))
  951. PARSE_ERROR("expected identifier");
  952. token_t *name = tokens->data[(*pos)++];
  953. table_set(captured, name->text, NODET(LITERAL, name));
  954. } while (MATCH(COMMA));
  955. EXPECT(RPAR, ")");
  956. }
  957. node_t *body = BLOCK();
  958. if (is_expr)
  959. return NODEF(FUNCEXPR, NULL, params, captured, body);
  960. return NODEF(FUNCDEF, name, params, captured, body);
  961. }
  962. node_t *parse_stmt(list_t *tokens, size_t *pos) {
  963. if (MATCH(LCB)) {
  964. list_t *stmts = list_new();
  965. while (!AT(EOF) && !AT(RCB)) {
  966. node_t *n = parse_stmt(tokens, pos);
  967. MATCH(SEMI);
  968. list_push(stmts, n);
  969. }
  970. EXPECT(RCB, "}");
  971. return NODEL(BLOCK, stmts);
  972. } else if (MATCH(VAR))
  973. return parse_var(tokens, pos);
  974. else if (MATCH(IF))
  975. return parse_if(tokens, pos);
  976. else if (MATCH(FOR)) {
  977. node_t *a = NULL;
  978. node_t *b = NULL;
  979. node_t *c = NULL;
  980. if (!AT(LCB) && !AT(COLON)) {
  981. if (MATCH(VAR)) {
  982. a = parse_var(tokens, pos);
  983. EXPECT(SEMI, ";");
  984. b = parse_expr(tokens, pos);
  985. EXPECT(SEMI, ";");
  986. c = parse_expr(tokens, pos);
  987. } else a = parse_expr(tokens, pos);
  988. }
  989. node_t *d = BLOCK();
  990. return NODE4(FOR, a, b, c, d);
  991. } else if (MATCH(BREAK)) return NODE0(BREAK);
  992. else if (MATCH(CONTINUE)) return NODE0(CONTINUE);
  993. else if (MATCH(FUNC))
  994. return parse_func(tokens, pos, 0);
  995. else if (MATCH(RETURN)) {
  996. node_t *a = NULL;
  997. if (!AT(RCB) && !AT(EOF) && !CLIFF)
  998. a = parse_expr(tokens, pos);
  999. return NODE1(RETURN, a);
  1000. } else if (MATCH(DEFER)) {
  1001. node_t *a;
  1002. if (AT(LCB) || AT(COLON))
  1003. a = BLOCK();
  1004. else a = parse_stmt(tokens, pos);
  1005. return NODE1(DEFER, a);
  1006. } else if (MATCH(PASS)) return NODE0(PASS);
  1007. else if (MATCH(TRY)) {
  1008. node_t *a = BLOCK();
  1009. token_t *t = NULL;
  1010. EXPECT(CATCH, "catch");
  1011. if (!AT(COLON) && !AT(LCB)) {
  1012. if (!AT(NAME))
  1013. PARSE_ERROR("expected identifier");
  1014. t = tokens->data[(*pos)++];
  1015. }
  1016. node_t *b = BLOCK();
  1017. return NODE2t(TRY, a, b, t);
  1018. } else if (MATCH(THROW)) {
  1019. node_t *a = NULL;
  1020. if (!CLIFF)
  1021. a = parse_expr(tokens, pos);
  1022. return NODE1(THROW, a);
  1023. }
  1024. node_t *n = parse_expr(tokens, pos);
  1025. return NODE1(EXPRSTMT, n);
  1026. }
  1027. node_t *parse_program(list_t *tokens, size_t *pos) {
  1028. if (AT(EOF))
  1029. PARSE_ERROR("empty program");
  1030. list_t *stmts = list_new();
  1031. int flag = 0;
  1032. while (!AT(EOF) && *pos < tokens->length) {
  1033. node_t *n;
  1034. if (MATCH(REQUIRE)) {
  1035. if (flag)
  1036. PARSE_ERROR("misplaced require statement")
  1037. if (!AT(STRING))
  1038. PARSE_ERROR("expected string");
  1039. token_t *path = tokens->data[(*pos)++];
  1040. n = NODET(REQUIRE, path);
  1041. } else { n = parse_stmt(tokens, pos); flag = 1; }
  1042. MATCH(SEMI);
  1043. list_push(stmts, n);
  1044. }
  1045. return NODEL(PROGRAM, stmts);
  1046. }
  1047. node_t *parse(char *source) {
  1048. size_t pos = 0;
  1049. return parse_program(tokenize(source), &pos);
  1050. }
  1051. #define NEWGID() size_t gid = GID++
  1052. #define EMIT(fmt, ...) buffer_fmt(buf, (fmt), ##__VA_ARGS__);
  1053. #define BINOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, lstk, node->a); EMIT(", "); compile_node(gbuf, buf, ctx, lstk, node->b); EMIT(")"); }
  1054. #define UNOP(s) { EMIT("qi_" s "(state, "); compile_node(gbuf, buf, ctx, lstk, node->a); EMIT(")"); }
  1055. #define ASSIGN(lhs, rhs) {\
  1056. if ((lhs)->tag == N_LITERAL && (lhs)->t->tag == T_NAME) {\
  1057. EMIT("qi_set(state, false, \"%s\", ", (lhs)->t->text);\
  1058. rhs;\
  1059. EMIT(")");\
  1060. } else if ((lhs)->tag == N_INDEX) {\
  1061. EMIT("qi_index_set(state, false, ");\
  1062. compile_node(gbuf, buf, ctx, lstk, (lhs)->a);\
  1063. EMIT(", ");\
  1064. compile_node(gbuf, buf, ctx, lstk, (lhs)->b);\
  1065. EMIT(", ");\
  1066. rhs;\
  1067. EMIT(")");\
  1068. } else if ((lhs)->tag == N_MEMBER) {\
  1069. EMIT("qi_index_set(state, false, ");\
  1070. compile_node(gbuf, buf, ctx, lstk, (lhs)->a);\
  1071. EMIT(", qi_make_string(state, \"%s\"), ", (lhs)->t->text);\
  1072. rhs;\
  1073. EMIT(")");\
  1074. } else COMPILE_ERROR("illegal assignment left-hand side");\
  1075. }
  1076. #define COMPASSIGN(lhs, s, rhs) {\
  1077. ASSIGN(node->a, {\
  1078. EMIT("qi_%s(state, ", s);\
  1079. compile_node(gbuf, buf, ctx, lstk, (lhs));\
  1080. EMIT(", ");\
  1081. rhs;\
  1082. EMIT(")");\
  1083. });\
  1084. }
  1085. #define COMPILE_ERROR(fmt, ...) { format_error(GETFNAME(node->fi), GETSRC(node->fi), node->pos, fmt, ##__VA_ARGS__); exit(1); }
  1086. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, node_t *node);
  1087. void compile_list(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *seq) {
  1088. if (!seq || seq->length < 1) {
  1089. EMIT("NULL");
  1090. return;
  1091. }
  1092. buffer_t *tbuf = buffer_new();
  1093. NEWGID();
  1094. buffer_fmt(tbuf, "qi_list_t *__list%d(qi_state_t *state) {\n", gid);
  1095. buffer_fmt(tbuf, "qi_list_t *list = qi_list_make();\n");
  1096. for (size_t i = 0; i < seq->length; i++) {
  1097. buffer_fmt(tbuf, "qi_list_push(list, ");
  1098. compile_node(gbuf, tbuf, ctx, lstk, seq->data[i]);
  1099. buffer_fmt(tbuf, ");\n");
  1100. }
  1101. buffer_fmt(tbuf, "return list;\n");
  1102. buffer_fmt(tbuf, "}\n");
  1103. buffer_appendb(gbuf, tbuf);
  1104. EMIT("__list%d(state)", gid);
  1105. }
  1106. void compile_table(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, table_t *table) {
  1107. if (!table || table->used < 1) {
  1108. EMIT("NULL");
  1109. return;
  1110. }
  1111. buffer_t *tbuf = buffer_new();
  1112. NEWGID();
  1113. buffer_fmt(tbuf, "qi_table_t *__table%d(qi_state_t *state) {\n", gid);
  1114. buffer_fmt(tbuf, "qi_table_t *table = qi_table_make();\n");
  1115. table_iterate(table, {
  1116. buffer_fmt(tbuf, "qi_table_set(table, \"%s\", ", entry.key);
  1117. compile_node(gbuf, tbuf, ctx, lstk, entry.value);
  1118. buffer_fmt(tbuf, ");\n");
  1119. });
  1120. buffer_fmt(tbuf, "return table;\n");
  1121. buffer_fmt(tbuf, "}\n");
  1122. buffer_appendb(gbuf, tbuf);
  1123. EMIT("__table%d(state)", gid);
  1124. }
  1125. #define CTXPUSH(s) list_push(ctx, (s))
  1126. #define CTXPOP() list_pop(ctx)
  1127. int in_context(list_t *ctx, char *s) {
  1128. if (!ctx->length)
  1129. return 0;
  1130. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1131. if (strcmp(ctx->data[i], "gap") == 0)
  1132. break;
  1133. else if (strcmp(ctx->data[i], s) == 0)
  1134. return 1;
  1135. }
  1136. return 0;
  1137. }
  1138. size_t count_ctxs(list_t *ctx, char *s) {
  1139. if (!ctx->length)
  1140. return 0;
  1141. size_t k = 0;
  1142. for (ssize_t i = ctx->length - 1; i >= 0; i--) {
  1143. if (strcmp(ctx->data[i], "gap") == 0)
  1144. break;
  1145. else if (strcmp(ctx->data[i], s) == 0)
  1146. k++;
  1147. }
  1148. return k;
  1149. }
  1150. #define INCTX(s) (in_context(ctx, (s)))
  1151. #define SCOPESK (count_ctxs(ctx, "scope"))
  1152. #define TRAPSK (count_ctxs(ctx, "trap"))
  1153. #define LPUSH(i) stack_push(lstk, (i))
  1154. #define LPOP() stack_pop(lstk)
  1155. #define LID (lstk->data[lstk->length-1])
  1156. void compile_func(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, node_t *node) {
  1157. NEWGID();
  1158. buffer_t *tbuf = buffer_new();
  1159. buffer_fmt(tbuf, "qi_value_t *__func%d(qi_state_t *state, qi_size_t pargc, qi_list_t *pargs) {\n", gid);
  1160. CTXPUSH("gap");
  1161. CTXPUSH("func");
  1162. size_t optargc = 0;
  1163. if (node->h) {
  1164. table_iterate(node->h, {
  1165. list_t *pair = entry.value;
  1166. size_t argc = *(size_t *)pair->data[0];
  1167. if (pair->data[1]) {
  1168. optargc++;
  1169. buffer_fmt(tbuf, "qi_set(state, false, \"%s\", pargc >= %d? qi_list_index(pargs, %d): ", entry.key, argc+1, argc);
  1170. compile_node(gbuf, tbuf, ctx, lstk, pair->data[1]);
  1171. buffer_fmt(tbuf, ");\n");
  1172. } else
  1173. buffer_fmt(tbuf, "qi_set(state, false, \"%s\", qi_list_index(pargs, %d));\n", entry.key, argc);
  1174. argc++;
  1175. });
  1176. }
  1177. compile_node(gbuf, tbuf, ctx, lstk, node->a);
  1178. CTXPOP();
  1179. CTXPOP();
  1180. buffer_fmt(tbuf, "return state->nil;\n");
  1181. buffer_fmt(tbuf, "}\n");
  1182. buffer_appendb(gbuf, tbuf);
  1183. tbuf = buffer_new();
  1184. buffer_fmt(tbuf, "qi_make_function(state, \"%s\", %d, __func%d, ", node->t? node->t->text: "<anon>", !node->h? 0: (node->h->used - optargc), gid);
  1185. compile_table(gbuf, tbuf, ctx, lstk, node->h2);
  1186. buffer_fmt(tbuf, ")");
  1187. if (node->tag == N_FUNCEXPR) {
  1188. buffer_appendb(buf, tbuf);
  1189. return;
  1190. }
  1191. EMIT("qi_set(state, false, \"%s\", ", node->t->text);
  1192. buffer_appendb(buf, tbuf);
  1193. EMIT(");");
  1194. }
  1195. void compile_block(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, list_t *block) {
  1196. for (size_t i = 0; i < block->length; i++) {
  1197. node_t *n = block->data[i];
  1198. if (n->tag == N_FUNCDEF) {
  1199. compile_func(gbuf, buf, ctx, lstk, n);
  1200. EMIT("\n");
  1201. } else if (n->tag == N_VAR) {
  1202. table_iterate(n->h, {
  1203. EMIT("qi_decl(state, \"%s\", ", entry.key);
  1204. if (entry.value)
  1205. compile_node(gbuf, buf, ctx, lstk, entry.value);
  1206. else EMIT("state->nil");
  1207. EMIT(");\n");
  1208. });
  1209. }
  1210. }
  1211. for (size_t i = 0; i < block->length; i++) {
  1212. compile_node(gbuf, buf, ctx, lstk, block->data[i]);
  1213. EMIT("\n");
  1214. }
  1215. }
  1216. #define STD_SIZE 1
  1217. const char *STD[STD_SIZE][2] = {
  1218. {"std", "func head(l): return l[0]"},
  1219. };
  1220. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctk, stack_t *lstk);
  1221. void compile_node(buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk, node_t *node) {
  1222. switch (node->tag) {
  1223. case N_PROGRAM:
  1224. compile_block(gbuf, buf, ctx, lstk, node->l);
  1225. break;
  1226. case N_EXPRSTMT:
  1227. EMIT("(void)(");
  1228. compile_node(gbuf, buf, ctx, lstk, node->a);
  1229. EMIT(");");
  1230. break;
  1231. case N_BLOCK:
  1232. CTXPUSH("scope");
  1233. EMIT("qi_new_scope(state);\n");
  1234. compile_block(gbuf, buf, ctx, lstk, node->l);
  1235. EMIT("qi_old_scope(state);");
  1236. CTXPOP();
  1237. break;
  1238. case N_LITERAL:
  1239. switch (node->t->tag) {
  1240. case T_NUMBER:
  1241. EMIT("qi_make_number(state, %s)", node->t->text);
  1242. break;
  1243. case T_STRING:
  1244. if (!*(node->t->text)) {
  1245. EMIT("state->empty_string");
  1246. } else {
  1247. EMIT("qi_make_string(state, \"%s\")", node->t->text);
  1248. }
  1249. break;
  1250. case T_NAME:
  1251. EMIT("qi_get(state, \"%s\")", node->t->text);
  1252. break;
  1253. default:
  1254. COMPILE_ERROR("not yet implemented");
  1255. }
  1256. break;
  1257. case N_LIST:
  1258. EMIT("qi_make_list(state, ");
  1259. compile_list(gbuf, buf, ctx, lstk, node->l);
  1260. EMIT(")");
  1261. break;
  1262. case N_TUPLE:
  1263. EMIT("qi_make_tuple(state, ");
  1264. compile_list(gbuf, buf, ctx, lstk, node->l);
  1265. EMIT(")");
  1266. break;
  1267. case N_NILTUPLE: EMIT("state->empty_tuple"); break;
  1268. case N_TABLE:
  1269. EMIT("qi_make_table(state, ");
  1270. compile_table(gbuf, buf, ctx, lstk, node->h);
  1271. EMIT(")");
  1272. break;
  1273. case N_CALL:
  1274. EMIT("qi_call(state, ");
  1275. compile_node(gbuf, buf, ctx, lstk, node->a);
  1276. EMIT(", ");
  1277. compile_list(gbuf, buf, ctx, lstk, node->l);
  1278. EMIT(")");
  1279. break;
  1280. case N_MEMBER:
  1281. EMIT("qi_index(state, ");
  1282. compile_node(gbuf, buf, ctx, lstk, node->a);
  1283. EMIT(", qi_make_string(state, \"%s\"))", node->t->text);
  1284. break;
  1285. case N_INDEX:
  1286. EMIT("qi_index(state, ");
  1287. compile_node(gbuf, buf, ctx, lstk, node->a);
  1288. EMIT(", ");
  1289. compile_node(gbuf, buf, ctx, lstk, node->b);
  1290. EMIT(")");
  1291. break;
  1292. case N_ASSIGN: ASSIGN(node->a, compile_node(gbuf, buf, ctx, lstk, node->b)); break;
  1293. case N_ASSIGN_ADD: COMPASSIGN(node->a, "add", compile_node(gbuf, buf, ctx, lstk, node->b)); break;
  1294. case N_INC:
  1295. COMPASSIGN(node->a, "add", EMIT("state->one"));
  1296. break;
  1297. case N_DEC:
  1298. COMPASSIGN(node->a, "sub", EMIT("state->one"));
  1299. break;
  1300. case N_VAR: break;
  1301. case N_IF:
  1302. EMIT("if (_qi_truthy(state, ");
  1303. compile_node(gbuf, buf, ctx, lstk, node->a);
  1304. EMIT(")) {\n");
  1305. CTXPUSH("scope");
  1306. EMIT("qi_new_scope(state);\n");
  1307. compile_node(gbuf, buf, ctx, lstk, node->b);
  1308. EMIT("qi_old_scope(state);\n");
  1309. CTXPOP();
  1310. if (node->c) {
  1311. EMIT("} else {\n");
  1312. CTXPUSH("scope");
  1313. EMIT("qi_new_scope(state);\n");
  1314. compile_node(gbuf, buf, ctx, lstk, node->c);
  1315. EMIT("qi_old_scope(state);\n");
  1316. CTXPOP();
  1317. }
  1318. EMIT("}");
  1319. break;
  1320. case N_FOR: {
  1321. NEWGID();
  1322. CTXPUSH("scope");
  1323. EMIT("qi_new_scope(state);\n");
  1324. if (!node->a) {
  1325. EMIT("for (;;) {\n");
  1326. } else if (node->a && !node->b) {
  1327. EMIT("while (_qi_truthy(state, ");
  1328. compile_node(gbuf, buf, ctx, lstk, node->a);
  1329. EMIT(")) {\n");
  1330. } else {
  1331. compile_node(gbuf, buf, ctx, lstk, node->a);
  1332. EMIT("while (_qi_truthy(state, ");
  1333. compile_node(gbuf, buf, ctx, lstk, node->b);
  1334. EMIT(")) {\n");
  1335. }
  1336. LPUSH(gid);
  1337. CTXPUSH("for");
  1338. compile_node(gbuf, buf, ctx, lstk, node->d);
  1339. CTXPOP();
  1340. LPOP();
  1341. EMIT("__continue%d:;\n", gid);
  1342. if (node->c)
  1343. compile_node(gbuf, buf, ctx, lstk, node->c);
  1344. EMIT("}\n");
  1345. EMIT("__break%d:;\n", gid);
  1346. EMIT("qi_old_scope(state);\n");
  1347. CTXPOP();
  1348. } break;
  1349. case N_BREAK:
  1350. if (!INCTX("for"))
  1351. COMPILE_ERROR("break outside of a loop");
  1352. EMIT("goto __break%d;", LID);
  1353. break;
  1354. case N_CONTINUE:
  1355. if (!INCTX("for"))
  1356. COMPILE_ERROR("continue outside of a loop");
  1357. EMIT("goto __continue%d;", LID);
  1358. break;
  1359. case N_DEFER: {
  1360. NEWGID();
  1361. buffer_t *tbuf = buffer_new();
  1362. buffer_fmt(tbuf, "void __defer%d(qi_state_t *state) {\n", gid);
  1363. CTXPUSH("gap");
  1364. compile_node(gbuf, tbuf, ctx, lstk, node->a);
  1365. CTXPOP();
  1366. buffer_fmt(tbuf, "\n");
  1367. buffer_fmt(tbuf, "}\n");
  1368. buffer_appendb(gbuf, tbuf);
  1369. EMIT("qi_add_defer(state, -1, __defer%d);", gid);
  1370. } break;
  1371. case N_RETURN:
  1372. if (!INCTX("func"))
  1373. COMPILE_ERROR("return outside of a function");
  1374. for (size_t i = 0; i < SCOPESK; i++)
  1375. EMIT("qi_old_scope(state);\n");
  1376. for (size_t i = 0; i < TRAPSK; i++)
  1377. EMIT("qi_unset_trap(state, trap);\n");
  1378. EMIT("return ");
  1379. if (node->a)
  1380. compile_node(gbuf, buf, ctx, lstk, node->a);
  1381. else EMIT("state->nil");
  1382. EMIT(";");
  1383. break;
  1384. case N_FUNCDEF: break;
  1385. case N_PASS: break;
  1386. case N_TRY:
  1387. CTXPUSH("scope");
  1388. EMIT("qi_new_scope(state);\n");
  1389. EMIT("qi_try(state, {\n");
  1390. compile_node(gbuf, buf, ctx, lstk, node->a);
  1391. EMIT("}, {\n");
  1392. if (node->t)
  1393. EMIT("qi_decl(state, \"%s\", trap->value);\n", node->t->text);
  1394. CTXPUSH("trap");
  1395. compile_node(gbuf, buf, ctx, lstk, node->b);
  1396. CTXPOP();
  1397. EMIT("}, NULL);\n");
  1398. EMIT("qi_new_scope(state);");
  1399. CTXPOP();
  1400. break;
  1401. case N_THROW:
  1402. EMIT("qi_throw(state, ");
  1403. if (node->a)
  1404. compile_node(gbuf, buf, ctx, lstk, node->a);
  1405. else {
  1406. EMIT("state->nil");
  1407. }
  1408. EMIT(");");
  1409. break;
  1410. case N_REQUIRE: {
  1411. char *source = NULL;
  1412. char *path = node->t->text;
  1413. for (size_t i = 0; i < STD_SIZE; i++) {
  1414. if (strcmp(path, STD[i][0]) == 0) {
  1415. source = (char *)STD[i][1];
  1416. break;
  1417. }
  1418. }
  1419. if (is_required(path))
  1420. break;
  1421. if (!source) {
  1422. FILE *fd = fopen(path, "rb");
  1423. if (!fd)
  1424. COMPILE_ERROR("failed to open: `%s'", path);
  1425. buffer_t *fbuf = buffer_new();
  1426. for (;;) {
  1427. char line[512];
  1428. if (!fgets(line, sizeof(line), fd))
  1429. break;
  1430. buffer_appends(fbuf, line);
  1431. }
  1432. source = buffer_read(fbuf);
  1433. path = realpath(path, NULL);
  1434. }
  1435. list_t *pair = list_new();
  1436. list_push(pair, path);
  1437. list_push(pair, source);
  1438. list_push(FILES, pair);
  1439. compile_into(source, gbuf, buf, ctx, lstk);
  1440. list_pop(FILES);
  1441. list_push(REQUIRED, path);
  1442. } break;
  1443. case N_IFEXPR:
  1444. EMIT("(_qi_truthy(state, ");
  1445. compile_node(gbuf, buf, ctx, lstk, node->a);
  1446. EMIT(")? ");
  1447. compile_node(gbuf, buf, ctx, lstk, node->b);
  1448. EMIT(": ");
  1449. compile_node(gbuf, buf, ctx, lstk, node->c);
  1450. EMIT(")");
  1451. break;
  1452. case N_FUNCEXPR:
  1453. compile_func(gbuf, buf, ctx, lstk, node);
  1454. break;
  1455. case N_EQUALS:
  1456. BINOP("equals");
  1457. break;
  1458. case N_LT:
  1459. BINOP("lt");
  1460. break;
  1461. case N_GT:
  1462. BINOP("gt");
  1463. break;
  1464. case N_ADD:
  1465. BINOP("add");
  1466. break;
  1467. case N_SUB:
  1468. BINOP("sub");
  1469. break;
  1470. case N_MUL:
  1471. BINOP("mul");
  1472. break;
  1473. case N_DIV:
  1474. BINOP("div");
  1475. break;
  1476. case N_IDIV:
  1477. BINOP("idiv");
  1478. break;
  1479. case N_POW:
  1480. BINOP("pow");
  1481. break;
  1482. case N_NEGATE:
  1483. UNOP("negate");
  1484. break;
  1485. default:
  1486. COMPILE_ERROR("not yet implemented");
  1487. }
  1488. }
  1489. void compile_into(char *source, buffer_t *gbuf, buffer_t *buf, list_t *ctx, stack_t *lstk) {
  1490. node_t *n = parse(source);
  1491. compile_node(gbuf, buf, ctx, lstk, n);
  1492. }
  1493. char *compile(char *source) {
  1494. list_t *ctx = list_new();
  1495. stack_t *lstk = stack_new();
  1496. buffer_t *gbuf = buffer_new();
  1497. buffer_appends(gbuf, "#include <qirt.h>\n");
  1498. buffer_t *buf = buffer_new();
  1499. compile_into(source, gbuf, buf, ctx, lstk);
  1500. buffer_t *rbuf = buffer_new();
  1501. buffer_appendb(rbuf, gbuf);
  1502. buffer_appends(rbuf, "int main(int argc, char **argv) {\n");
  1503. buffer_appends(rbuf, "qi_state_t *state;\n");
  1504. buffer_appends(rbuf, "qi_state_init(&state);\n");
  1505. buffer_appendb(rbuf, buf);
  1506. buffer_appends(rbuf, "qi_old_scope(state);\n");
  1507. buffer_appends(rbuf, "qi_finalize();\n");
  1508. buffer_appends(rbuf, "return 0;\n");
  1509. buffer_appends(rbuf, "}\n");
  1510. return buffer_read(rbuf);
  1511. }
  1512. char *compile_file(char *filename, FILE *fd) {
  1513. buffer_t *buf = buffer_new();
  1514. for (;;) {
  1515. char line[512];
  1516. if (!fgets(line, sizeof(line), fd))
  1517. break;
  1518. buffer_appends(buf, line);
  1519. }
  1520. char *source = buffer_read(buf);
  1521. list_t *pair = list_new();
  1522. list_push(pair, filename);
  1523. list_push(pair, source);
  1524. list_push(FILES, pair);
  1525. char *out = compile(source);
  1526. list_pop(FILES);
  1527. return out;
  1528. }
  1529. int main(int argc, char **argv) {
  1530. FILES = list_new();
  1531. REQUIRED = list_new();
  1532. char *out = compile_file("<stdin>", stdin);
  1533. fwrite(out, sizeof(char), strlen(out), stdout);
  1534. return 0;
  1535. }