qic.c 103 KB

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