qic.c 111 KB

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