compiler.c 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  1. #include "pocketpy/compiler/compiler.h"
  2. #include "pocketpy/common/vector.h"
  3. #include "pocketpy/common/name.h"
  4. #include "pocketpy/compiler/lexer.h"
  5. #include "pocketpy/objects/base.h"
  6. #include "pocketpy/objects/codeobject.h"
  7. #include "pocketpy/objects/sourcedata.h"
  8. #include "pocketpy/common/sstream.h"
  9. #include <assert.h>
  10. #include <stdbool.h>
  11. /* expr.h */
  12. typedef struct Expr Expr;
  13. typedef struct Ctx Ctx;
  14. typedef struct ExprVt {
  15. /* emit */
  16. void (*emit_)(Expr*, Ctx*);
  17. bool (*emit_del)(Expr*, Ctx*);
  18. bool (*emit_store)(Expr*, Ctx*);
  19. void (*emit_inplace)(Expr*, Ctx*);
  20. bool (*emit_istore)(Expr*, Ctx*);
  21. /* reflections */
  22. bool is_literal;
  23. bool is_name; // NameExpr
  24. bool is_tuple; // TupleExpr
  25. bool is_attrib; // AttribExpr
  26. bool is_subscr; // SubscrExpr
  27. bool is_starred; // StarredExpr
  28. bool is_binary; // BinaryExpr
  29. bool is_ternary; // TernaryExpr
  30. void (*dtor)(Expr*);
  31. } ExprVt;
  32. #define vtcall(f, self, ctx) ((self)->vt->f((self), (ctx)))
  33. #define vtemit_(self, ctx) vtcall(emit_, (self), (ctx))
  34. #define vtemit_del(self, ctx) ((self)->vt->emit_del ? vtcall(emit_del, self, ctx) : false)
  35. #define vtemit_store(self, ctx) ((self)->vt->emit_store ? vtcall(emit_store, self, ctx) : false)
  36. #define vtemit_inplace(self, ctx) \
  37. ((self)->vt->emit_inplace ? vtcall(emit_inplace, self, ctx) : vtemit_(self, ctx))
  38. #define vtemit_istore(self, ctx) \
  39. ((self)->vt->emit_istore ? vtcall(emit_istore, self, ctx) : vtemit_store(self, ctx))
  40. #define vtdelete(self) \
  41. do { \
  42. if(self) { \
  43. if((self)->vt->dtor) (self)->vt->dtor(self); \
  44. PK_FREE(self); \
  45. } \
  46. } while(0)
  47. #define EXPR_COMMON_HEADER \
  48. const ExprVt* vt; \
  49. int line;
  50. typedef struct Expr {
  51. EXPR_COMMON_HEADER
  52. } Expr;
  53. /* context.h */
  54. typedef struct Ctx {
  55. CodeObject* co; // 1 CodeEmitContext <=> 1 CodeObject*
  56. FuncDecl* func; // optional, weakref
  57. py_Name n_self;
  58. int level;
  59. int curr_iblock;
  60. bool is_compiling_class;
  61. c11_vector /*T=Expr_p*/ s_expr;
  62. c11_smallmap_n2d global_names;
  63. c11_smallmap_v2d co_consts_string_dedup_map; // this stores 0-based index instead of pointer
  64. } Ctx;
  65. typedef struct Expr Expr;
  66. static void Ctx__ctor(Ctx* self, CodeObject* co, FuncDecl* func, int level, py_Name n_self);
  67. static void Ctx__dtor(Ctx* self);
  68. static int Ctx__prepare_loop_divert(Ctx* self, int line, bool is_break);
  69. static int Ctx__enter_block(Ctx* self, CodeBlockType type);
  70. static void Ctx__exit_block(Ctx* self);
  71. static int Ctx__emit_(Ctx* self, Opcode opcode, uint16_t arg, int line);
  72. static int Ctx__emit_int(Ctx* self, int64_t value, int line);
  73. static int Ctx__emit_name(Ctx* self, py_Name name, int line);
  74. static void Ctx__patch_jump(Ctx* self, int index);
  75. static void Ctx__emit_jump(Ctx* self, int target, int line);
  76. static int Ctx__add_varname(Ctx* self, py_Name name);
  77. static int Ctx__add_name(Ctx* self, py_Name name);
  78. static int Ctx__add_const(Ctx* self, py_Ref);
  79. static int Ctx__add_const_string(Ctx* self, c11_sv);
  80. static void Ctx__emit_store_name(Ctx* self, NameScope scope, py_Name name, int line);
  81. static void Ctx__s_emit_top(Ctx*); // emit top -> pop -> delete
  82. static void Ctx__s_push(Ctx*, Expr*); // push
  83. static Expr* Ctx__s_top(Ctx*); // top
  84. static int Ctx__s_size(Ctx*); // size
  85. static void Ctx__s_pop(Ctx*); // pop -> delete
  86. static Expr* Ctx__s_popx(Ctx*); // pop move
  87. static void Ctx__s_emit_decorators(Ctx*, int count);
  88. /* expr.c */
  89. typedef struct NameExpr {
  90. EXPR_COMMON_HEADER
  91. py_Name name;
  92. NameScope scope;
  93. } NameExpr;
  94. void NameExpr__emit_(Expr* self_, Ctx* ctx) {
  95. NameExpr* self = (NameExpr*)self_;
  96. int index = c11_smallmap_n2d__get(&ctx->co->varnames_inv, self->name, -1);
  97. if(self->scope == NAME_LOCAL && index >= 0) {
  98. // we know this is a local variable
  99. Ctx__emit_(ctx, OP_LOAD_FAST, index, self->line);
  100. } else {
  101. Opcode op = ctx->level <= 1 ? OP_LOAD_GLOBAL : OP_LOAD_NONLOCAL;
  102. if(self->scope == NAME_GLOBAL) {
  103. if(ctx->co->src->is_dynamic) {
  104. op = OP_LOAD_NAME;
  105. } else {
  106. if(ctx->is_compiling_class) {
  107. // if we are compiling a class, we should use `OP_LOAD_CLASS_GLOBAL`
  108. // this is for @property.setter
  109. op = OP_LOAD_CLASS_GLOBAL;
  110. }
  111. }
  112. }
  113. Ctx__emit_(ctx, op, Ctx__add_name(ctx, self->name), self->line);
  114. }
  115. }
  116. bool NameExpr__emit_del(Expr* self_, Ctx* ctx) {
  117. NameExpr* self = (NameExpr*)self_;
  118. switch(self->scope) {
  119. case NAME_LOCAL:
  120. Ctx__emit_(ctx, OP_DELETE_FAST, Ctx__add_varname(ctx, self->name), self->line);
  121. break;
  122. case NAME_GLOBAL: {
  123. Opcode op = ctx->co->src->is_dynamic ? OP_DELETE_NAME : OP_DELETE_GLOBAL;
  124. Ctx__emit_(ctx, op, Ctx__add_name(ctx, self->name), self->line);
  125. break;
  126. }
  127. default: c11__unreachable();
  128. }
  129. return true;
  130. }
  131. bool NameExpr__emit_store(Expr* self_, Ctx* ctx) {
  132. NameExpr* self = (NameExpr*)self_;
  133. if(ctx->is_compiling_class) {
  134. Ctx__emit_(ctx, OP_STORE_CLASS_ATTR, Ctx__add_name(ctx, self->name), self->line);
  135. return true;
  136. }
  137. Ctx__emit_store_name(ctx, self->scope, self->name, self->line);
  138. return true;
  139. }
  140. NameExpr* NameExpr__new(int line, py_Name name, NameScope scope) {
  141. const static ExprVt Vt = {.emit_ = NameExpr__emit_,
  142. .emit_del = NameExpr__emit_del,
  143. .emit_store = NameExpr__emit_store,
  144. .is_name = true};
  145. NameExpr* self = PK_MALLOC(sizeof(NameExpr));
  146. self->vt = &Vt;
  147. self->line = line;
  148. self->name = name;
  149. self->scope = scope;
  150. return self;
  151. }
  152. typedef struct StarredExpr {
  153. EXPR_COMMON_HEADER
  154. Expr* child;
  155. int level;
  156. } StarredExpr;
  157. void StarredExpr__emit_(Expr* self_, Ctx* ctx) {
  158. StarredExpr* self = (StarredExpr*)self_;
  159. vtemit_(self->child, ctx);
  160. Ctx__emit_(ctx, OP_UNARY_STAR, self->level, self->line);
  161. }
  162. bool StarredExpr__emit_store(Expr* self_, Ctx* ctx) {
  163. StarredExpr* self = (StarredExpr*)self_;
  164. if(self->level != 1) return false;
  165. // simply proxy to child
  166. return vtemit_store(self->child, ctx);
  167. }
  168. void StarredExpr__dtor(Expr* self_) {
  169. StarredExpr* self = (StarredExpr*)self_;
  170. vtdelete(self->child);
  171. }
  172. StarredExpr* StarredExpr__new(int line, Expr* child, int level) {
  173. const static ExprVt Vt = {.emit_ = StarredExpr__emit_,
  174. .emit_store = StarredExpr__emit_store,
  175. .is_starred = true,
  176. .dtor = StarredExpr__dtor};
  177. StarredExpr* self = PK_MALLOC(sizeof(StarredExpr));
  178. self->vt = &Vt;
  179. self->line = line;
  180. self->child = child;
  181. self->level = level;
  182. return self;
  183. }
  184. // InvertExpr, NotExpr, NegatedExpr
  185. // NOTE: NegatedExpr always contains a non-const child. Should not generate -1 or -0.1
  186. typedef struct UnaryExpr {
  187. EXPR_COMMON_HEADER
  188. Expr* child;
  189. Opcode opcode;
  190. } UnaryExpr;
  191. void UnaryExpr__dtor(Expr* self_) {
  192. UnaryExpr* self = (UnaryExpr*)self_;
  193. vtdelete(self->child);
  194. }
  195. static void UnaryExpr__emit_(Expr* self_, Ctx* ctx) {
  196. UnaryExpr* self = (UnaryExpr*)self_;
  197. vtemit_(self->child, ctx);
  198. Ctx__emit_(ctx, self->opcode, BC_NOARG, self->line);
  199. }
  200. UnaryExpr* UnaryExpr__new(int line, Expr* child, Opcode opcode) {
  201. const static ExprVt Vt = {.emit_ = UnaryExpr__emit_, .dtor = UnaryExpr__dtor};
  202. UnaryExpr* self = PK_MALLOC(sizeof(UnaryExpr));
  203. self->vt = &Vt;
  204. self->line = line;
  205. self->child = child;
  206. self->opcode = opcode;
  207. return self;
  208. }
  209. typedef struct FStringSpecExpr {
  210. EXPR_COMMON_HEADER
  211. Expr* child;
  212. c11_sv spec;
  213. } FStringSpecExpr;
  214. void FStringSpecExpr__emit_(Expr* self_, Ctx* ctx) {
  215. FStringSpecExpr* self = (FStringSpecExpr*)self_;
  216. vtemit_(self->child, ctx);
  217. int index = Ctx__add_const_string(ctx, self->spec);
  218. Ctx__emit_(ctx, OP_FORMAT_STRING, index, self->line);
  219. }
  220. FStringSpecExpr* FStringSpecExpr__new(int line, Expr* child, c11_sv spec) {
  221. const static ExprVt Vt = {.emit_ = FStringSpecExpr__emit_, .dtor = UnaryExpr__dtor};
  222. FStringSpecExpr* self = PK_MALLOC(sizeof(FStringSpecExpr));
  223. self->vt = &Vt;
  224. self->line = line;
  225. self->child = child;
  226. self->spec = spec;
  227. return self;
  228. }
  229. typedef struct RawStringExpr {
  230. EXPR_COMMON_HEADER
  231. c11_sv value;
  232. Opcode opcode;
  233. } RawStringExpr;
  234. void RawStringExpr__emit_(Expr* self_, Ctx* ctx) {
  235. RawStringExpr* self = (RawStringExpr*)self_;
  236. int index = Ctx__add_const_string(ctx, self->value);
  237. Ctx__emit_(ctx, self->opcode, index, self->line);
  238. }
  239. RawStringExpr* RawStringExpr__new(int line, c11_sv value, Opcode opcode) {
  240. const static ExprVt Vt = {.emit_ = RawStringExpr__emit_};
  241. RawStringExpr* self = PK_MALLOC(sizeof(RawStringExpr));
  242. self->vt = &Vt;
  243. self->line = line;
  244. self->value = value;
  245. self->opcode = opcode;
  246. return self;
  247. }
  248. typedef struct ImagExpr {
  249. EXPR_COMMON_HEADER
  250. double value;
  251. } ImagExpr;
  252. void ImagExpr__emit_(Expr* self_, Ctx* ctx) {
  253. ImagExpr* self = (ImagExpr*)self_;
  254. py_TValue value;
  255. py_newfloat(&value, self->value);
  256. int index = Ctx__add_const(ctx, &value);
  257. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  258. Ctx__emit_(ctx, OP_BUILD_IMAG, BC_NOARG, self->line);
  259. }
  260. ImagExpr* ImagExpr__new(int line, double value) {
  261. const static ExprVt Vt = {.emit_ = ImagExpr__emit_};
  262. ImagExpr* self = PK_MALLOC(sizeof(ImagExpr));
  263. self->vt = &Vt;
  264. self->line = line;
  265. self->value = value;
  266. return self;
  267. }
  268. typedef struct LiteralExpr {
  269. EXPR_COMMON_HEADER
  270. const TokenValue* value;
  271. bool negated;
  272. } LiteralExpr;
  273. void LiteralExpr__emit_(Expr* self_, Ctx* ctx) {
  274. LiteralExpr* self = (LiteralExpr*)self_;
  275. switch(self->value->index) {
  276. case TokenValue_I64: {
  277. py_i64 val = self->value->_i64;
  278. if(self->negated) val = -val;
  279. Ctx__emit_int(ctx, val, self->line);
  280. break;
  281. }
  282. case TokenValue_F64: {
  283. py_TValue value;
  284. py_f64 val = self->value->_f64;
  285. if(self->negated) val = -val;
  286. py_newfloat(&value, val);
  287. int index = Ctx__add_const(ctx, &value);
  288. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  289. break;
  290. }
  291. case TokenValue_STR: {
  292. assert(!self->negated);
  293. c11_sv sv = c11_string__sv(self->value->_str);
  294. int index = Ctx__add_const_string(ctx, sv);
  295. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  296. break;
  297. }
  298. default: c11__unreachable();
  299. }
  300. }
  301. LiteralExpr* LiteralExpr__new(int line, const TokenValue* value) {
  302. const static ExprVt Vt = {.emit_ = LiteralExpr__emit_, .is_literal = true};
  303. LiteralExpr* self = PK_MALLOC(sizeof(LiteralExpr));
  304. self->vt = &Vt;
  305. self->line = line;
  306. self->value = value;
  307. self->negated = false;
  308. return self;
  309. }
  310. typedef struct Literal0Expr {
  311. EXPR_COMMON_HEADER
  312. TokenIndex token;
  313. } Literal0Expr;
  314. void Literal0Expr__emit_(Expr* self_, Ctx* ctx) {
  315. Literal0Expr* self = (Literal0Expr*)self_;
  316. Opcode opcode;
  317. switch(self->token) {
  318. case TK_NONE: opcode = OP_LOAD_NONE; break;
  319. case TK_TRUE: opcode = OP_LOAD_TRUE; break;
  320. case TK_FALSE: opcode = OP_LOAD_FALSE; break;
  321. case TK_DOTDOTDOT: opcode = OP_LOAD_ELLIPSIS; break;
  322. default: c11__unreachable();
  323. }
  324. Ctx__emit_(ctx, opcode, BC_NOARG, self->line);
  325. }
  326. Literal0Expr* Literal0Expr__new(int line, TokenIndex token) {
  327. const static ExprVt Vt = {.emit_ = Literal0Expr__emit_};
  328. Literal0Expr* self = PK_MALLOC(sizeof(Literal0Expr));
  329. self->vt = &Vt;
  330. self->line = line;
  331. self->token = token;
  332. return self;
  333. }
  334. typedef struct LoadConstExpr {
  335. EXPR_COMMON_HEADER
  336. int index;
  337. } LoadConstExpr;
  338. void LoadConstExpr__emit_(Expr* self_, Ctx* ctx) {
  339. LoadConstExpr* self = (LoadConstExpr*)self_;
  340. Ctx__emit_(ctx, OP_LOAD_CONST, self->index, self->line);
  341. }
  342. LoadConstExpr* LoadConstExpr__new(int line, int index) {
  343. const static ExprVt Vt = {.emit_ = LoadConstExpr__emit_};
  344. LoadConstExpr* self = PK_MALLOC(sizeof(LoadConstExpr));
  345. self->vt = &Vt;
  346. self->line = line;
  347. self->index = index;
  348. return self;
  349. }
  350. typedef struct SliceExpr {
  351. EXPR_COMMON_HEADER
  352. Expr* start;
  353. Expr* stop;
  354. Expr* step;
  355. } SliceExpr;
  356. void SliceExpr__dtor(Expr* self_) {
  357. SliceExpr* self = (SliceExpr*)self_;
  358. vtdelete(self->start);
  359. vtdelete(self->stop);
  360. vtdelete(self->step);
  361. }
  362. void SliceExpr__emit_(Expr* self_, Ctx* ctx) {
  363. SliceExpr* self = (SliceExpr*)self_;
  364. if(self->start)
  365. vtemit_(self->start, ctx);
  366. else
  367. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  368. if(self->stop)
  369. vtemit_(self->stop, ctx);
  370. else
  371. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  372. if(self->step)
  373. vtemit_(self->step, ctx);
  374. else
  375. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  376. Ctx__emit_(ctx, OP_BUILD_SLICE, BC_NOARG, self->line);
  377. }
  378. SliceExpr* SliceExpr__new(int line) {
  379. const static ExprVt Vt = {.dtor = SliceExpr__dtor, .emit_ = SliceExpr__emit_};
  380. SliceExpr* self = PK_MALLOC(sizeof(SliceExpr));
  381. self->vt = &Vt;
  382. self->line = line;
  383. self->start = NULL;
  384. self->stop = NULL;
  385. self->step = NULL;
  386. return self;
  387. }
  388. typedef struct DictItemExpr {
  389. EXPR_COMMON_HEADER
  390. Expr* key;
  391. Expr* value;
  392. } DictItemExpr;
  393. static void DictItemExpr__dtor(Expr* self_) {
  394. DictItemExpr* self = (DictItemExpr*)self_;
  395. vtdelete(self->key);
  396. vtdelete(self->value);
  397. }
  398. static void DictItemExpr__emit_(Expr* self_, Ctx* ctx) {
  399. DictItemExpr* self = (DictItemExpr*)self_;
  400. vtemit_(self->key, ctx);
  401. vtemit_(self->value, ctx);
  402. }
  403. static DictItemExpr* DictItemExpr__new(int line) {
  404. const static ExprVt Vt = {.dtor = DictItemExpr__dtor, .emit_ = DictItemExpr__emit_};
  405. DictItemExpr* self = PK_MALLOC(sizeof(DictItemExpr));
  406. self->vt = &Vt;
  407. self->line = line;
  408. self->key = NULL;
  409. self->value = NULL;
  410. return self;
  411. }
  412. // ListExpr, DictExpr, SetExpr, TupleExpr
  413. typedef struct SequenceExpr {
  414. EXPR_COMMON_HEADER
  415. Expr** items;
  416. int itemCount;
  417. Opcode opcode;
  418. } SequenceExpr;
  419. static void SequenceExpr__emit_(Expr* self_, Ctx* ctx) {
  420. SequenceExpr* self = (SequenceExpr*)self_;
  421. for(int i = 0; i < self->itemCount; i++) {
  422. Expr* item = self->items[i];
  423. vtemit_(item, ctx);
  424. }
  425. Ctx__emit_(ctx, self->opcode, self->itemCount, self->line);
  426. }
  427. void SequenceExpr__dtor(Expr* self_) {
  428. SequenceExpr* self = (SequenceExpr*)self_;
  429. for(int i = 0; i < self->itemCount; i++) {
  430. vtdelete(self->items[i]);
  431. }
  432. PK_FREE(self->items);
  433. }
  434. bool TupleExpr__emit_store(Expr* self_, Ctx* ctx) {
  435. SequenceExpr* self = (SequenceExpr*)self_;
  436. // TOS is an iterable
  437. // items may contain StarredExpr, we should check it
  438. int starred_i = -1;
  439. for(int i = 0; i < self->itemCount; i++) {
  440. Expr* e = self->items[i];
  441. if(e->vt->is_starred) {
  442. if(((StarredExpr*)e)->level > 0) {
  443. if(starred_i == -1)
  444. starred_i = i;
  445. else
  446. return false; // multiple StarredExpr not allowed
  447. }
  448. }
  449. }
  450. if(starred_i == -1) {
  451. Ctx__emit_(ctx, OP_UNPACK_SEQUENCE, self->itemCount, self->line);
  452. } else {
  453. // starred assignment target must be in a tuple
  454. if(self->itemCount == 1) return false;
  455. // starred assignment target must be the last one (differ from cpython)
  456. if(starred_i != self->itemCount - 1) return false;
  457. // a,*b = [1,2,3]
  458. // stack is [1,2,3] -> [1,[2,3]]
  459. Ctx__emit_(ctx, OP_UNPACK_EX, self->itemCount - 1, self->line);
  460. }
  461. // do reverse emit
  462. for(int i = self->itemCount - 1; i >= 0; i--) {
  463. Expr* e = self->items[i];
  464. bool ok = vtemit_store(e, ctx);
  465. if(!ok) return false;
  466. }
  467. return true;
  468. }
  469. bool TupleExpr__emit_del(Expr* self_, Ctx* ctx) {
  470. SequenceExpr* self = (SequenceExpr*)self_;
  471. for(int i = 0; i < self->itemCount; i++) {
  472. Expr* e = self->items[i];
  473. bool ok = vtemit_del(e, ctx);
  474. if(!ok) return false;
  475. }
  476. return true;
  477. }
  478. static SequenceExpr* SequenceExpr__new(int line, const ExprVt* vt, int count, Opcode opcode) {
  479. SequenceExpr* self = PK_MALLOC(sizeof(SequenceExpr));
  480. self->vt = vt;
  481. self->line = line;
  482. self->opcode = opcode;
  483. self->items = PK_MALLOC(sizeof(Expr*) * count);
  484. self->itemCount = count;
  485. return self;
  486. }
  487. SequenceExpr* FStringExpr__new(int line, int count) {
  488. const static ExprVt ListExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  489. return SequenceExpr__new(line, &ListExprVt, count, OP_BUILD_STRING);
  490. }
  491. SequenceExpr* ListExpr__new(int line, int count) {
  492. const static ExprVt ListExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  493. return SequenceExpr__new(line, &ListExprVt, count, OP_BUILD_LIST);
  494. }
  495. SequenceExpr* DictExpr__new(int line, int count) {
  496. const static ExprVt DictExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  497. return SequenceExpr__new(line, &DictExprVt, count, OP_BUILD_DICT);
  498. }
  499. SequenceExpr* SetExpr__new(int line, int count) {
  500. const static ExprVt SetExprVt = {
  501. .dtor = SequenceExpr__dtor,
  502. .emit_ = SequenceExpr__emit_,
  503. };
  504. return SequenceExpr__new(line, &SetExprVt, count, OP_BUILD_SET);
  505. }
  506. SequenceExpr* TupleExpr__new(int line, int count) {
  507. const static ExprVt TupleExprVt = {.dtor = SequenceExpr__dtor,
  508. .emit_ = SequenceExpr__emit_,
  509. .is_tuple = true,
  510. .emit_store = TupleExpr__emit_store,
  511. .emit_del = TupleExpr__emit_del};
  512. return SequenceExpr__new(line, &TupleExprVt, count, OP_BUILD_TUPLE);
  513. }
  514. typedef struct CompExpr {
  515. EXPR_COMMON_HEADER
  516. Expr* expr; // loop expr
  517. Expr* vars; // loop vars
  518. Expr* iter; // loop iter
  519. Expr* cond; // optional if condition
  520. Opcode op0;
  521. Opcode op1;
  522. } CompExpr;
  523. void CompExpr__dtor(Expr* self_) {
  524. CompExpr* self = (CompExpr*)self_;
  525. vtdelete(self->expr);
  526. vtdelete(self->vars);
  527. vtdelete(self->iter);
  528. vtdelete(self->cond);
  529. }
  530. void CompExpr__emit_(Expr* self_, Ctx* ctx) {
  531. CompExpr* self = (CompExpr*)self_;
  532. Ctx__emit_(ctx, self->op0, 0, self->line);
  533. vtemit_(self->iter, ctx);
  534. Ctx__emit_(ctx, OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  535. int block = Ctx__enter_block(ctx, CodeBlockType_FOR_LOOP);
  536. int block_start = Ctx__emit_(ctx, OP_FOR_ITER, block, BC_KEEPLINE);
  537. bool ok = vtemit_store(self->vars, ctx);
  538. // this error occurs in `vars` instead of this line, but...nevermind
  539. assert(ok); // this should raise a SyntaxError, but we just assert it
  540. if(self->cond) {
  541. vtemit_(self->cond, ctx);
  542. int patch = Ctx__emit_(ctx, OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  543. vtemit_(self->expr, ctx);
  544. Ctx__emit_(ctx, self->op1, BC_NOARG, BC_KEEPLINE);
  545. Ctx__patch_jump(ctx, patch);
  546. } else {
  547. vtemit_(self->expr, ctx);
  548. Ctx__emit_(ctx, self->op1, BC_NOARG, BC_KEEPLINE);
  549. }
  550. Ctx__emit_jump(ctx, block_start, BC_KEEPLINE);
  551. Ctx__exit_block(ctx);
  552. }
  553. CompExpr* CompExpr__new(int line, Opcode op0, Opcode op1) {
  554. const static ExprVt Vt = {.dtor = CompExpr__dtor, .emit_ = CompExpr__emit_};
  555. CompExpr* self = PK_MALLOC(sizeof(CompExpr));
  556. self->vt = &Vt;
  557. self->line = line;
  558. self->op0 = op0;
  559. self->op1 = op1;
  560. self->expr = NULL;
  561. self->vars = NULL;
  562. self->iter = NULL;
  563. self->cond = NULL;
  564. return self;
  565. }
  566. typedef struct LambdaExpr {
  567. EXPR_COMMON_HEADER
  568. int index;
  569. } LambdaExpr;
  570. static void LambdaExpr__emit_(Expr* self_, Ctx* ctx) {
  571. LambdaExpr* self = (LambdaExpr*)self_;
  572. Ctx__emit_(ctx, OP_LOAD_FUNCTION, self->index, self->line);
  573. }
  574. LambdaExpr* LambdaExpr__new(int line, int index) {
  575. const static ExprVt Vt = {.emit_ = LambdaExpr__emit_};
  576. LambdaExpr* self = PK_MALLOC(sizeof(LambdaExpr));
  577. self->vt = &Vt;
  578. self->line = line;
  579. self->index = index;
  580. return self;
  581. }
  582. // AndExpr, OrExpr
  583. typedef struct LogicBinaryExpr {
  584. EXPR_COMMON_HEADER
  585. Expr* lhs;
  586. Expr* rhs;
  587. Opcode opcode;
  588. } LogicBinaryExpr;
  589. void LogicBinaryExpr__dtor(Expr* self_) {
  590. LogicBinaryExpr* self = (LogicBinaryExpr*)self_;
  591. vtdelete(self->lhs);
  592. vtdelete(self->rhs);
  593. }
  594. void LogicBinaryExpr__emit_(Expr* self_, Ctx* ctx) {
  595. LogicBinaryExpr* self = (LogicBinaryExpr*)self_;
  596. vtemit_(self->lhs, ctx);
  597. int patch = Ctx__emit_(ctx, self->opcode, BC_NOARG, self->line);
  598. vtemit_(self->rhs, ctx);
  599. Ctx__patch_jump(ctx, patch);
  600. }
  601. LogicBinaryExpr* LogicBinaryExpr__new(int line, Opcode opcode) {
  602. const static ExprVt Vt = {.emit_ = LogicBinaryExpr__emit_, .dtor = LogicBinaryExpr__dtor};
  603. LogicBinaryExpr* self = PK_MALLOC(sizeof(LogicBinaryExpr));
  604. self->vt = &Vt;
  605. self->line = line;
  606. self->lhs = NULL;
  607. self->rhs = NULL;
  608. self->opcode = opcode;
  609. return self;
  610. }
  611. typedef struct GroupedExpr {
  612. EXPR_COMMON_HEADER
  613. Expr* child;
  614. } GroupedExpr;
  615. void GroupedExpr__dtor(Expr* self_) {
  616. GroupedExpr* self = (GroupedExpr*)self_;
  617. vtdelete(self->child);
  618. }
  619. void GroupedExpr__emit_(Expr* self_, Ctx* ctx) {
  620. GroupedExpr* self = (GroupedExpr*)self_;
  621. vtemit_(self->child, ctx);
  622. }
  623. bool GroupedExpr__emit_del(Expr* self_, Ctx* ctx) {
  624. GroupedExpr* self = (GroupedExpr*)self_;
  625. return vtemit_del(self->child, ctx);
  626. }
  627. bool GroupedExpr__emit_store(Expr* self_, Ctx* ctx) {
  628. GroupedExpr* self = (GroupedExpr*)self_;
  629. return vtemit_store(self->child, ctx);
  630. }
  631. GroupedExpr* GroupedExpr__new(int line, Expr* child) {
  632. const static ExprVt Vt = {.dtor = GroupedExpr__dtor,
  633. .emit_ = GroupedExpr__emit_,
  634. .emit_del = GroupedExpr__emit_del,
  635. .emit_store = GroupedExpr__emit_store};
  636. GroupedExpr* self = PK_MALLOC(sizeof(GroupedExpr));
  637. self->vt = &Vt;
  638. self->line = line;
  639. self->child = child;
  640. return self;
  641. }
  642. // NamedExpr: walrus operator (x := expr)
  643. typedef struct NamedExpr {
  644. EXPR_COMMON_HEADER
  645. NameExpr* name;
  646. Expr* rhs;
  647. } NamedExpr;
  648. static void NamedExpr__dtor(Expr* self_) {
  649. NamedExpr* self = (NamedExpr*)self_;
  650. vtdelete((Expr*)self->name);
  651. vtdelete(self->rhs);
  652. }
  653. static void NamedExpr__emit_(Expr* self_, Ctx* ctx) {
  654. NamedExpr* self = (NamedExpr*)self_;
  655. vtemit_(self->rhs, ctx); // [value]
  656. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line); // [value, value]
  657. vtemit_store((Expr*)self->name, ctx); // [value]
  658. }
  659. static NamedExpr* NamedExpr__new(int line, NameExpr* name, Expr* rhs) {
  660. const static ExprVt Vt = {.dtor = NamedExpr__dtor, .emit_ = NamedExpr__emit_};
  661. NamedExpr* self = PK_MALLOC(sizeof(NamedExpr));
  662. self->vt = &Vt;
  663. self->line = line;
  664. self->name = name;
  665. self->rhs = rhs;
  666. return self;
  667. }
  668. typedef struct BinaryExpr {
  669. EXPR_COMMON_HEADER
  670. Expr* lhs;
  671. Expr* rhs;
  672. TokenIndex op;
  673. bool inplace;
  674. } BinaryExpr;
  675. static void BinaryExpr__dtor(Expr* self_) {
  676. BinaryExpr* self = (BinaryExpr*)self_;
  677. vtdelete(self->lhs);
  678. vtdelete(self->rhs);
  679. }
  680. static Opcode cmp_token2op(TokenIndex token) {
  681. switch(token) {
  682. case TK_LT: return OP_COMPARE_LT;
  683. case TK_LE: return OP_COMPARE_LE;
  684. case TK_EQ: return OP_COMPARE_EQ;
  685. case TK_NE: return OP_COMPARE_NE;
  686. case TK_GT: return OP_COMPARE_GT;
  687. case TK_GE: return OP_COMPARE_GE;
  688. default: return 0;
  689. }
  690. }
  691. #define is_compare_expr(e) ((e)->vt->is_binary && cmp_token2op(((BinaryExpr*)(e))->op))
  692. static void _emit_compare(BinaryExpr* self, Ctx* ctx, c11_vector* jmps) {
  693. if(is_compare_expr(self->lhs)) {
  694. _emit_compare((BinaryExpr*)self->lhs, ctx, jmps);
  695. } else {
  696. vtemit_(self->lhs, ctx); // [a]
  697. }
  698. vtemit_(self->rhs, ctx); // [a, b]
  699. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line); // [a, b, b]
  700. Ctx__emit_(ctx, OP_ROT_THREE, BC_NOARG, self->line); // [b, a, b]
  701. Ctx__emit_(ctx, cmp_token2op(self->op), BC_NOARG, self->line);
  702. // [b, RES]
  703. int index = Ctx__emit_(ctx, OP_SHORTCUT_IF_FALSE_OR_POP, BC_NOARG, self->line);
  704. c11_vector__push(int, jmps, index);
  705. }
  706. static void BinaryExpr__emit_(Expr* self_, Ctx* ctx) {
  707. BinaryExpr* self = (BinaryExpr*)self_;
  708. c11_vector /*T=int*/ jmps;
  709. c11_vector__ctor(&jmps, sizeof(int));
  710. if(cmp_token2op(self->op) && is_compare_expr(self->lhs)) {
  711. // (a < b) < c
  712. BinaryExpr* e = (BinaryExpr*)self->lhs;
  713. _emit_compare(e, ctx, &jmps);
  714. // [b, RES]
  715. } else {
  716. // (1 + 2) < c
  717. if(self->inplace) {
  718. vtemit_inplace(self->lhs, ctx);
  719. } else {
  720. vtemit_(self->lhs, ctx);
  721. }
  722. }
  723. vtemit_(self->rhs, ctx);
  724. Opcode opcode;
  725. uint16_t arg = BC_NOARG;
  726. switch(self->op) {
  727. case TK_ADD: opcode = OP_BINARY_ADD; break;
  728. case TK_SUB: opcode = OP_BINARY_SUB; break;
  729. case TK_MUL: opcode = OP_BINARY_MUL; break;
  730. case TK_DIV: opcode = OP_BINARY_TRUEDIV; break;
  731. case TK_FLOORDIV: opcode = OP_BINARY_FLOORDIV; break;
  732. case TK_MOD: opcode = OP_BINARY_MOD; break;
  733. case TK_POW: opcode = OP_BINARY_POW; break;
  734. case TK_LT: opcode = OP_COMPARE_LT; break;
  735. case TK_LE: opcode = OP_COMPARE_LE; break;
  736. case TK_EQ: opcode = OP_COMPARE_EQ; break;
  737. case TK_NE: opcode = OP_COMPARE_NE; break;
  738. case TK_GT: opcode = OP_COMPARE_GT; break;
  739. case TK_GE: opcode = OP_COMPARE_GE; break;
  740. case TK_IN:
  741. opcode = OP_CONTAINS_OP;
  742. arg = 0;
  743. break;
  744. case TK_NOT_IN:
  745. opcode = OP_CONTAINS_OP;
  746. arg = 1;
  747. break;
  748. case TK_IS:
  749. opcode = OP_IS_OP;
  750. arg = 0;
  751. break;
  752. case TK_IS_NOT:
  753. opcode = OP_IS_OP;
  754. arg = 1;
  755. break;
  756. case TK_LSHIFT: opcode = OP_BINARY_LSHIFT; break;
  757. case TK_RSHIFT: opcode = OP_BINARY_RSHIFT; break;
  758. case TK_AND: opcode = OP_BINARY_AND; break;
  759. case TK_OR: opcode = OP_BINARY_OR; break;
  760. case TK_XOR: opcode = OP_BINARY_XOR; break;
  761. case TK_DECORATOR: opcode = OP_BINARY_MATMUL; break;
  762. default: c11__unreachable();
  763. }
  764. Ctx__emit_(ctx, opcode, arg, self->line);
  765. for(int i = 0; i < jmps.length; i++) {
  766. Ctx__patch_jump(ctx, c11__getitem(int, &jmps, i));
  767. }
  768. c11_vector__dtor(&jmps);
  769. }
  770. BinaryExpr* BinaryExpr__new(int line, TokenIndex op, bool inplace) {
  771. const static ExprVt Vt = {.emit_ = BinaryExpr__emit_,
  772. .dtor = BinaryExpr__dtor,
  773. .is_binary = true};
  774. BinaryExpr* self = PK_MALLOC(sizeof(BinaryExpr));
  775. self->vt = &Vt;
  776. self->line = line;
  777. self->lhs = NULL;
  778. self->rhs = NULL;
  779. self->op = op;
  780. self->inplace = inplace;
  781. return self;
  782. }
  783. typedef struct TernaryExpr {
  784. EXPR_COMMON_HEADER
  785. Expr* cond;
  786. Expr* true_expr;
  787. Expr* false_expr;
  788. } TernaryExpr;
  789. void TernaryExpr__dtor(Expr* self_) {
  790. TernaryExpr* self = (TernaryExpr*)self_;
  791. vtdelete(self->cond);
  792. vtdelete(self->true_expr);
  793. vtdelete(self->false_expr);
  794. }
  795. void TernaryExpr__emit_(Expr* self_, Ctx* ctx) {
  796. TernaryExpr* self = (TernaryExpr*)self_;
  797. vtemit_(self->cond, ctx);
  798. int patch = Ctx__emit_(ctx, OP_POP_JUMP_IF_FALSE, BC_NOARG, self->cond->line);
  799. vtemit_(self->true_expr, ctx);
  800. int patch_2 = Ctx__emit_(ctx, OP_JUMP_FORWARD, BC_NOARG, self->true_expr->line);
  801. Ctx__patch_jump(ctx, patch);
  802. vtemit_(self->false_expr, ctx);
  803. Ctx__patch_jump(ctx, patch_2);
  804. }
  805. TernaryExpr* TernaryExpr__new(int line) {
  806. const static ExprVt Vt = {
  807. .dtor = TernaryExpr__dtor,
  808. .emit_ = TernaryExpr__emit_,
  809. .is_ternary = true,
  810. };
  811. TernaryExpr* self = PK_MALLOC(sizeof(TernaryExpr));
  812. self->vt = &Vt;
  813. self->line = line;
  814. self->cond = NULL;
  815. self->true_expr = NULL;
  816. self->false_expr = NULL;
  817. return self;
  818. }
  819. typedef struct SubscrExpr {
  820. EXPR_COMMON_HEADER
  821. Expr* lhs;
  822. Expr* rhs;
  823. } SubscrExpr;
  824. void SubscrExpr__dtor(Expr* self_) {
  825. SubscrExpr* self = (SubscrExpr*)self_;
  826. vtdelete(self->lhs);
  827. vtdelete(self->rhs);
  828. }
  829. void SubscrExpr__emit_(Expr* self_, Ctx* ctx) {
  830. SubscrExpr* self = (SubscrExpr*)self_;
  831. vtemit_(self->lhs, ctx);
  832. vtemit_(self->rhs, ctx);
  833. Ctx__emit_(ctx, OP_LOAD_SUBSCR, BC_NOARG, self->line);
  834. }
  835. bool SubscrExpr__emit_store(Expr* self_, Ctx* ctx) {
  836. SubscrExpr* self = (SubscrExpr*)self_;
  837. vtemit_(self->lhs, ctx);
  838. vtemit_(self->rhs, ctx);
  839. Ctx__emit_(ctx, OP_STORE_SUBSCR, BC_NOARG, self->line);
  840. return true;
  841. }
  842. void SubscrExpr__emit_inplace(Expr* self_, Ctx* ctx) {
  843. SubscrExpr* self = (SubscrExpr*)self_;
  844. vtemit_(self->lhs, ctx);
  845. vtemit_(self->rhs, ctx);
  846. Ctx__emit_(ctx, OP_DUP_TOP_TWO, BC_NOARG, self->line);
  847. Ctx__emit_(ctx, OP_LOAD_SUBSCR, BC_NOARG, self->line);
  848. }
  849. bool SubscrExpr__emit_istore(Expr* self_, Ctx* ctx) {
  850. SubscrExpr* self = (SubscrExpr*)self_;
  851. // [a, b, val] -> [val, a, b]
  852. Ctx__emit_(ctx, OP_ROT_THREE, BC_NOARG, self->line);
  853. Ctx__emit_(ctx, OP_STORE_SUBSCR, BC_NOARG, self->line);
  854. return true;
  855. }
  856. bool SubscrExpr__emit_del(Expr* self_, Ctx* ctx) {
  857. SubscrExpr* self = (SubscrExpr*)self_;
  858. vtemit_(self->lhs, ctx);
  859. vtemit_(self->rhs, ctx);
  860. Ctx__emit_(ctx, OP_DELETE_SUBSCR, BC_NOARG, self->line);
  861. return true;
  862. }
  863. SubscrExpr* SubscrExpr__new(int line) {
  864. const static ExprVt Vt = {
  865. .dtor = SubscrExpr__dtor,
  866. .emit_ = SubscrExpr__emit_,
  867. .emit_store = SubscrExpr__emit_store,
  868. .emit_inplace = SubscrExpr__emit_inplace,
  869. .emit_istore = SubscrExpr__emit_istore,
  870. .emit_del = SubscrExpr__emit_del,
  871. .is_subscr = true,
  872. };
  873. SubscrExpr* self = PK_MALLOC(sizeof(SubscrExpr));
  874. self->vt = &Vt;
  875. self->line = line;
  876. self->lhs = NULL;
  877. self->rhs = NULL;
  878. return self;
  879. }
  880. typedef struct AttribExpr {
  881. EXPR_COMMON_HEADER
  882. Expr* child;
  883. py_Name name;
  884. } AttribExpr;
  885. void AttribExpr__dtor(Expr* self_) {
  886. AttribExpr* self = (AttribExpr*)self_;
  887. vtdelete(self->child);
  888. }
  889. static bool is_self_xxx(Expr* child, Ctx* ctx) {
  890. if(child->vt->is_name) {
  891. NameExpr* ne = (NameExpr*)child;
  892. if(ne->scope == NAME_LOCAL && ne->name == ctx->n_self) {
  893. int index = c11_smallmap_n2d__get(&ctx->co->varnames_inv, ne->name, -1);
  894. if(index == 0) return true;
  895. }
  896. }
  897. return false;
  898. }
  899. void AttribExpr__emit_(Expr* self_, Ctx* ctx) {
  900. AttribExpr* self = (AttribExpr*)self_;
  901. if(is_self_xxx(self->child, ctx)) {
  902. Ctx__emit_(ctx, OP_LOAD_SELF_ATTR, Ctx__add_name(ctx, self->name), self->line);
  903. return;
  904. }
  905. vtemit_(self->child, ctx);
  906. Ctx__emit_(ctx, OP_LOAD_ATTR, Ctx__add_name(ctx, self->name), self->line);
  907. }
  908. bool AttribExpr__emit_del(Expr* self_, Ctx* ctx) {
  909. AttribExpr* self = (AttribExpr*)self_;
  910. vtemit_(self->child, ctx);
  911. Ctx__emit_(ctx, OP_DELETE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  912. return true;
  913. }
  914. bool AttribExpr__emit_store(Expr* self_, Ctx* ctx) {
  915. AttribExpr* self = (AttribExpr*)self_;
  916. if(is_self_xxx(self->child, ctx)) {
  917. Ctx__emit_(ctx, OP_STORE_SELF_ATTR, Ctx__add_name(ctx, self->name), self->line);
  918. return true;
  919. }
  920. vtemit_(self->child, ctx);
  921. Ctx__emit_(ctx, OP_STORE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  922. return true;
  923. }
  924. void AttribExpr__emit_inplace(Expr* self_, Ctx* ctx) {
  925. AttribExpr* self = (AttribExpr*)self_;
  926. vtemit_(self->child, ctx);
  927. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line);
  928. Ctx__emit_(ctx, OP_LOAD_ATTR, Ctx__add_name(ctx, self->name), self->line);
  929. }
  930. bool AttribExpr__emit_istore(Expr* self_, Ctx* ctx) {
  931. // [a, val] -> [val, a]
  932. AttribExpr* self = (AttribExpr*)self_;
  933. Ctx__emit_(ctx, OP_ROT_TWO, BC_NOARG, self->line);
  934. Ctx__emit_(ctx, OP_STORE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  935. return true;
  936. }
  937. AttribExpr* AttribExpr__new(int line, Expr* child, py_Name name) {
  938. const static ExprVt Vt = {.emit_ = AttribExpr__emit_,
  939. .emit_del = AttribExpr__emit_del,
  940. .emit_store = AttribExpr__emit_store,
  941. .emit_inplace = AttribExpr__emit_inplace,
  942. .emit_istore = AttribExpr__emit_istore,
  943. .dtor = AttribExpr__dtor,
  944. .is_attrib = true};
  945. AttribExpr* self = PK_MALLOC(sizeof(AttribExpr));
  946. self->vt = &Vt;
  947. self->line = line;
  948. self->child = child;
  949. self->name = name;
  950. return self;
  951. }
  952. typedef struct CallExprKwArg {
  953. py_Name key;
  954. Expr* val;
  955. } CallExprKwArg;
  956. typedef struct CallExpr {
  957. EXPR_COMMON_HEADER
  958. Expr* callable;
  959. c11_vector /*T=Expr* */ args;
  960. // **a will be interpreted as a special keyword argument: {{0}: a}
  961. c11_vector /*T=CallExprKwArg */ kwargs;
  962. } CallExpr;
  963. void CallExpr__dtor(Expr* self_) {
  964. CallExpr* self = (CallExpr*)self_;
  965. vtdelete(self->callable);
  966. c11__foreach(Expr*, &self->args, e) vtdelete(*e);
  967. c11__foreach(CallExprKwArg, &self->kwargs, e) vtdelete(e->val);
  968. c11_vector__dtor(&self->args);
  969. c11_vector__dtor(&self->kwargs);
  970. }
  971. void CallExpr__emit_(Expr* self_, Ctx* ctx) {
  972. CallExpr* self = (CallExpr*)self_;
  973. bool vargs = false; // whether there is *args as input
  974. bool vkwargs = false; // whether there is **kwargs as input
  975. c11__foreach(Expr*, &self->args, e) {
  976. if((*e)->vt->is_starred) vargs = true;
  977. }
  978. c11__foreach(CallExprKwArg, &self->kwargs, e) {
  979. if(e->val->vt->is_starred) vkwargs = true;
  980. }
  981. // if callable is a AttrExpr, we should try to use `fast_call` instead of use `boundmethod`
  982. if(self->callable->vt->is_attrib) {
  983. AttribExpr* p = (AttribExpr*)self->callable;
  984. vtemit_(p->child, ctx);
  985. Ctx__emit_(ctx, OP_LOAD_METHOD, Ctx__add_name(ctx, p->name), p->line);
  986. } else {
  987. vtemit_(self->callable, ctx);
  988. Ctx__emit_(ctx, OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  989. }
  990. Opcode opcode = OP_CALL;
  991. if(vargs || vkwargs) {
  992. // in this case, there is at least one *args or **kwargs as StarredExpr
  993. // OP_CALL_VARGS needs to unpack them via vectorcall_buffer
  994. opcode = OP_CALL_VARGS;
  995. }
  996. c11__foreach(Expr*, &self->args, e) { vtemit_(*e, ctx); }
  997. c11__foreach(CallExprKwArg, &self->kwargs, e) {
  998. if(e->key == 0) {
  999. // special key for **kwargs
  1000. Ctx__emit_int(ctx, 0, self->line);
  1001. } else {
  1002. Ctx__emit_name(ctx, e->key, self->line);
  1003. }
  1004. vtemit_(e->val, ctx);
  1005. }
  1006. int KWARGC = self->kwargs.length;
  1007. int ARGC = self->args.length;
  1008. assert(KWARGC < 256 && ARGC < 256);
  1009. Ctx__emit_(ctx, opcode, (KWARGC << 8) | ARGC, self->line);
  1010. }
  1011. CallExpr* CallExpr__new(int line, Expr* callable) {
  1012. const static ExprVt Vt = {.dtor = CallExpr__dtor, .emit_ = CallExpr__emit_};
  1013. CallExpr* self = PK_MALLOC(sizeof(CallExpr));
  1014. self->vt = &Vt;
  1015. self->line = line;
  1016. self->callable = callable;
  1017. c11_vector__ctor(&self->args, sizeof(Expr*));
  1018. c11_vector__ctor(&self->kwargs, sizeof(CallExprKwArg));
  1019. return self;
  1020. }
  1021. /* context.c */
  1022. static void Ctx__ctor(Ctx* self, CodeObject* co, FuncDecl* func, int level, py_Name n_self) {
  1023. self->co = co;
  1024. self->func = func;
  1025. self->n_self = n_self;
  1026. self->level = level;
  1027. self->curr_iblock = 0;
  1028. self->is_compiling_class = false;
  1029. c11_vector__ctor(&self->s_expr, sizeof(Expr*));
  1030. c11_smallmap_n2d__ctor(&self->global_names);
  1031. c11_smallmap_v2d__ctor(&self->co_consts_string_dedup_map);
  1032. }
  1033. static void Ctx__dtor(Ctx* self) {
  1034. // clean the expr stack
  1035. for(int i = 0; i < self->s_expr.length; i++) {
  1036. vtdelete(c11__getitem(Expr*, &self->s_expr, i));
  1037. }
  1038. c11_vector__dtor(&self->s_expr);
  1039. c11_smallmap_n2d__dtor(&self->global_names);
  1040. // free the dedup map
  1041. c11__foreach(c11_smallmap_v2d_KV, &self->co_consts_string_dedup_map, p_kv) {
  1042. const char* p = p_kv->key.data;
  1043. PK_FREE((void*)p);
  1044. }
  1045. c11_smallmap_v2d__dtor(&self->co_consts_string_dedup_map);
  1046. }
  1047. static int Ctx__prepare_loop_divert(Ctx* self, int line, bool is_break) {
  1048. int index = self->curr_iblock;
  1049. while(index >= 0) {
  1050. CodeBlock* block = c11__at(CodeBlock, &self->co->blocks, index);
  1051. switch(block->type) {
  1052. case CodeBlockType_WHILE_LOOP: return index;
  1053. case CodeBlockType_FOR_LOOP: {
  1054. if(is_break) Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  1055. return index;
  1056. }
  1057. case CodeBlockType_WITH: {
  1058. Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  1059. break;
  1060. }
  1061. case CodeBlockType_TRY: {
  1062. Ctx__emit_(self, OP_END_TRY, BC_NOARG, line);
  1063. break;
  1064. }
  1065. case CodeBlockType_EXCEPT: {
  1066. Ctx__emit_(self, OP_END_TRY, BC_NOARG, line);
  1067. break;
  1068. }
  1069. default: break;
  1070. }
  1071. index = block->parent;
  1072. }
  1073. return index;
  1074. }
  1075. static int Ctx__enter_block(Ctx* self, CodeBlockType type) {
  1076. CodeBlock block = {type, self->curr_iblock, self->co->codes.length, -1, -1};
  1077. c11_vector__push(CodeBlock, &self->co->blocks, block);
  1078. self->curr_iblock = self->co->blocks.length - 1;
  1079. return self->curr_iblock;
  1080. }
  1081. static void Ctx__exit_block(Ctx* self) {
  1082. CodeBlock* block = c11__at(CodeBlock, &self->co->blocks, self->curr_iblock);
  1083. block->end = self->co->codes.length;
  1084. self->curr_iblock = block->parent;
  1085. assert(self->curr_iblock >= 0);
  1086. }
  1087. static void Ctx__s_emit_decorators(Ctx* self, int count) {
  1088. if(count == 0) return;
  1089. assert(Ctx__s_size(self) >= count);
  1090. // [obj]
  1091. for(int i = 0; i < count; i++) {
  1092. Expr* deco = Ctx__s_popx(self);
  1093. vtemit_(deco, self); // [obj, f]
  1094. Ctx__emit_(self, OP_ROT_TWO, BC_NOARG, deco->line); // [f, obj]
  1095. Ctx__emit_(self, OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE); // [f, obj, NULL]
  1096. Ctx__emit_(self, OP_ROT_TWO, BC_NOARG, BC_KEEPLINE); // [obj, NULL, f]
  1097. Ctx__emit_(self, OP_CALL, 1, deco->line); // [obj]
  1098. vtdelete(deco);
  1099. }
  1100. }
  1101. static int Ctx__emit_(Ctx* self, Opcode opcode, uint16_t arg, int line) {
  1102. Bytecode bc = {(uint16_t)opcode, arg};
  1103. BytecodeEx bcx = {line, self->curr_iblock};
  1104. c11_vector__push(Bytecode, &self->co->codes, bc);
  1105. c11_vector__push(BytecodeEx, &self->co->codes_ex, bcx);
  1106. int i = self->co->codes.length - 1;
  1107. BytecodeEx* codes_ex = (BytecodeEx*)self->co->codes_ex.data;
  1108. if(line == BC_KEEPLINE) { codes_ex[i].lineno = i >= 1 ? codes_ex[i - 1].lineno : 1; }
  1109. return i;
  1110. }
  1111. static int Ctx__emit_int(Ctx* self, int64_t value, int line) {
  1112. if(INT16_MIN <= value && value <= INT16_MAX) {
  1113. return Ctx__emit_(self, OP_LOAD_SMALL_INT, (uint16_t)value, line);
  1114. } else {
  1115. py_TValue tmp;
  1116. py_newint(&tmp, value);
  1117. return Ctx__emit_(self, OP_LOAD_CONST, Ctx__add_const(self, &tmp), line);
  1118. }
  1119. }
  1120. static int Ctx__emit_name(Ctx* self, py_Name name, int line) {
  1121. int index = Ctx__add_name(self, name);
  1122. assert(index <= UINT16_MAX);
  1123. return Ctx__emit_(self, OP_LOAD_NAME_AS_INT, (uint16_t)index, line);
  1124. }
  1125. static void Ctx__patch_jump(Ctx* self, int index) {
  1126. Bytecode* co_codes = (Bytecode*)self->co->codes.data;
  1127. int target = self->co->codes.length;
  1128. Bytecode__set_signed_arg(&co_codes[index], target - index);
  1129. }
  1130. static void Ctx__emit_jump(Ctx* self, int target, int line) {
  1131. int index = Ctx__emit_(self, OP_JUMP_FORWARD, BC_NOARG, line);
  1132. // should place after Ctx__emit_ because of realloc
  1133. Bytecode* co_codes = (Bytecode*)self->co->codes.data;
  1134. Bytecode__set_signed_arg(&co_codes[index], target - index);
  1135. }
  1136. static int Ctx__add_varname(Ctx* self, py_Name name) {
  1137. // PK_MAX_CO_VARNAMES will be checked when pop_context(), not here
  1138. return CodeObject__add_varname(self->co, name);
  1139. }
  1140. static int Ctx__add_name(Ctx* self, py_Name name) {
  1141. assert(name != 0);
  1142. return CodeObject__add_name(self->co, name);
  1143. }
  1144. static int Ctx__add_const_string(Ctx* self, c11_sv key) {
  1145. if(key.size > 100) {
  1146. py_Ref tmp = c11_vector__emplace(&self->co->consts);
  1147. py_newstrv(tmp, key);
  1148. int index = self->co->consts.length - 1;
  1149. return index;
  1150. }
  1151. int* val = c11_smallmap_v2d__try_get(&self->co_consts_string_dedup_map, key);
  1152. if(val) {
  1153. return *val;
  1154. } else {
  1155. py_Ref tmp = c11_vector__emplace(&self->co->consts);
  1156. py_newstrv(tmp, key);
  1157. int index = self->co->consts.length - 1;
  1158. // dedup
  1159. char* new_buf = PK_MALLOC(key.size + 1);
  1160. memcpy(new_buf, key.data, key.size);
  1161. new_buf[key.size] = 0;
  1162. c11_smallmap_v2d__set(&self->co_consts_string_dedup_map,
  1163. (c11_sv){new_buf, key.size},
  1164. index);
  1165. return index;
  1166. }
  1167. }
  1168. static int Ctx__add_const(Ctx* self, py_Ref v) {
  1169. assert(v->type != tp_str);
  1170. c11_vector__push(py_TValue, &self->co->consts, *v);
  1171. return self->co->consts.length - 1;
  1172. }
  1173. static void Ctx__emit_store_name(Ctx* self, NameScope scope, py_Name name, int line) {
  1174. if(name == py_name("_")) {
  1175. Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  1176. return;
  1177. }
  1178. switch(scope) {
  1179. case NAME_LOCAL: Ctx__emit_(self, OP_STORE_FAST, Ctx__add_varname(self, name), line); break;
  1180. case NAME_GLOBAL: {
  1181. Opcode op = self->co->src->is_dynamic ? OP_STORE_NAME : OP_STORE_GLOBAL;
  1182. Ctx__emit_(self, op, Ctx__add_name(self, name), line);
  1183. } break;
  1184. default: c11__unreachable();
  1185. }
  1186. }
  1187. // emit top -> pop -> delete
  1188. static void Ctx__s_emit_top(Ctx* self) {
  1189. assert(self->s_expr.length);
  1190. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  1191. vtemit_(top, self);
  1192. vtdelete(top);
  1193. c11_vector__pop(&self->s_expr);
  1194. }
  1195. // push
  1196. static void Ctx__s_push(Ctx* self, Expr* expr) { c11_vector__push(Expr*, &self->s_expr, expr); }
  1197. // top
  1198. static Expr* Ctx__s_top(Ctx* self) {
  1199. assert(self->s_expr.length);
  1200. return c11_vector__back(Expr*, &self->s_expr);
  1201. }
  1202. // size
  1203. static int Ctx__s_size(Ctx* self) { return self->s_expr.length; }
  1204. // pop -> delete
  1205. static void Ctx__s_pop(Ctx* self) {
  1206. assert(self->s_expr.length);
  1207. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  1208. vtdelete(top);
  1209. c11_vector__pop(&self->s_expr);
  1210. }
  1211. // pop move
  1212. static Expr* Ctx__s_popx(Ctx* self) {
  1213. assert(self->s_expr.length);
  1214. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  1215. c11_vector__pop(&self->s_expr);
  1216. return top;
  1217. }
  1218. /* compiler.c */
  1219. typedef struct Compiler Compiler;
  1220. typedef Error* (*PrattCallback)(Compiler* self);
  1221. typedef struct PrattRule {
  1222. PrattCallback prefix;
  1223. PrattCallback infix;
  1224. enum Precedence precedence;
  1225. } PrattRule;
  1226. const static PrattRule rules[TK__COUNT__];
  1227. typedef struct Compiler {
  1228. SourceData_ src; // weakref
  1229. Token* tokens;
  1230. int tokens_length;
  1231. py_Name n_self;
  1232. int i; // current token index
  1233. c11_vector /*T=CodeEmitContext*/ contexts;
  1234. } Compiler;
  1235. static void Compiler__ctor(Compiler* self, SourceData_ src, Token* tokens, int tokens_length) {
  1236. self->src = src;
  1237. self->tokens = tokens;
  1238. self->tokens_length = tokens_length;
  1239. self->n_self = py_name("self");
  1240. self->i = 0;
  1241. c11_vector__ctor(&self->contexts, sizeof(Ctx));
  1242. }
  1243. static void Compiler__dtor(Compiler* self) {
  1244. // free tokens
  1245. for(int i = 0; i < self->tokens_length; i++) {
  1246. if(self->tokens[i].value.index == TokenValue_STR) {
  1247. // PK_FREE internal string
  1248. c11_string__delete(self->tokens[i].value._str);
  1249. }
  1250. }
  1251. PK_FREE(self->tokens);
  1252. // free contexts
  1253. c11__foreach(Ctx, &self->contexts, ctx) Ctx__dtor(ctx);
  1254. c11_vector__dtor(&self->contexts);
  1255. }
  1256. /**************************************/
  1257. #define tk(i) (&self->tokens[i])
  1258. #define prev() (&self->tokens[self->i - 1])
  1259. #define curr() (&self->tokens[self->i])
  1260. #define next() (&self->tokens[self->i + 1])
  1261. #define advance() self->i++
  1262. #define mode() self->src->mode
  1263. #define ctx() (&c11_vector__back(Ctx, &self->contexts))
  1264. #define match_newlines() match_newlines_impl(self)
  1265. #define consume(expected) \
  1266. if(!match(expected)) \
  1267. return SyntaxError(self, \
  1268. "expected '%s', got '%s'", \
  1269. TokenSymbols[expected], \
  1270. TokenSymbols[curr()->type]);
  1271. #define consume_end_stmt() \
  1272. if(!match_end_stmt(self)) return SyntaxError(self, "expected statement end")
  1273. #define check(B) \
  1274. if((err = B)) return err
  1275. static NameScope name_scope(Compiler* self) {
  1276. return self->contexts.length > 1 ? NAME_LOCAL : NAME_GLOBAL;
  1277. }
  1278. Error* SyntaxError(Compiler* self, const char* fmt, ...) {
  1279. Error* err = PK_MALLOC(sizeof(Error));
  1280. err->src = self->src;
  1281. PK_INCREF(self->src);
  1282. Token* t = self->i == self->tokens_length ? prev() : curr();
  1283. err->lineno = t->line;
  1284. va_list args;
  1285. va_start(args, fmt);
  1286. vsnprintf(err->msg, sizeof(err->msg), fmt, args);
  1287. va_end(args);
  1288. return err;
  1289. }
  1290. /* Matchers */
  1291. static bool is_expression(Compiler* self, bool allow_slice) {
  1292. PrattCallback prefix = rules[curr()->type].prefix;
  1293. return prefix && (allow_slice || curr()->type != TK_COLON);
  1294. }
  1295. #define match(expected) (curr()->type == expected ? (++self->i) : 0)
  1296. static bool match_id_by_str(Compiler* self, const char* name) {
  1297. if(curr()->type == TK_ID) {
  1298. bool ok = c11__sveq2(Token__sv(curr()), name);
  1299. if(ok) advance();
  1300. return ok;
  1301. }
  1302. return false;
  1303. }
  1304. static bool match_newlines_impl(Compiler* self) {
  1305. bool consumed = false;
  1306. if(curr()->type == TK_EOL) {
  1307. while(curr()->type == TK_EOL)
  1308. advance();
  1309. consumed = true;
  1310. }
  1311. return consumed;
  1312. }
  1313. static bool match_end_stmt(Compiler* self) {
  1314. if(match(TK_SEMICOLON)) {
  1315. match_newlines();
  1316. return true;
  1317. }
  1318. if(match_newlines() || curr()->type == TK_EOF) return true;
  1319. if(curr()->type == TK_DEDENT) return true;
  1320. return false;
  1321. }
  1322. /* Expression */
  1323. /// Parse an expression and push it onto the stack.
  1324. static Error* parse_expression(Compiler* self, int precedence, bool allow_slice) {
  1325. PrattCallback prefix = rules[curr()->type].prefix;
  1326. if(!prefix || (curr()->type == TK_COLON && !allow_slice)) {
  1327. return SyntaxError(self, "expected an expression, got %s", TokenSymbols[curr()->type]);
  1328. }
  1329. advance();
  1330. Error* err;
  1331. check(prefix(self));
  1332. while(rules[curr()->type].precedence >= precedence &&
  1333. (allow_slice || curr()->type != TK_COLON)) {
  1334. TokenIndex op = curr()->type;
  1335. advance();
  1336. PrattCallback infix = rules[op].infix;
  1337. if(infix == NULL) {
  1338. return SyntaxError(self, "expected an infix operator, got %s", TokenSymbols[op]);
  1339. }
  1340. check(infix(self));
  1341. }
  1342. return NULL;
  1343. }
  1344. static Error* EXPR_TUPLE_ALLOW_SLICE(Compiler* self, bool allow_slice) {
  1345. Error* err;
  1346. check(parse_expression(self, PREC_LOWEST + 1, allow_slice));
  1347. if(!match(TK_COMMA)) return NULL;
  1348. // tuple expression // (a, )
  1349. int count = 1;
  1350. do {
  1351. if(!is_expression(self, allow_slice)) break;
  1352. check(parse_expression(self, PREC_LOWEST + 1, allow_slice));
  1353. count += 1;
  1354. } while(match(TK_COMMA));
  1355. // pop `count` expressions from the stack and merge them into a TupleExpr
  1356. SequenceExpr* e = TupleExpr__new(prev()->line, count);
  1357. for(int i = count - 1; i >= 0; i--) {
  1358. e->items[i] = Ctx__s_popx(ctx());
  1359. }
  1360. Ctx__s_push(ctx(), (Expr*)e);
  1361. return NULL;
  1362. }
  1363. /// Parse a simple expression.
  1364. static Error* EXPR(Compiler* self) { return parse_expression(self, PREC_LOWEST + 1, false); }
  1365. /// Parse a simple expression or a tuple of expressions.
  1366. static Error* EXPR_TUPLE(Compiler* self) { return EXPR_TUPLE_ALLOW_SLICE(self, false); }
  1367. // special case for `for loop` and `comp`
  1368. static Error* EXPR_VARS(Compiler* self) {
  1369. int count = 0;
  1370. do {
  1371. consume(TK_ID);
  1372. py_Name name = py_namev(Token__sv(prev()));
  1373. NameExpr* e = NameExpr__new(prev()->line, name, name_scope(self));
  1374. Ctx__s_push(ctx(), (Expr*)e);
  1375. count += 1;
  1376. } while(match(TK_COMMA));
  1377. if(count > 1) {
  1378. SequenceExpr* e = TupleExpr__new(prev()->line, count);
  1379. for(int i = count - 1; i >= 0; i--) {
  1380. e->items[i] = Ctx__s_popx(ctx());
  1381. }
  1382. Ctx__s_push(ctx(), (Expr*)e);
  1383. }
  1384. return NULL;
  1385. }
  1386. /* Misc */
  1387. static void push_global_context(Compiler* self, CodeObject* co) {
  1388. co->start_line = self->i == 0 ? 1 : prev()->line;
  1389. Ctx* ctx = c11_vector__emplace(&self->contexts);
  1390. Ctx__ctor(ctx, co, NULL, self->contexts.length, self->n_self);
  1391. }
  1392. static Error* pop_context(Compiler* self) {
  1393. // add a `return None` in the end as a guard
  1394. // previously, we only do this if the last opcode is not a return
  1395. // however, this is buggy...since there may be a jump to the end (out of bound) even if the last
  1396. // opcode is a return
  1397. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_RETURN_VIRTUAL, BC_KEEPLINE);
  1398. CodeObject* co = ctx()->co;
  1399. // find the last valid token
  1400. int j = self->i - 1;
  1401. while(tk(j)->type == TK_EOL || tk(j)->type == TK_DEDENT || tk(j)->type == TK_EOF)
  1402. j--;
  1403. co->end_line = tk(j)->line;
  1404. // some check here
  1405. c11_vector* codes = &co->codes;
  1406. if(co->nlocals > PK_MAX_CO_VARNAMES) {
  1407. return SyntaxError(self, "maximum number of local variables exceeded");
  1408. }
  1409. if(co->consts.length > 65530) {
  1410. return SyntaxError(self, "maximum number of constants exceeded");
  1411. }
  1412. // pre-compute block.end or block.end2
  1413. for(int i = 0; i < codes->length; i++) {
  1414. Bytecode* bc = c11__at(Bytecode, codes, i);
  1415. if(bc->op == OP_LOOP_CONTINUE) {
  1416. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  1417. Bytecode__set_signed_arg(bc, block->start - i);
  1418. } else if(bc->op == OP_LOOP_BREAK) {
  1419. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  1420. Bytecode__set_signed_arg(bc, (block->end2 != -1 ? block->end2 : block->end) - i);
  1421. } else if(bc->op == OP_FOR_ITER || bc->op == OP_FOR_ITER_YIELD_VALUE) {
  1422. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  1423. Bytecode__set_signed_arg(bc, block->end - i);
  1424. }
  1425. }
  1426. // pre-compute func->is_simple
  1427. FuncDecl* func = ctx()->func;
  1428. if(func) {
  1429. // check generator
  1430. Bytecode* codes = func->code.codes.data;
  1431. int codes_length = func->code.codes.length;
  1432. for(int i = 0; i < codes_length; i++) {
  1433. if(codes[i].op == OP_YIELD_VALUE || codes[i].op == OP_FOR_ITER_YIELD_VALUE) {
  1434. func->type = FuncType_GENERATOR;
  1435. break;
  1436. }
  1437. }
  1438. if(func->type == FuncType_UNSET) {
  1439. bool is_simple = true;
  1440. if(func->kwargs.length > 0) is_simple = false;
  1441. if(func->starred_arg >= 0) is_simple = false;
  1442. if(func->starred_kwarg >= 0) is_simple = false;
  1443. if(is_simple) {
  1444. func->type = FuncType_SIMPLE;
  1445. } else {
  1446. func->type = FuncType_NORMAL;
  1447. }
  1448. }
  1449. assert(func->type != FuncType_UNSET);
  1450. }
  1451. Ctx__dtor(ctx());
  1452. c11_vector__pop(&self->contexts);
  1453. return NULL;
  1454. }
  1455. /* Expression Callbacks */
  1456. static Error* exprLiteral(Compiler* self) {
  1457. LiteralExpr* e = LiteralExpr__new(prev()->line, &prev()->value);
  1458. Ctx__s_push(ctx(), (Expr*)e);
  1459. return NULL;
  1460. }
  1461. static Error* exprBytes(Compiler* self) {
  1462. c11_sv sv = c11_string__sv(prev()->value._str);
  1463. Ctx__s_push(ctx(), (Expr*)RawStringExpr__new(prev()->line, sv, OP_BUILD_BYTES));
  1464. return NULL;
  1465. }
  1466. static Error* exprFString(Compiler* self) {
  1467. // @fstr-begin, [@fstr-cpnt | <expr>]*, @fstr-end
  1468. int count = 0;
  1469. int line = prev()->line;
  1470. while(true) {
  1471. if(match(TK_FSTR_END)) {
  1472. SequenceExpr* e = FStringExpr__new(line, count);
  1473. for(int i = count - 1; i >= 0; i--) {
  1474. e->items[i] = Ctx__s_popx(ctx());
  1475. }
  1476. Ctx__s_push(ctx(), (Expr*)e);
  1477. return NULL;
  1478. } else if(match(TK_FSTR_CPNT)) {
  1479. // OP_LOAD_CONST
  1480. LiteralExpr* e = LiteralExpr__new(prev()->line, &prev()->value);
  1481. Ctx__s_push(ctx(), (Expr*)e);
  1482. count++;
  1483. } else {
  1484. // {a!r:.2f}
  1485. Error* err = EXPR(self);
  1486. if(err) return err;
  1487. count++;
  1488. if(match(TK_FSTR_SPEC)) {
  1489. c11_sv spec = Token__sv(prev());
  1490. // ':.2f}' -> ':.2f'
  1491. spec.size--;
  1492. Expr* child = Ctx__s_popx(ctx());
  1493. FStringSpecExpr* e = FStringSpecExpr__new(prev()->line, child, spec);
  1494. Ctx__s_push(ctx(), (Expr*)e);
  1495. }
  1496. }
  1497. }
  1498. }
  1499. static Error* exprImag(Compiler* self) {
  1500. Ctx__s_push(ctx(), (Expr*)ImagExpr__new(prev()->line, prev()->value._f64));
  1501. return NULL;
  1502. }
  1503. static FuncDecl_ push_f_context(Compiler* self, c11_sv name, int* out_index);
  1504. static Error* _compile_f_args(Compiler* self, FuncDecl* decl, bool is_lambda);
  1505. static Error* exprLambda(Compiler* self) {
  1506. Error* err;
  1507. int line = prev()->line;
  1508. int decl_index;
  1509. FuncDecl_ decl = push_f_context(self, (c11_sv){"<lambda>", 8}, &decl_index);
  1510. if(!match(TK_COLON)) {
  1511. check(_compile_f_args(self, decl, true));
  1512. consume(TK_COLON);
  1513. }
  1514. // https://github.com/pocketpy/pocketpy/issues/37
  1515. check(parse_expression(self, PREC_LAMBDA + 1, false));
  1516. Ctx__s_emit_top(ctx());
  1517. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1518. check(pop_context(self));
  1519. LambdaExpr* e = LambdaExpr__new(line, decl_index);
  1520. Ctx__s_push(ctx(), (Expr*)e);
  1521. return NULL;
  1522. }
  1523. static Error* exprOr(Compiler* self) {
  1524. Error* err;
  1525. int line = prev()->line;
  1526. check(parse_expression(self, PREC_LOGICAL_OR + 1, false));
  1527. LogicBinaryExpr* e = LogicBinaryExpr__new(line, OP_JUMP_IF_TRUE_OR_POP);
  1528. e->rhs = Ctx__s_popx(ctx());
  1529. e->lhs = Ctx__s_popx(ctx());
  1530. Ctx__s_push(ctx(), (Expr*)e);
  1531. return NULL;
  1532. }
  1533. static Error* exprAnd(Compiler* self) {
  1534. Error* err;
  1535. int line = prev()->line;
  1536. check(parse_expression(self, PREC_LOGICAL_AND + 1, false));
  1537. LogicBinaryExpr* e = LogicBinaryExpr__new(line, OP_JUMP_IF_FALSE_OR_POP);
  1538. e->rhs = Ctx__s_popx(ctx());
  1539. e->lhs = Ctx__s_popx(ctx());
  1540. Ctx__s_push(ctx(), (Expr*)e);
  1541. return NULL;
  1542. }
  1543. static Error* exprWalrus(Compiler* self) {
  1544. Error* err;
  1545. int line = prev()->line;
  1546. // LHS is on the stack; verify it's a simple name
  1547. Expr* lhs = Ctx__s_top(ctx());
  1548. if(!lhs->vt->is_name) { return SyntaxError(self, "':=' target must be a simple name"); }
  1549. check(parse_expression(self, PREC_NAMED_EXPR + 1, false));
  1550. Expr* rhs = Ctx__s_popx(ctx());
  1551. NameExpr* name = (NameExpr*)Ctx__s_popx(ctx());
  1552. NamedExpr* e = NamedExpr__new(line, name, rhs);
  1553. Ctx__s_push(ctx(), (Expr*)e);
  1554. return NULL;
  1555. }
  1556. static Error* exprTernary(Compiler* self) {
  1557. // [true_expr]
  1558. Error* err;
  1559. int line = prev()->line;
  1560. check(parse_expression(self, PREC_TERNARY + 1, false)); // [true_expr, cond]
  1561. consume(TK_ELSE);
  1562. check(parse_expression(self, PREC_TERNARY + 1, false)); // [true_expr, cond, false_expr]
  1563. TernaryExpr* e = TernaryExpr__new(line);
  1564. e->false_expr = Ctx__s_popx(ctx());
  1565. e->cond = Ctx__s_popx(ctx());
  1566. e->true_expr = Ctx__s_popx(ctx());
  1567. Ctx__s_push(ctx(), (Expr*)e);
  1568. if(e->cond->vt->is_ternary || e->false_expr->vt->is_ternary || e->true_expr->vt->is_ternary) {
  1569. return SyntaxError(self, "nested ternary expressions without `()` are ambiguous");
  1570. }
  1571. return NULL;
  1572. }
  1573. static Error* exprBinaryOp(Compiler* self) {
  1574. Error* err;
  1575. int line = prev()->line;
  1576. TokenIndex op = prev()->type;
  1577. int precedence = rules[op].precedence;
  1578. if(op != TK_POW) {
  1579. // if not right associative, increase precedence
  1580. precedence += 1;
  1581. }
  1582. check(parse_expression(self, precedence, false));
  1583. BinaryExpr* e = BinaryExpr__new(line, op, false);
  1584. if(op == TK_IN || op == TK_NOT_IN) {
  1585. e->lhs = Ctx__s_popx(ctx());
  1586. e->rhs = Ctx__s_popx(ctx());
  1587. } else {
  1588. e->rhs = Ctx__s_popx(ctx());
  1589. e->lhs = Ctx__s_popx(ctx());
  1590. }
  1591. Ctx__s_push(ctx(), (Expr*)e);
  1592. return NULL;
  1593. }
  1594. static Error* exprNot(Compiler* self) {
  1595. Error* err;
  1596. int line = prev()->line;
  1597. check(parse_expression(self, PREC_LOGICAL_NOT + 1, false));
  1598. UnaryExpr* e = UnaryExpr__new(line, Ctx__s_popx(ctx()), OP_UNARY_NOT);
  1599. Ctx__s_push(ctx(), (Expr*)e);
  1600. return NULL;
  1601. }
  1602. static Error* exprUnaryOp(Compiler* self) {
  1603. Error* err;
  1604. int line = prev()->line;
  1605. TokenIndex op = prev()->type;
  1606. check(parse_expression(self, PREC_UNARY + 1, false));
  1607. Expr* e = Ctx__s_popx(ctx());
  1608. switch(op) {
  1609. case TK_SUB: {
  1610. // constant fold
  1611. if(e->vt->is_literal) {
  1612. LiteralExpr* le = (LiteralExpr*)e;
  1613. if(le->value->index == TokenValue_I64 || le->value->index == TokenValue_F64) {
  1614. le->negated = true;
  1615. }
  1616. Ctx__s_push(ctx(), e);
  1617. } else {
  1618. Ctx__s_push(ctx(), (Expr*)UnaryExpr__new(line, e, OP_UNARY_NEGATIVE));
  1619. }
  1620. break;
  1621. }
  1622. case TK_INVERT: Ctx__s_push(ctx(), (Expr*)UnaryExpr__new(line, e, OP_UNARY_INVERT)); break;
  1623. case TK_MUL: Ctx__s_push(ctx(), (Expr*)StarredExpr__new(line, e, 1)); break;
  1624. case TK_POW: Ctx__s_push(ctx(), (Expr*)StarredExpr__new(line, e, 2)); break;
  1625. default: assert(false);
  1626. }
  1627. return NULL;
  1628. }
  1629. static Error* exprGroup(Compiler* self) {
  1630. Error* err;
  1631. int line = prev()->line;
  1632. if(match(TK_RPAREN)) {
  1633. // empty tuple
  1634. Ctx__s_push(ctx(), (Expr*)TupleExpr__new(line, 0));
  1635. return NULL;
  1636. }
  1637. check(EXPR_TUPLE(self)); // () is just for change precedence
  1638. consume(TK_RPAREN);
  1639. if(Ctx__s_top(ctx())->vt->is_tuple) return NULL;
  1640. GroupedExpr* g = GroupedExpr__new(line, Ctx__s_popx(ctx()));
  1641. Ctx__s_push(ctx(), (Expr*)g);
  1642. return NULL;
  1643. }
  1644. static Error* exprName(Compiler* self) {
  1645. py_Name name = py_namev(Token__sv(prev()));
  1646. NameScope scope = name_scope(self);
  1647. // promote this name to global scope if needed
  1648. if(c11_smallmap_n2d__contains(&ctx()->global_names, name)) {
  1649. if(self->src->is_dynamic) return SyntaxError(self, "cannot use global keyword here");
  1650. scope = NAME_GLOBAL;
  1651. }
  1652. NameExpr* e = NameExpr__new(prev()->line, name, scope);
  1653. Ctx__s_push(ctx(), (Expr*)e);
  1654. return NULL;
  1655. }
  1656. static Error* exprAttrib(Compiler* self) {
  1657. consume(TK_ID);
  1658. py_Name name = py_namev(Token__sv(prev()));
  1659. AttribExpr* e = AttribExpr__new(prev()->line, Ctx__s_popx(ctx()), name);
  1660. Ctx__s_push(ctx(), (Expr*)e);
  1661. return NULL;
  1662. }
  1663. static Error* exprLiteral0(Compiler* self) {
  1664. Literal0Expr* e = Literal0Expr__new(prev()->line, prev()->type);
  1665. Ctx__s_push(ctx(), (Expr*)e);
  1666. return NULL;
  1667. }
  1668. static Error* consume_comp(Compiler* self, Opcode op0, Opcode op1) {
  1669. // [expr]
  1670. Error* err;
  1671. int line = prev()->line;
  1672. bool has_cond = false;
  1673. check(EXPR_VARS(self)); // [expr, vars]
  1674. consume(TK_IN);
  1675. check(parse_expression(self, PREC_TERNARY + 1, false)); // [expr, vars, iter]
  1676. if(match(TK_IF)) {
  1677. check(parse_expression(self, PREC_TERNARY + 1, false)); // [expr, vars, iter, cond]
  1678. has_cond = true;
  1679. }
  1680. CompExpr* ce = CompExpr__new(line, op0, op1);
  1681. if(has_cond) ce->cond = Ctx__s_popx(ctx());
  1682. ce->iter = Ctx__s_popx(ctx());
  1683. ce->vars = Ctx__s_popx(ctx());
  1684. ce->expr = Ctx__s_popx(ctx());
  1685. Ctx__s_push(ctx(), (Expr*)ce);
  1686. return NULL;
  1687. }
  1688. static Error* exprList(Compiler* self) {
  1689. Error* err;
  1690. int line = prev()->line;
  1691. int count = 0;
  1692. do {
  1693. if(curr()->type == TK_RBRACKET) break;
  1694. check(EXPR(self));
  1695. count += 1;
  1696. if(count == 1 && match(TK_FOR)) {
  1697. check(consume_comp(self, OP_BUILD_LIST, OP_LIST_APPEND));
  1698. consume(TK_RBRACKET);
  1699. return NULL;
  1700. }
  1701. } while(match(TK_COMMA));
  1702. consume(TK_RBRACKET);
  1703. SequenceExpr* e = ListExpr__new(line, count);
  1704. for(int i = count - 1; i >= 0; i--) {
  1705. e->items[i] = Ctx__s_popx(ctx());
  1706. }
  1707. Ctx__s_push(ctx(), (Expr*)e);
  1708. return NULL;
  1709. }
  1710. static Error* exprMap(Compiler* self) {
  1711. Error* err;
  1712. int line = prev()->line;
  1713. bool parsing_dict = false; // {...} may be dict or set
  1714. int count = 0;
  1715. do {
  1716. if(curr()->type == TK_RBRACE) break;
  1717. check(EXPR(self)); // [key]
  1718. if(curr()->type == TK_COLON) { parsing_dict = true; }
  1719. if(parsing_dict) {
  1720. consume(TK_COLON);
  1721. check(EXPR(self)); // [key, value] -> [item]
  1722. DictItemExpr* item = DictItemExpr__new(prev()->line);
  1723. item->value = Ctx__s_popx(ctx());
  1724. item->key = Ctx__s_popx(ctx());
  1725. Ctx__s_push(ctx(), (Expr*)item);
  1726. }
  1727. count += 1; // key-value pair count
  1728. if(count == 1 && match(TK_FOR)) {
  1729. if(parsing_dict) {
  1730. check(consume_comp(self, OP_BUILD_DICT, OP_DICT_ADD));
  1731. } else {
  1732. check(consume_comp(self, OP_BUILD_SET, OP_SET_ADD));
  1733. }
  1734. consume(TK_RBRACE);
  1735. return NULL;
  1736. }
  1737. } while(match(TK_COMMA));
  1738. consume(TK_RBRACE);
  1739. SequenceExpr* se;
  1740. if(count == 0 || parsing_dict) {
  1741. se = DictExpr__new(line, count);
  1742. } else {
  1743. se = SetExpr__new(line, count);
  1744. }
  1745. for(int i = count - 1; i >= 0; i--) {
  1746. se->items[i] = Ctx__s_popx(ctx());
  1747. }
  1748. Ctx__s_push(ctx(), (Expr*)se);
  1749. return NULL;
  1750. }
  1751. static Error* read_literal(Compiler* self, py_Ref out);
  1752. static Error* exprCall(Compiler* self) {
  1753. Error* err;
  1754. Expr* callable = Ctx__s_popx(ctx());
  1755. int line = prev()->line;
  1756. CallExpr* e = CallExpr__new(line, callable);
  1757. Ctx__s_push(ctx(), (Expr*)e); // push onto the stack in advance
  1758. do {
  1759. if(curr()->type == TK_RPAREN) break;
  1760. if(curr()->type == TK_ID && next()->type == TK_ASSIGN) {
  1761. consume(TK_ID);
  1762. py_Name key = py_namev(Token__sv(prev()));
  1763. consume(TK_ASSIGN);
  1764. check(EXPR(self));
  1765. CallExprKwArg kw = {key, Ctx__s_popx(ctx())};
  1766. c11_vector__push(CallExprKwArg, &e->kwargs, kw);
  1767. } else {
  1768. check(EXPR(self));
  1769. int star_level = 0;
  1770. Expr* top = Ctx__s_top(ctx());
  1771. if(top->vt->is_starred) star_level = ((StarredExpr*)top)->level;
  1772. if(star_level == 2) {
  1773. // **kwargs
  1774. CallExprKwArg kw = {0, Ctx__s_popx(ctx())};
  1775. c11_vector__push(CallExprKwArg, &e->kwargs, kw);
  1776. } else {
  1777. // positional argument
  1778. if(e->kwargs.length > 0) {
  1779. return SyntaxError(self, "positional argument follows keyword argument");
  1780. }
  1781. c11_vector__push(Expr*, &e->args, Ctx__s_popx(ctx()));
  1782. }
  1783. }
  1784. } while(match(TK_COMMA));
  1785. consume(TK_RPAREN);
  1786. return NULL;
  1787. }
  1788. static Error* exprSlice0(Compiler* self) {
  1789. Error* err;
  1790. SliceExpr* slice = SliceExpr__new(prev()->line);
  1791. Ctx__s_push(ctx(), (Expr*)slice); // push onto the stack in advance
  1792. if(is_expression(self, false)) { // :<stop>
  1793. check(EXPR(self));
  1794. slice->stop = Ctx__s_popx(ctx());
  1795. // try optional step
  1796. if(match(TK_COLON)) { // :<stop>:<step>
  1797. check(EXPR(self));
  1798. slice->step = Ctx__s_popx(ctx());
  1799. }
  1800. } else if(match(TK_COLON)) {
  1801. if(is_expression(self, false)) { // ::<step>
  1802. check(EXPR(self));
  1803. slice->step = Ctx__s_popx(ctx());
  1804. } // else ::
  1805. } // else :
  1806. return NULL;
  1807. }
  1808. static Error* exprSlice1(Compiler* self) {
  1809. Error* err;
  1810. SliceExpr* slice = SliceExpr__new(prev()->line);
  1811. slice->start = Ctx__s_popx(ctx());
  1812. Ctx__s_push(ctx(), (Expr*)slice); // push onto the stack in advance
  1813. if(is_expression(self, false)) { // <start>:<stop>
  1814. check(EXPR(self));
  1815. slice->stop = Ctx__s_popx(ctx());
  1816. // try optional step
  1817. if(match(TK_COLON)) { // <start>:<stop>:<step>
  1818. check(EXPR(self));
  1819. slice->step = Ctx__s_popx(ctx());
  1820. }
  1821. } else if(match(TK_COLON)) { // <start>::<step>
  1822. check(EXPR(self));
  1823. slice->step = Ctx__s_popx(ctx());
  1824. } // else <start>:
  1825. return NULL;
  1826. }
  1827. static Error* exprSubscr(Compiler* self) {
  1828. Error* err;
  1829. int line = prev()->line;
  1830. check(EXPR_TUPLE_ALLOW_SLICE(self, true));
  1831. consume(TK_RBRACKET); // [lhs, rhs]
  1832. SubscrExpr* e = SubscrExpr__new(line);
  1833. e->rhs = Ctx__s_popx(ctx()); // [lhs]
  1834. e->lhs = Ctx__s_popx(ctx()); // []
  1835. Ctx__s_push(ctx(), (Expr*)e);
  1836. return NULL;
  1837. }
  1838. ////////////////
  1839. static Error* consume_type_hints(Compiler* self) {
  1840. Error* err;
  1841. check(EXPR(self));
  1842. Ctx__s_pop(ctx());
  1843. return NULL;
  1844. }
  1845. static Error* consume_type_hints_sv(Compiler* self, c11_sv* out) {
  1846. Error* err;
  1847. const char* start = curr()->start;
  1848. check(EXPR(self));
  1849. const char* end = prev()->start + prev()->length;
  1850. *out = (c11_sv){start, end - start};
  1851. Ctx__s_pop(ctx());
  1852. return NULL;
  1853. }
  1854. static Error* compile_stmt(Compiler* self);
  1855. static Error* compile_block_body(Compiler* self) {
  1856. Error* err;
  1857. consume(TK_COLON);
  1858. if(curr()->type != TK_EOL && curr()->type != TK_EOF) {
  1859. while(true) {
  1860. check(compile_stmt(self));
  1861. bool possible = curr()->type != TK_EOL && curr()->type != TK_EOF;
  1862. if(prev()->type != TK_SEMICOLON || !possible) break;
  1863. }
  1864. return NULL;
  1865. }
  1866. bool consumed = match_newlines();
  1867. if(!consumed) return SyntaxError(self, "expected a new line after ':'");
  1868. consume(TK_INDENT);
  1869. while(curr()->type != TK_DEDENT) {
  1870. match_newlines();
  1871. check(compile_stmt(self));
  1872. match_newlines();
  1873. }
  1874. consume(TK_DEDENT);
  1875. return NULL;
  1876. }
  1877. static Error* compile_if_stmt(Compiler* self) {
  1878. Error* err;
  1879. check(EXPR(self)); // condition
  1880. Ctx__s_emit_top(ctx());
  1881. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, prev()->line);
  1882. err = compile_block_body(self);
  1883. if(err) return err;
  1884. if(match(TK_ELIF)) {
  1885. int exit_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  1886. Ctx__patch_jump(ctx(), patch);
  1887. check(compile_if_stmt(self));
  1888. Ctx__patch_jump(ctx(), exit_patch);
  1889. } else if(match(TK_ELSE)) {
  1890. int exit_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  1891. Ctx__patch_jump(ctx(), patch);
  1892. check(compile_block_body(self));
  1893. Ctx__patch_jump(ctx(), exit_patch);
  1894. } else {
  1895. Ctx__patch_jump(ctx(), patch);
  1896. }
  1897. return NULL;
  1898. }
  1899. static Error* compile_match_case(Compiler* self, c11_vector* patches) {
  1900. Error* err;
  1901. bool is_case_default = false;
  1902. check(EXPR(self)); // condition
  1903. Ctx__s_emit_top(ctx());
  1904. consume(TK_COLON);
  1905. bool consumed = match_newlines();
  1906. if(!consumed) return SyntaxError(self, "expected a new line after ':'");
  1907. consume(TK_INDENT);
  1908. while(curr()->type != TK_DEDENT) {
  1909. match_newlines();
  1910. if(match_id_by_str(self, "case")) {
  1911. if(is_case_default) return SyntaxError(self, "case _: must be the last one");
  1912. is_case_default = match_id_by_str(self, "_");
  1913. if(!is_case_default) {
  1914. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, prev()->line);
  1915. check(EXPR(self)); // expr
  1916. Ctx__s_emit_top(ctx());
  1917. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_NOT_MATCH, BC_NOARG, prev()->line);
  1918. check(compile_block_body(self));
  1919. int break_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  1920. c11_vector__push(int, patches, break_patch);
  1921. Ctx__patch_jump(ctx(), patch);
  1922. } else {
  1923. check(compile_block_body(self));
  1924. }
  1925. } else {
  1926. return SyntaxError(self, "expected 'case', got '%s'", TokenSymbols[curr()->type]);
  1927. }
  1928. match_newlines();
  1929. }
  1930. consume(TK_DEDENT);
  1931. for(int i = 0; i < patches->length; i++) {
  1932. int patch = c11__getitem(int, patches, i);
  1933. Ctx__patch_jump(ctx(), patch);
  1934. }
  1935. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, prev()->line);
  1936. return NULL;
  1937. }
  1938. static Error* compile_while_loop(Compiler* self) {
  1939. Error* err;
  1940. int block = Ctx__enter_block(ctx(), CodeBlockType_WHILE_LOOP);
  1941. int block_start = c11__at(CodeBlock, &ctx()->co->blocks, block)->start;
  1942. check(EXPR(self)); // condition
  1943. Ctx__s_emit_top(ctx());
  1944. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, prev()->line);
  1945. check(compile_block_body(self));
  1946. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  1947. Ctx__patch_jump(ctx(), patch);
  1948. Ctx__exit_block(ctx());
  1949. // optional else clause
  1950. if(match(TK_ELSE)) {
  1951. check(compile_block_body(self));
  1952. CodeBlock* p_block = c11__at(CodeBlock, &ctx()->co->blocks, block);
  1953. p_block->end2 = ctx()->co->codes.length;
  1954. }
  1955. return NULL;
  1956. }
  1957. static Error* compile_for_loop(Compiler* self) {
  1958. Error* err;
  1959. check(EXPR_VARS(self)); // [vars]
  1960. consume(TK_IN);
  1961. check(EXPR_TUPLE(self)); // [vars, iter]
  1962. Ctx__s_emit_top(ctx()); // [vars]
  1963. Ctx__emit_(ctx(), OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  1964. int block = Ctx__enter_block(ctx(), CodeBlockType_FOR_LOOP);
  1965. int block_start = Ctx__emit_(ctx(), OP_FOR_ITER, block, BC_KEEPLINE);
  1966. Expr* vars = Ctx__s_popx(ctx());
  1967. bool ok = vtemit_store(vars, ctx());
  1968. vtdelete(vars);
  1969. if(!ok) {
  1970. // this error occurs in `vars` instead of this line, but...nevermind
  1971. return SyntaxError(self, "invalid syntax");
  1972. }
  1973. check(compile_block_body(self));
  1974. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  1975. Ctx__exit_block(ctx());
  1976. // optional else clause
  1977. if(match(TK_ELSE)) {
  1978. check(compile_block_body(self));
  1979. CodeBlock* p_block = c11__at(CodeBlock, &ctx()->co->blocks, block);
  1980. p_block->end2 = ctx()->co->codes.length;
  1981. }
  1982. return NULL;
  1983. }
  1984. static Error* compile_yield_from(Compiler* self, int kw_line) {
  1985. Error* err;
  1986. if(self->contexts.length <= 1) return SyntaxError(self, "'yield from' outside function");
  1987. check(EXPR_TUPLE(self));
  1988. Ctx__s_emit_top(ctx());
  1989. Ctx__emit_(ctx(), OP_GET_ITER, BC_NOARG, kw_line);
  1990. int block = Ctx__enter_block(ctx(), CodeBlockType_FOR_LOOP);
  1991. int block_start = Ctx__emit_(ctx(), OP_FOR_ITER_YIELD_VALUE, block, kw_line);
  1992. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  1993. Ctx__exit_block(ctx());
  1994. // StopIteration.value will be pushed onto the stack
  1995. return NULL;
  1996. }
  1997. Error* try_compile_assignment(Compiler* self, bool* is_assign) {
  1998. Error* err;
  1999. switch(curr()->type) {
  2000. case TK_IADD:
  2001. case TK_ISUB:
  2002. case TK_IMUL:
  2003. case TK_IDIV:
  2004. case TK_IFLOORDIV:
  2005. case TK_IMOD:
  2006. case TK_ILSHIFT:
  2007. case TK_IRSHIFT:
  2008. case TK_IAND:
  2009. case TK_IOR:
  2010. case TK_IXOR: {
  2011. if(Ctx__s_top(ctx())->vt->is_starred)
  2012. return SyntaxError(self, "can't use inplace operator with starred expression");
  2013. if(ctx()->is_compiling_class)
  2014. return SyntaxError(self, "can't use inplace operator in class definition");
  2015. advance();
  2016. // a[x] += 1; a and x should be evaluated only once
  2017. // a.x += 1; a should be evaluated only once
  2018. // -1 to remove =; inplace=true
  2019. int line = prev()->line;
  2020. TokenIndex op = (TokenIndex)(prev()->type - 1);
  2021. // [lhs]
  2022. check(EXPR_TUPLE(self)); // [lhs, rhs]
  2023. if(Ctx__s_top(ctx())->vt->is_starred)
  2024. return SyntaxError(self, "can't use starred expression here");
  2025. BinaryExpr* e = BinaryExpr__new(line, op, true);
  2026. e->rhs = Ctx__s_popx(ctx()); // [lhs]
  2027. e->lhs = Ctx__s_popx(ctx()); // []
  2028. vtemit_((Expr*)e, ctx());
  2029. bool ok = vtemit_istore(e->lhs, ctx());
  2030. vtdelete((Expr*)e);
  2031. if(!ok) return SyntaxError(self, "invalid syntax");
  2032. *is_assign = true;
  2033. return NULL;
  2034. }
  2035. case TK_ASSIGN: {
  2036. consume(TK_ASSIGN);
  2037. int n = 0; // assignment count
  2038. if(match(TK_YIELD_FROM)) {
  2039. check(compile_yield_from(self, prev()->line));
  2040. n = 1;
  2041. } else {
  2042. do {
  2043. check(EXPR_TUPLE(self));
  2044. n += 1;
  2045. } while(match(TK_ASSIGN));
  2046. // stack size is n+1
  2047. Ctx__s_emit_top(ctx());
  2048. for(int j = 1; j < n; j++)
  2049. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  2050. }
  2051. for(int j = 0; j < n; j++) {
  2052. if(Ctx__s_top(ctx())->vt->is_starred)
  2053. return SyntaxError(self, "can't use starred expression here");
  2054. Expr* e = Ctx__s_top(ctx());
  2055. bool ok = vtemit_store(e, ctx());
  2056. Ctx__s_pop(ctx());
  2057. if(!ok) return SyntaxError(self, "invalid syntax");
  2058. }
  2059. *is_assign = true;
  2060. return NULL;
  2061. }
  2062. default: *is_assign = false;
  2063. }
  2064. return NULL;
  2065. }
  2066. static FuncDecl_ push_f_context(Compiler* self, c11_sv name, int* out_index) {
  2067. FuncDecl_ decl = FuncDecl__rcnew(self->src, name);
  2068. decl->code.start_line = self->i == 0 ? 1 : prev()->line;
  2069. decl->nested = name_scope(self) == NAME_LOCAL;
  2070. // add_func_decl
  2071. Ctx* top_ctx = ctx();
  2072. c11_vector__push(FuncDecl_, &top_ctx->co->func_decls, decl);
  2073. *out_index = top_ctx->co->func_decls.length - 1;
  2074. // push new context
  2075. top_ctx = c11_vector__emplace(&self->contexts);
  2076. Ctx__ctor(top_ctx, &decl->code, decl, self->contexts.length, self->n_self);
  2077. return decl;
  2078. }
  2079. static Error* read_literal(Compiler* self, py_Ref out) {
  2080. Error* err;
  2081. advance();
  2082. const TokenValue* value = &prev()->value;
  2083. bool negated = false;
  2084. switch(prev()->type) {
  2085. case TK_SUB:
  2086. consume(TK_NUM);
  2087. value = &prev()->value;
  2088. negated = true;
  2089. case TK_NUM: {
  2090. if(value->index == TokenValue_I64) {
  2091. py_newint(out, negated ? -value->_i64 : value->_i64);
  2092. } else if(value->index == TokenValue_F64) {
  2093. py_newfloat(out, negated ? -value->_f64 : value->_f64);
  2094. } else {
  2095. c11__unreachable();
  2096. }
  2097. return NULL;
  2098. }
  2099. case TK_STR: py_newstr(out, value->_str->data); return NULL;
  2100. case TK_TRUE: py_newbool(out, true); return NULL;
  2101. case TK_FALSE: py_newbool(out, false); return NULL;
  2102. case TK_NONE: py_newnone(out); return NULL;
  2103. case TK_DOTDOTDOT: py_newellipsis(out); return NULL;
  2104. case TK_LPAREN: {
  2105. py_TValue cpnts[4];
  2106. int count = 0;
  2107. while(true) {
  2108. if(count == 4)
  2109. return SyntaxError(self, "default argument tuple exceeds 4 elements");
  2110. check(read_literal(self, &cpnts[count]));
  2111. count += 1;
  2112. if(curr()->type == TK_RPAREN) break;
  2113. consume(TK_COMMA);
  2114. if(curr()->type == TK_RPAREN) break;
  2115. }
  2116. consume(TK_RPAREN);
  2117. py_Ref p = py_newtuple(out, count);
  2118. for(int i = 0; i < count; i++) {
  2119. p[i] = cpnts[i];
  2120. }
  2121. return NULL;
  2122. }
  2123. default: {
  2124. return SyntaxError(self, "expected a literal, got '%s'", TokenSymbols[prev()->type]);
  2125. }
  2126. }
  2127. }
  2128. static Error* _compile_f_args(Compiler* self, FuncDecl* decl, bool is_lambda) {
  2129. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  2130. Error* err;
  2131. do {
  2132. // allow trailing comma
  2133. if(!is_lambda && curr()->type == TK_RPAREN) break;
  2134. if(state >= 3) return SyntaxError(self, "**kwargs should be the last argument");
  2135. if(match(TK_MUL)) {
  2136. if(state < 1)
  2137. state = 1;
  2138. else
  2139. return SyntaxError(self, "*args should be placed before **kwargs");
  2140. } else if(match(TK_POW)) {
  2141. state = 3;
  2142. }
  2143. consume(TK_ID);
  2144. py_Name name = py_namev(Token__sv(prev()));
  2145. // check duplicate argument name
  2146. if(FuncDecl__is_duplicated_arg(decl, name)) {
  2147. return SyntaxError(self, "duplicate argument name");
  2148. }
  2149. // eat type hints
  2150. if(!is_lambda && match(TK_COLON)) check(consume_type_hints(self));
  2151. if(state == 0 && curr()->type == TK_ASSIGN) state = 2;
  2152. switch(state) {
  2153. case 0: FuncDecl__add_arg(decl, name); break;
  2154. case 1:
  2155. FuncDecl__add_starred_arg(decl, name);
  2156. state += 1;
  2157. break;
  2158. case 2: {
  2159. consume(TK_ASSIGN);
  2160. py_TValue value;
  2161. check(read_literal(self, &value));
  2162. FuncDecl__add_kwarg(decl, name, &value);
  2163. } break;
  2164. case 3:
  2165. FuncDecl__add_starred_kwarg(decl, name);
  2166. state += 1;
  2167. break;
  2168. }
  2169. } while(match(TK_COMMA));
  2170. return NULL;
  2171. }
  2172. static Error* consume_pep695_py312(Compiler* self) {
  2173. // https://peps.python.org/pep-0695/
  2174. Error* err;
  2175. if(match(TK_LBRACKET)) {
  2176. do {
  2177. consume(TK_ID);
  2178. if(match(TK_COLON)) check(consume_type_hints(self));
  2179. } while(match(TK_COMMA));
  2180. consume(TK_RBRACKET);
  2181. }
  2182. return NULL;
  2183. }
  2184. static Error* compile_function(Compiler* self, int decorators) {
  2185. Error* err;
  2186. int def_line = prev()->line;
  2187. consume(TK_ID);
  2188. c11_sv decl_name_sv = Token__sv(prev());
  2189. int decl_index;
  2190. FuncDecl_ decl = push_f_context(self, decl_name_sv, &decl_index);
  2191. consume_pep695_py312(self);
  2192. consume(TK_LPAREN);
  2193. if(!match(TK_RPAREN)) {
  2194. check(_compile_f_args(self, decl, false));
  2195. consume(TK_RPAREN);
  2196. }
  2197. if(match(TK_ARROW)) check(consume_type_hints(self));
  2198. check(compile_block_body(self));
  2199. check(pop_context(self));
  2200. if(decl->code.codes.length >= 2) {
  2201. Bytecode* codes = (Bytecode*)decl->code.codes.data;
  2202. if(codes[0].op == OP_LOAD_CONST && codes[1].op == OP_POP_TOP) {
  2203. // handle optional docstring
  2204. py_TValue* consts = decl->code.consts.data;
  2205. py_TValue* c = &consts[codes[0].arg];
  2206. if(py_isstr(c)) {
  2207. decl->docstring = c11_strdup(py_tostr(c));
  2208. codes[0].op = OP_NO_OP;
  2209. codes[1].op = OP_NO_OP;
  2210. }
  2211. }
  2212. }
  2213. Ctx__emit_(ctx(), OP_LOAD_FUNCTION, decl_index, def_line);
  2214. Ctx__s_emit_decorators(ctx(), decorators);
  2215. py_Name decl_name = py_namev(decl_name_sv);
  2216. if(ctx()->is_compiling_class) {
  2217. if(decl_name == __new__ || decl_name == __init__) {
  2218. if(decl->args.length == 0) {
  2219. return SyntaxError(self,
  2220. "%s() should have at least one positional argument",
  2221. py_name2str(decl_name));
  2222. }
  2223. }
  2224. Ctx__emit_(ctx(), OP_STORE_CLASS_ATTR, Ctx__add_name(ctx(), decl_name), def_line);
  2225. } else {
  2226. NameExpr* e = NameExpr__new(def_line, decl_name, name_scope(self));
  2227. vtemit_store((Expr*)e, ctx());
  2228. vtdelete((Expr*)e);
  2229. }
  2230. return NULL;
  2231. }
  2232. static Error* compile_class(Compiler* self, int decorators) {
  2233. Error* err;
  2234. if(ctx()->level > 1) return SyntaxError(self, "class definition not allowed here");
  2235. consume(TK_ID);
  2236. py_Name name = py_namev(Token__sv(prev()));
  2237. bool has_base = false;
  2238. consume_pep695_py312(self);
  2239. if(match(TK_LPAREN)) {
  2240. if(is_expression(self, false)) {
  2241. check(EXPR(self));
  2242. has_base = true; // [base]
  2243. }
  2244. consume(TK_RPAREN);
  2245. }
  2246. if(!has_base) {
  2247. Ctx__emit_(ctx(), OP_LOAD_NONE, BC_NOARG, prev()->line);
  2248. } else {
  2249. Ctx__s_emit_top(ctx()); // []
  2250. }
  2251. Ctx__emit_(ctx(), OP_BEGIN_CLASS, Ctx__add_name(ctx(), name), BC_KEEPLINE);
  2252. c11__foreach(Ctx, &self->contexts, it) {
  2253. if(it->is_compiling_class) return SyntaxError(self, "nested class is not allowed");
  2254. }
  2255. ctx()->is_compiling_class = true;
  2256. check(compile_block_body(self));
  2257. ctx()->is_compiling_class = false;
  2258. Ctx__s_emit_decorators(ctx(), decorators);
  2259. Ctx__emit_(ctx(), OP_END_CLASS, Ctx__add_name(ctx(), name), BC_KEEPLINE);
  2260. return NULL;
  2261. }
  2262. static Error* compile_decorated(Compiler* self) {
  2263. Error* err;
  2264. int count = 0;
  2265. do {
  2266. check(EXPR(self));
  2267. count += 1;
  2268. if(!match_newlines()) return SyntaxError(self, "expected a newline after '@'");
  2269. } while(match(TK_DECORATOR));
  2270. if(match(TK_CLASS)) {
  2271. check(compile_class(self, count));
  2272. } else {
  2273. consume(TK_DEF);
  2274. check(compile_function(self, count));
  2275. }
  2276. return NULL;
  2277. }
  2278. // import a [as b]
  2279. // import a [as b], c [as d]
  2280. static Error* compile_normal_import(Compiler* self, c11_sbuf* buf) {
  2281. do {
  2282. consume(TK_ID);
  2283. c11_sv name = Token__sv(prev());
  2284. c11_sbuf__write_sv(buf, name);
  2285. bool has_sub_cpnt = false;
  2286. while(match(TK_DOT)) {
  2287. has_sub_cpnt = true;
  2288. consume(TK_ID);
  2289. c11_sbuf__write_char(buf, '.');
  2290. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2291. }
  2292. c11_string* path = c11_sbuf__submit(buf);
  2293. c11_sbuf__ctor(buf);
  2294. int path_index = Ctx__add_const_string(ctx(), c11_string__sv(path));
  2295. c11_string__delete(path);
  2296. NameScope scope = name_scope(self);
  2297. Ctx__emit_(ctx(), OP_IMPORT_PATH, path_index, prev()->line);
  2298. // [module <path>]
  2299. if(!has_sub_cpnt) {
  2300. if(match(TK_AS)) {
  2301. // import a as x
  2302. consume(TK_ID);
  2303. name = Token__sv(prev());
  2304. } else {
  2305. // import a
  2306. }
  2307. } else {
  2308. if(match(TK_AS)) {
  2309. // import a.b as x
  2310. consume(TK_ID);
  2311. name = Token__sv(prev());
  2312. } else {
  2313. // import a.b
  2314. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2315. int index = Ctx__add_const_string(ctx(), name);
  2316. Ctx__emit_(ctx(), OP_IMPORT_PATH, index, BC_KEEPLINE);
  2317. }
  2318. }
  2319. Ctx__emit_store_name(ctx(), scope, py_namev(name), BC_KEEPLINE);
  2320. } while(match(TK_COMMA));
  2321. consume_end_stmt();
  2322. return NULL;
  2323. }
  2324. // from a import b [as c], d [as e]
  2325. // from a.b import c [as d]
  2326. // from . import a [as b]
  2327. // from .a import b [as c]
  2328. // from ..a import b [as c]
  2329. // from .a.b import c [as d]
  2330. // from xxx import *
  2331. static Error* compile_from_import(Compiler* self, c11_sbuf* buf) {
  2332. int dots = 0;
  2333. while(true) {
  2334. switch(curr()->type) {
  2335. case TK_DOT: dots += 1; break;
  2336. case TK_DOTDOT: dots += 2; break;
  2337. case TK_DOTDOTDOT: dots += 3; break;
  2338. default: goto __EAT_DOTS_END;
  2339. }
  2340. advance();
  2341. }
  2342. __EAT_DOTS_END:
  2343. for(int i = 0; i < dots; i++) {
  2344. c11_sbuf__write_char(buf, '.');
  2345. }
  2346. if(dots > 0) {
  2347. // @id is optional if dots > 0
  2348. if(match(TK_ID)) {
  2349. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2350. while(match(TK_DOT)) {
  2351. consume(TK_ID);
  2352. c11_sbuf__write_char(buf, '.');
  2353. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2354. }
  2355. }
  2356. } else {
  2357. // @id is required if dots == 0
  2358. consume(TK_ID);
  2359. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2360. while(match(TK_DOT)) {
  2361. consume(TK_ID);
  2362. c11_sbuf__write_char(buf, '.');
  2363. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2364. }
  2365. }
  2366. c11_string* path = c11_sbuf__submit(buf);
  2367. Ctx__emit_(ctx(),
  2368. OP_IMPORT_PATH,
  2369. Ctx__add_const_string(ctx(), c11_string__sv(path)),
  2370. prev()->line);
  2371. c11_string__delete(path);
  2372. consume(TK_IMPORT);
  2373. if(match(TK_MUL)) {
  2374. if(name_scope(self) != NAME_GLOBAL)
  2375. return SyntaxError(self, "from <module> import * can only be used in global scope");
  2376. // pop the module and import __all__
  2377. Ctx__emit_(ctx(), OP_POP_IMPORT_STAR, BC_NOARG, prev()->line);
  2378. consume_end_stmt();
  2379. return NULL;
  2380. }
  2381. bool has_bracket = match(TK_LPAREN);
  2382. do {
  2383. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  2384. consume(TK_ID);
  2385. c11_sv name = Token__sv(prev());
  2386. Ctx__emit_(ctx(), OP_LOAD_ATTR, Ctx__add_name(ctx(), py_namev(name)), prev()->line);
  2387. if(match(TK_AS)) {
  2388. consume(TK_ID);
  2389. name = Token__sv(prev());
  2390. }
  2391. Ctx__emit_store_name(ctx(), name_scope(self), py_namev(name), prev()->line);
  2392. } while(match(TK_COMMA));
  2393. if(has_bracket) { consume(TK_RPAREN); }
  2394. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2395. consume_end_stmt();
  2396. return NULL;
  2397. }
  2398. static Error* compile_try_except(Compiler* self) {
  2399. Error* err;
  2400. int patches[8];
  2401. int patches_length = 0;
  2402. Ctx__enter_block(ctx(), CodeBlockType_TRY);
  2403. Ctx__emit_(ctx(), OP_BEGIN_TRY, BC_NOARG, prev()->line);
  2404. check(compile_block_body(self));
  2405. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  2406. // https://docs.python.org/3/reference/compound_stmts.html#finally-clause
  2407. /* If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed,
  2408. * including any except and else clauses. If an exception occurs in any of the clauses and is
  2409. * not handled, the exception is temporarily saved. The finally clause is executed. If there is
  2410. * a saved exception it is re-raised at the end of the finally clause. If the finally clause
  2411. * raises another exception, the saved exception is set as the context of the new exception. If
  2412. * the finally clause executes a return, break or continue statement, the saved exception is
  2413. * discarded.
  2414. */
  2415. // known issue:
  2416. // A return, break, continue in try/except block will make the finally block not executed
  2417. bool has_finally = curr()->type == TK_FINALLY;
  2418. if(has_finally) return SyntaxError(self, "finally clause is not supported yet");
  2419. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  2420. Ctx__exit_block(ctx());
  2421. do {
  2422. if(patches_length == 8) {
  2423. return SyntaxError(self, "maximum number of except clauses reached");
  2424. }
  2425. py_Name as_name = 0;
  2426. consume(TK_EXCEPT);
  2427. if(is_expression(self, false)) {
  2428. // except <expr>:
  2429. check(EXPR(self));
  2430. Ctx__s_emit_top(ctx());
  2431. Ctx__emit_(ctx(), OP_EXCEPTION_MATCH, BC_NOARG, prev()->line);
  2432. if(match(TK_AS)) {
  2433. // except <expr> as <name>:
  2434. consume(TK_ID);
  2435. as_name = py_namev(Token__sv(prev()));
  2436. }
  2437. } else {
  2438. // except:
  2439. Ctx__emit_(ctx(), OP_LOAD_TRUE, BC_NOARG, BC_KEEPLINE);
  2440. }
  2441. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  2442. // on match
  2443. Ctx__emit_(ctx(), OP_HANDLE_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  2444. if(as_name) {
  2445. Ctx__emit_(ctx(), OP_PUSH_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  2446. Ctx__emit_store_name(ctx(), name_scope(self), as_name, BC_KEEPLINE);
  2447. }
  2448. Ctx__enter_block(ctx(), CodeBlockType_EXCEPT);
  2449. check(compile_block_body(self));
  2450. Ctx__exit_block(ctx());
  2451. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  2452. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  2453. Ctx__patch_jump(ctx(), patch);
  2454. } while(curr()->type == TK_EXCEPT);
  2455. // no match, re-raise
  2456. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, BC_KEEPLINE);
  2457. // match one & handled, jump to the end
  2458. for(int i = 0; i < patches_length; i++) {
  2459. Ctx__patch_jump(ctx(), patches[i]);
  2460. }
  2461. if(match(TK_FINALLY)) return SyntaxError(self, "finally clause is not supported yet");
  2462. return NULL;
  2463. }
  2464. static Error* compile_stmt(Compiler* self) {
  2465. Error* err;
  2466. if(match(TK_CLASS)) {
  2467. check(compile_class(self, 0));
  2468. return NULL;
  2469. }
  2470. advance();
  2471. int kw_line = prev()->line; // backup line number
  2472. switch(prev()->type) {
  2473. case TK_BREAK: {
  2474. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, true);
  2475. if(curr_loop_block < 0) return SyntaxError(self, "'break' outside loop");
  2476. Ctx__emit_(ctx(), OP_LOOP_BREAK, curr_loop_block, kw_line);
  2477. consume_end_stmt();
  2478. break;
  2479. }
  2480. case TK_CONTINUE: {
  2481. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, false);
  2482. if(curr_loop_block < 0) return SyntaxError(self, "'continue' not properly in loop");
  2483. Ctx__emit_(ctx(), OP_LOOP_CONTINUE, curr_loop_block, kw_line);
  2484. consume_end_stmt();
  2485. break;
  2486. }
  2487. case TK_YIELD:
  2488. if(self->contexts.length <= 1) return SyntaxError(self, "'yield' outside function");
  2489. if(match_end_stmt(self)) {
  2490. Ctx__emit_(ctx(), OP_YIELD_VALUE, 1, kw_line);
  2491. } else {
  2492. check(EXPR_TUPLE(self));
  2493. Ctx__s_emit_top(ctx());
  2494. Ctx__emit_(ctx(), OP_YIELD_VALUE, BC_NOARG, kw_line);
  2495. consume_end_stmt();
  2496. }
  2497. break;
  2498. case TK_YIELD_FROM:
  2499. check(compile_yield_from(self, kw_line));
  2500. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, kw_line);
  2501. consume_end_stmt();
  2502. break;
  2503. case TK_RETURN:
  2504. if(self->contexts.length <= 1) return SyntaxError(self, "'return' outside function");
  2505. if(match_end_stmt(self)) {
  2506. Ctx__emit_(ctx(), OP_RETURN_VALUE, 1, kw_line);
  2507. } else {
  2508. check(EXPR_TUPLE(self));
  2509. Ctx__s_emit_top(ctx());
  2510. consume_end_stmt();
  2511. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, kw_line);
  2512. }
  2513. break;
  2514. /*************************************************/
  2515. case TK_IF: check(compile_if_stmt(self)); break;
  2516. case TK_MATCH: {
  2517. c11_vector patches;
  2518. c11_vector__ctor(&patches, sizeof(int));
  2519. check(compile_match_case(self, &patches));
  2520. c11_vector__dtor(&patches);
  2521. break;
  2522. }
  2523. case TK_WHILE: check(compile_while_loop(self)); break;
  2524. case TK_FOR: check(compile_for_loop(self)); break;
  2525. case TK_IMPORT: {
  2526. c11_sbuf buf;
  2527. c11_sbuf__ctor(&buf);
  2528. err = compile_normal_import(self, &buf);
  2529. c11_sbuf__dtor(&buf);
  2530. if(err) return err;
  2531. break;
  2532. }
  2533. case TK_FROM: {
  2534. c11_sbuf buf;
  2535. c11_sbuf__ctor(&buf);
  2536. err = compile_from_import(self, &buf);
  2537. c11_sbuf__dtor(&buf);
  2538. if(err) return err;
  2539. break;
  2540. }
  2541. case TK_DEF: check(compile_function(self, 0)); break;
  2542. case TK_DECORATOR: check(compile_decorated(self)); break;
  2543. case TK_TRY: check(compile_try_except(self)); break;
  2544. case TK_PASS: consume_end_stmt(); break;
  2545. /*************************************************/
  2546. case TK_ASSERT: {
  2547. check(EXPR(self)); // condition
  2548. Ctx__s_emit_top(ctx());
  2549. int index = Ctx__emit_(ctx(), OP_POP_JUMP_IF_TRUE, BC_NOARG, kw_line);
  2550. int has_msg = 0;
  2551. if(match(TK_COMMA)) {
  2552. check(EXPR(self)); // message
  2553. Ctx__s_emit_top(ctx());
  2554. has_msg = 1;
  2555. }
  2556. Ctx__emit_(ctx(), OP_RAISE_ASSERT, has_msg, kw_line);
  2557. Ctx__patch_jump(ctx(), index);
  2558. consume_end_stmt();
  2559. break;
  2560. }
  2561. case TK_GLOBAL:
  2562. do {
  2563. consume(TK_ID);
  2564. py_Name name = py_namev(Token__sv(prev()));
  2565. c11_smallmap_n2d__set(&ctx()->global_names, name, 0);
  2566. } while(match(TK_COMMA));
  2567. consume_end_stmt();
  2568. break;
  2569. case TK_RAISE: {
  2570. if(is_expression(self, false)) {
  2571. check(EXPR(self));
  2572. Ctx__s_emit_top(ctx());
  2573. Ctx__emit_(ctx(), OP_RAISE, BC_NOARG, kw_line);
  2574. } else {
  2575. int iblock = ctx()->curr_iblock;
  2576. CodeBlock* blocks = (CodeBlock*)ctx()->co->blocks.data;
  2577. if(blocks[iblock].type != CodeBlockType_EXCEPT) {
  2578. return SyntaxError(self,
  2579. "raise without exception is only allowed in except block");
  2580. }
  2581. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, kw_line);
  2582. }
  2583. consume_end_stmt();
  2584. } break;
  2585. case TK_DEL: {
  2586. check(EXPR_TUPLE(self));
  2587. Expr* e = Ctx__s_top(ctx());
  2588. if(!vtemit_del(e, ctx())) return SyntaxError(self, "invalid syntax");
  2589. Ctx__s_pop(ctx());
  2590. consume_end_stmt();
  2591. } break;
  2592. case TK_WITH: {
  2593. check(EXPR(self)); // [ <expr> ]
  2594. Ctx__s_emit_top(ctx());
  2595. Ctx__enter_block(ctx(), CodeBlockType_WITH);
  2596. NameExpr* as_name = NULL;
  2597. if(match(TK_AS)) {
  2598. consume(TK_ID);
  2599. py_Name name = py_namev(Token__sv(prev()));
  2600. as_name = NameExpr__new(prev()->line, name, name_scope(self));
  2601. }
  2602. Ctx__emit_(ctx(), OP_WITH_ENTER, BC_NOARG, prev()->line);
  2603. // [ <expr> <expr>.__enter__() ]
  2604. if(as_name) {
  2605. bool ok = vtemit_store((Expr*)as_name, ctx());
  2606. vtdelete((Expr*)as_name);
  2607. if(!ok) return SyntaxError(self, "invalid syntax");
  2608. } else {
  2609. // discard `__enter__()`'s return value
  2610. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2611. }
  2612. check(compile_block_body(self));
  2613. Ctx__emit_(ctx(), OP_WITH_EXIT, BC_NOARG, prev()->line);
  2614. Ctx__exit_block(ctx());
  2615. } break;
  2616. /*************************************************/
  2617. // handle dangling expression or assignment
  2618. default: {
  2619. // do revert since we have pre-called advance() at the beginning
  2620. --self->i;
  2621. check(EXPR_TUPLE(self));
  2622. bool is_typed_name = false; // e.g. x: int
  2623. // eat variable's type hint if it is a single name
  2624. const ExprVt* top_vt = Ctx__s_top(ctx())->vt;
  2625. if(top_vt->is_name || top_vt->is_attrib) {
  2626. if(match(TK_COLON)) {
  2627. c11_sv type_hint;
  2628. check(consume_type_hints_sv(self, &type_hint));
  2629. is_typed_name = true;
  2630. if(ctx()->is_compiling_class && top_vt->is_name) {
  2631. NameExpr* ne = (NameExpr*)Ctx__s_top(ctx());
  2632. int index = Ctx__add_const_string(ctx(), type_hint);
  2633. Ctx__emit_(ctx(), OP_LOAD_CONST, index, BC_KEEPLINE);
  2634. Ctx__emit_(ctx(),
  2635. OP_ADD_CLASS_ANNOTATION,
  2636. Ctx__add_name(ctx(), ne->name),
  2637. BC_KEEPLINE);
  2638. }
  2639. }
  2640. }
  2641. bool is_assign = false;
  2642. check(try_compile_assignment(self, &is_assign));
  2643. if(!is_assign) {
  2644. if(Ctx__s_size(ctx()) > 0 && Ctx__s_top(ctx())->vt->is_starred) {
  2645. return SyntaxError(self, "can't use starred expression here");
  2646. }
  2647. if(!is_typed_name) {
  2648. Ctx__s_emit_top(ctx());
  2649. if((mode() == SINGLE_MODE) && name_scope(self) == NAME_GLOBAL) {
  2650. Ctx__emit_(ctx(), OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  2651. } else {
  2652. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2653. }
  2654. } else {
  2655. Ctx__s_pop(ctx());
  2656. }
  2657. }
  2658. consume_end_stmt();
  2659. break;
  2660. }
  2661. }
  2662. return NULL;
  2663. }
  2664. /////////////////////////////////////////////////////////////////
  2665. Error* Compiler__compile(Compiler* self, CodeObject* out) {
  2666. // make sure it is the first time to compile
  2667. assert(self->i == 0);
  2668. // make sure the first token is @sof
  2669. assert(tk(0)->type == TK_SOF);
  2670. push_global_context(self, out);
  2671. advance(); // skip @sof, so prev() is always valid
  2672. match_newlines(); // skip possible leading '\n'
  2673. Error* err;
  2674. if(mode() == EVAL_MODE) {
  2675. check(EXPR_TUPLE(self));
  2676. Ctx__s_emit_top(ctx());
  2677. consume(TK_EOF);
  2678. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  2679. check(pop_context(self));
  2680. return NULL;
  2681. }
  2682. while(!match(TK_EOF)) {
  2683. check(compile_stmt(self));
  2684. match_newlines();
  2685. }
  2686. check(pop_context(self));
  2687. return NULL;
  2688. }
  2689. Error* pk_compile(SourceData_ src, CodeObject* out) {
  2690. Token* tokens;
  2691. int tokens_length;
  2692. Error* err = Lexer__process(src, &tokens, &tokens_length);
  2693. if(err) return err;
  2694. #if 0
  2695. Token* data = (Token*)tokens.data;
  2696. printf("%s\n", src->filename->data);
  2697. for(int i = 0; i < tokens.length; i++) {
  2698. Token* t = data + i;
  2699. c11_string* tmp = c11_string__new2(t->start, t->length);
  2700. if(t->value.index == TokenValue_STR) {
  2701. const char* value_str = t->value._str->data;
  2702. printf("[%d] %s: %s (value._str=%s)\n",
  2703. t->line,
  2704. TokenSymbols[t->type],
  2705. tmp->data,
  2706. value_str);
  2707. } else {
  2708. printf("[%d] %s: %s\n", t->line, TokenSymbols[t->type], tmp->data);
  2709. }
  2710. c11_string__delete(tmp);
  2711. }
  2712. #endif
  2713. Compiler compiler;
  2714. Compiler__ctor(&compiler, src, tokens, tokens_length);
  2715. CodeObject__ctor(out, src, c11_string__sv(src->filename));
  2716. err = Compiler__compile(&compiler, out);
  2717. if(err) {
  2718. // dispose the code object if error occurs
  2719. CodeObject__dtor(out);
  2720. }
  2721. Compiler__dtor(&compiler);
  2722. return err;
  2723. }
  2724. // clang-format off
  2725. const static PrattRule rules[TK__COUNT__] = {
  2726. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  2727. [TK_DOT] = { NULL, exprAttrib, PREC_PRIMARY },
  2728. [TK_LPAREN] = { exprGroup, exprCall, PREC_PRIMARY },
  2729. [TK_LBRACKET] = { exprList, exprSubscr, PREC_PRIMARY },
  2730. [TK_MOD] = { NULL, exprBinaryOp, PREC_FACTOR },
  2731. [TK_ADD] = { NULL, exprBinaryOp, PREC_TERM },
  2732. [TK_SUB] = { exprUnaryOp, exprBinaryOp, PREC_TERM },
  2733. [TK_MUL] = { exprUnaryOp, exprBinaryOp, PREC_FACTOR },
  2734. [TK_INVERT] = { exprUnaryOp, NULL, PREC_UNARY },
  2735. [TK_DIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  2736. [TK_FLOORDIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  2737. [TK_POW] = { exprUnaryOp, exprBinaryOp, PREC_EXPONENT },
  2738. [TK_GT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2739. [TK_LT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2740. [TK_EQ] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2741. [TK_NE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2742. [TK_GE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2743. [TK_LE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2744. [TK_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2745. [TK_IS] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2746. [TK_LSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  2747. [TK_RSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  2748. [TK_AND] = { NULL, exprBinaryOp, PREC_BITWISE_AND },
  2749. [TK_OR] = { NULL, exprBinaryOp, PREC_BITWISE_OR },
  2750. [TK_XOR] = { NULL, exprBinaryOp, PREC_BITWISE_XOR },
  2751. [TK_DECORATOR] = { NULL, exprBinaryOp, PREC_FACTOR },
  2752. [TK_IF] = { NULL, exprTernary, PREC_TERNARY },
  2753. [TK_NOT_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2754. [TK_IS_NOT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2755. [TK_AND_KW ] = { NULL, exprAnd, PREC_LOGICAL_AND },
  2756. [TK_OR_KW] = { NULL, exprOr, PREC_LOGICAL_OR },
  2757. [TK_NOT_KW] = { exprNot, NULL, PREC_LOGICAL_NOT },
  2758. [TK_WALRUS] = { NULL, exprWalrus, PREC_NAMED_EXPR },
  2759. [TK_TRUE] = { exprLiteral0 },
  2760. [TK_FALSE] = { exprLiteral0 },
  2761. [TK_NONE] = { exprLiteral0 },
  2762. [TK_DOTDOTDOT] = { exprLiteral0 },
  2763. [TK_LAMBDA] = { exprLambda, },
  2764. [TK_ID] = { exprName, },
  2765. [TK_NUM] = { exprLiteral, },
  2766. [TK_STR] = { exprLiteral, },
  2767. [TK_FSTR_BEGIN] = { exprFString, },
  2768. [TK_IMAG] = { exprImag, },
  2769. [TK_BYTES] = { exprBytes, },
  2770. [TK_LBRACE] = { exprMap },
  2771. [TK_COLON] = { exprSlice0, exprSlice1, PREC_PRIMARY }
  2772. };
  2773. // clang-format on
  2774. #undef vtcall
  2775. #undef vtemit_
  2776. #undef vtemit_del
  2777. #undef vtemit_store
  2778. #undef vtemit_inplace
  2779. #undef vtemit_istore
  2780. #undef vtdelete
  2781. #undef EXPR_COMMON_HEADER
  2782. #undef is_compare_expr
  2783. #undef tk
  2784. #undef prev
  2785. #undef curr
  2786. #undef next
  2787. #undef advance
  2788. #undef mode
  2789. #undef ctx
  2790. #undef match_newlines
  2791. #undef consume
  2792. #undef consume_end_stmt
  2793. #undef check
  2794. #undef match