qic.c 105 KB

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