compiler.c 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084
  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. int path_index = Ctx__add_const_string(ctx(), c11_string__sv(path));
  2294. c11_string__delete(path);
  2295. NameScope scope = name_scope(self);
  2296. Ctx__emit_(ctx(), OP_IMPORT_PATH, path_index, prev()->line);
  2297. // [module <path>]
  2298. if(!has_sub_cpnt) {
  2299. if(match(TK_AS)) {
  2300. // import a as x
  2301. consume(TK_ID);
  2302. name = Token__sv(prev());
  2303. } else {
  2304. // import a
  2305. }
  2306. } else {
  2307. if(match(TK_AS)) {
  2308. // import a.b as x
  2309. consume(TK_ID);
  2310. name = Token__sv(prev());
  2311. } else {
  2312. // import a.b
  2313. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2314. int index = Ctx__add_const_string(ctx(), name);
  2315. Ctx__emit_(ctx(), OP_IMPORT_PATH, index, BC_KEEPLINE);
  2316. }
  2317. }
  2318. Ctx__emit_store_name(ctx(), scope, py_namev(name), BC_KEEPLINE);
  2319. } while(match(TK_COMMA));
  2320. consume_end_stmt();
  2321. return NULL;
  2322. }
  2323. // from a import b [as c], d [as e]
  2324. // from a.b import c [as d]
  2325. // from . import a [as b]
  2326. // from .a import b [as c]
  2327. // from ..a import b [as c]
  2328. // from .a.b import c [as d]
  2329. // from xxx import *
  2330. static Error* compile_from_import(Compiler* self, c11_sbuf* buf) {
  2331. int dots = 0;
  2332. while(true) {
  2333. switch(curr()->type) {
  2334. case TK_DOT: dots += 1; break;
  2335. case TK_DOTDOT: dots += 2; break;
  2336. case TK_DOTDOTDOT: dots += 3; break;
  2337. default: goto __EAT_DOTS_END;
  2338. }
  2339. advance();
  2340. }
  2341. __EAT_DOTS_END:
  2342. for(int i = 0; i < dots; i++) {
  2343. c11_sbuf__write_char(buf, '.');
  2344. }
  2345. if(dots > 0) {
  2346. // @id is optional if dots > 0
  2347. if(match(TK_ID)) {
  2348. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2349. while(match(TK_DOT)) {
  2350. consume(TK_ID);
  2351. c11_sbuf__write_char(buf, '.');
  2352. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2353. }
  2354. }
  2355. } else {
  2356. // @id is required if dots == 0
  2357. consume(TK_ID);
  2358. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2359. while(match(TK_DOT)) {
  2360. consume(TK_ID);
  2361. c11_sbuf__write_char(buf, '.');
  2362. c11_sbuf__write_sv(buf, Token__sv(prev()));
  2363. }
  2364. }
  2365. c11_string* path = c11_sbuf__submit(buf);
  2366. Ctx__emit_(ctx(),
  2367. OP_IMPORT_PATH,
  2368. Ctx__add_const_string(ctx(), c11_string__sv(path)),
  2369. prev()->line);
  2370. c11_string__delete(path);
  2371. consume(TK_IMPORT);
  2372. if(match(TK_MUL)) {
  2373. if(name_scope(self) != NAME_GLOBAL)
  2374. return SyntaxError(self, "from <module> import * can only be used in global scope");
  2375. // pop the module and import __all__
  2376. Ctx__emit_(ctx(), OP_POP_IMPORT_STAR, BC_NOARG, prev()->line);
  2377. consume_end_stmt();
  2378. return NULL;
  2379. }
  2380. bool has_bracket = match(TK_LPAREN);
  2381. do {
  2382. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  2383. consume(TK_ID);
  2384. c11_sv name = Token__sv(prev());
  2385. Ctx__emit_(ctx(), OP_LOAD_ATTR, Ctx__add_name(ctx(), py_namev(name)), prev()->line);
  2386. if(match(TK_AS)) {
  2387. consume(TK_ID);
  2388. name = Token__sv(prev());
  2389. }
  2390. Ctx__emit_store_name(ctx(), name_scope(self), py_namev(name), prev()->line);
  2391. } while(match(TK_COMMA));
  2392. if(has_bracket) { consume(TK_RPAREN); }
  2393. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2394. consume_end_stmt();
  2395. return NULL;
  2396. }
  2397. static Error* compile_try_except(Compiler* self) {
  2398. Error* err;
  2399. int patches[8];
  2400. int patches_length = 0;
  2401. Ctx__enter_block(ctx(), CodeBlockType_TRY);
  2402. Ctx__emit_(ctx(), OP_BEGIN_TRY, BC_NOARG, prev()->line);
  2403. check(compile_block_body(self));
  2404. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  2405. // https://docs.python.org/3/reference/compound_stmts.html#finally-clause
  2406. /* If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed,
  2407. * including any except and else clauses. If an exception occurs in any of the clauses and is
  2408. * not handled, the exception is temporarily saved. The finally clause is executed. If there is
  2409. * a saved exception it is re-raised at the end of the finally clause. If the finally clause
  2410. * raises another exception, the saved exception is set as the context of the new exception. If
  2411. * the finally clause executes a return, break or continue statement, the saved exception is
  2412. * discarded.
  2413. */
  2414. // known issue:
  2415. // A return, break, continue in try/except block will make the finally block not executed
  2416. bool has_finally = curr()->type == TK_FINALLY;
  2417. if(has_finally) return SyntaxError(self, "finally clause is not supported yet");
  2418. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  2419. Ctx__exit_block(ctx());
  2420. do {
  2421. if(patches_length == 8) {
  2422. return SyntaxError(self, "maximum number of except clauses reached");
  2423. }
  2424. py_Name as_name = 0;
  2425. consume(TK_EXCEPT);
  2426. if(is_expression(self, false)) {
  2427. // except <expr>:
  2428. check(EXPR(self));
  2429. Ctx__s_emit_top(ctx());
  2430. Ctx__emit_(ctx(), OP_EXCEPTION_MATCH, BC_NOARG, prev()->line);
  2431. if(match(TK_AS)) {
  2432. // except <expr> as <name>:
  2433. consume(TK_ID);
  2434. as_name = py_namev(Token__sv(prev()));
  2435. }
  2436. } else {
  2437. // except:
  2438. Ctx__emit_(ctx(), OP_LOAD_TRUE, BC_NOARG, BC_KEEPLINE);
  2439. }
  2440. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  2441. // on match
  2442. Ctx__emit_(ctx(), OP_HANDLE_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  2443. if(as_name) {
  2444. Ctx__emit_(ctx(), OP_PUSH_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  2445. Ctx__emit_store_name(ctx(), name_scope(self), as_name, BC_KEEPLINE);
  2446. }
  2447. Ctx__enter_block(ctx(), CodeBlockType_EXCEPT);
  2448. check(compile_block_body(self));
  2449. Ctx__exit_block(ctx());
  2450. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  2451. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  2452. Ctx__patch_jump(ctx(), patch);
  2453. } while(curr()->type == TK_EXCEPT);
  2454. // no match, re-raise
  2455. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, BC_KEEPLINE);
  2456. // match one & handled, jump to the end
  2457. for(int i = 0; i < patches_length; i++) {
  2458. Ctx__patch_jump(ctx(), patches[i]);
  2459. }
  2460. if(match(TK_FINALLY)) return SyntaxError(self, "finally clause is not supported yet");
  2461. return NULL;
  2462. }
  2463. static Error* compile_stmt(Compiler* self) {
  2464. Error* err;
  2465. if(match(TK_CLASS)) {
  2466. check(compile_class(self, 0));
  2467. return NULL;
  2468. }
  2469. advance();
  2470. int kw_line = prev()->line; // backup line number
  2471. switch(prev()->type) {
  2472. case TK_BREAK: {
  2473. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, true);
  2474. if(curr_loop_block < 0) return SyntaxError(self, "'break' outside loop");
  2475. Ctx__emit_(ctx(), OP_LOOP_BREAK, curr_loop_block, kw_line);
  2476. consume_end_stmt();
  2477. break;
  2478. }
  2479. case TK_CONTINUE: {
  2480. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, false);
  2481. if(curr_loop_block < 0) return SyntaxError(self, "'continue' not properly in loop");
  2482. Ctx__emit_(ctx(), OP_LOOP_CONTINUE, curr_loop_block, kw_line);
  2483. consume_end_stmt();
  2484. break;
  2485. }
  2486. case TK_YIELD:
  2487. if(self->contexts.length <= 1) return SyntaxError(self, "'yield' outside function");
  2488. if(match_end_stmt(self)) {
  2489. Ctx__emit_(ctx(), OP_YIELD_VALUE, 1, kw_line);
  2490. } else {
  2491. check(EXPR_TUPLE(self));
  2492. Ctx__s_emit_top(ctx());
  2493. Ctx__emit_(ctx(), OP_YIELD_VALUE, BC_NOARG, kw_line);
  2494. consume_end_stmt();
  2495. }
  2496. break;
  2497. case TK_YIELD_FROM:
  2498. check(compile_yield_from(self, kw_line));
  2499. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, kw_line);
  2500. consume_end_stmt();
  2501. break;
  2502. case TK_RETURN:
  2503. if(self->contexts.length <= 1) return SyntaxError(self, "'return' outside function");
  2504. if(match_end_stmt(self)) {
  2505. Ctx__emit_(ctx(), OP_RETURN_VALUE, 1, kw_line);
  2506. } else {
  2507. check(EXPR_TUPLE(self));
  2508. Ctx__s_emit_top(ctx());
  2509. consume_end_stmt();
  2510. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, kw_line);
  2511. }
  2512. break;
  2513. /*************************************************/
  2514. case TK_IF: check(compile_if_stmt(self)); break;
  2515. case TK_MATCH: {
  2516. c11_vector patches;
  2517. c11_vector__ctor(&patches, sizeof(int));
  2518. check(compile_match_case(self, &patches));
  2519. c11_vector__dtor(&patches);
  2520. break;
  2521. }
  2522. case TK_WHILE: check(compile_while_loop(self)); break;
  2523. case TK_FOR: check(compile_for_loop(self)); break;
  2524. case TK_IMPORT: {
  2525. c11_sbuf buf;
  2526. c11_sbuf__ctor(&buf);
  2527. err = compile_normal_import(self, &buf);
  2528. c11_sbuf__dtor(&buf);
  2529. if(err) return err;
  2530. break;
  2531. }
  2532. case TK_FROM: {
  2533. c11_sbuf buf;
  2534. c11_sbuf__ctor(&buf);
  2535. err = compile_from_import(self, &buf);
  2536. c11_sbuf__dtor(&buf);
  2537. if(err) return err;
  2538. break;
  2539. }
  2540. case TK_DEF: check(compile_function(self, 0)); break;
  2541. case TK_DECORATOR: check(compile_decorated(self)); break;
  2542. case TK_TRY: check(compile_try_except(self)); break;
  2543. case TK_PASS: consume_end_stmt(); break;
  2544. /*************************************************/
  2545. case TK_ASSERT: {
  2546. check(EXPR(self)); // condition
  2547. Ctx__s_emit_top(ctx());
  2548. int index = Ctx__emit_(ctx(), OP_POP_JUMP_IF_TRUE, BC_NOARG, kw_line);
  2549. int has_msg = 0;
  2550. if(match(TK_COMMA)) {
  2551. check(EXPR(self)); // message
  2552. Ctx__s_emit_top(ctx());
  2553. has_msg = 1;
  2554. }
  2555. Ctx__emit_(ctx(), OP_RAISE_ASSERT, has_msg, kw_line);
  2556. Ctx__patch_jump(ctx(), index);
  2557. consume_end_stmt();
  2558. break;
  2559. }
  2560. case TK_GLOBAL:
  2561. do {
  2562. consume(TK_ID);
  2563. py_Name name = py_namev(Token__sv(prev()));
  2564. c11_smallmap_n2d__set(&ctx()->global_names, name, 0);
  2565. } while(match(TK_COMMA));
  2566. consume_end_stmt();
  2567. break;
  2568. case TK_RAISE: {
  2569. if(is_expression(self, false)) {
  2570. check(EXPR(self));
  2571. Ctx__s_emit_top(ctx());
  2572. Ctx__emit_(ctx(), OP_RAISE, BC_NOARG, kw_line);
  2573. } else {
  2574. int iblock = ctx()->curr_iblock;
  2575. CodeBlock* blocks = (CodeBlock*)ctx()->co->blocks.data;
  2576. if(blocks[iblock].type != CodeBlockType_EXCEPT) {
  2577. return SyntaxError(self,
  2578. "raise without exception is only allowed in except block");
  2579. }
  2580. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, kw_line);
  2581. }
  2582. consume_end_stmt();
  2583. } break;
  2584. case TK_DEL: {
  2585. check(EXPR_TUPLE(self));
  2586. Expr* e = Ctx__s_top(ctx());
  2587. if(!vtemit_del(e, ctx())) return SyntaxError(self, "invalid syntax");
  2588. Ctx__s_pop(ctx());
  2589. consume_end_stmt();
  2590. } break;
  2591. case TK_WITH: {
  2592. check(EXPR(self)); // [ <expr> ]
  2593. Ctx__s_emit_top(ctx());
  2594. Ctx__enter_block(ctx(), CodeBlockType_WITH);
  2595. NameExpr* as_name = NULL;
  2596. if(match(TK_AS)) {
  2597. consume(TK_ID);
  2598. py_Name name = py_namev(Token__sv(prev()));
  2599. as_name = NameExpr__new(prev()->line, name, name_scope(self));
  2600. }
  2601. Ctx__emit_(ctx(), OP_WITH_ENTER, BC_NOARG, prev()->line);
  2602. // [ <expr> <expr>.__enter__() ]
  2603. if(as_name) {
  2604. bool ok = vtemit_store((Expr*)as_name, ctx());
  2605. vtdelete((Expr*)as_name);
  2606. if(!ok) return SyntaxError(self, "invalid syntax");
  2607. } else {
  2608. // discard `__enter__()`'s return value
  2609. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2610. }
  2611. check(compile_block_body(self));
  2612. Ctx__emit_(ctx(), OP_WITH_EXIT, BC_NOARG, prev()->line);
  2613. Ctx__exit_block(ctx());
  2614. } break;
  2615. /*************************************************/
  2616. // handle dangling expression or assignment
  2617. default: {
  2618. // do revert since we have pre-called advance() at the beginning
  2619. --self->i;
  2620. check(EXPR_TUPLE(self));
  2621. bool is_typed_name = false; // e.g. x: int
  2622. // eat variable's type hint if it is a single name
  2623. const ExprVt* top_vt = Ctx__s_top(ctx())->vt;
  2624. if(top_vt->is_name || top_vt->is_attrib) {
  2625. if(match(TK_COLON)) {
  2626. c11_sv type_hint;
  2627. check(consume_type_hints_sv(self, &type_hint));
  2628. is_typed_name = true;
  2629. if(ctx()->is_compiling_class && top_vt->is_name) {
  2630. NameExpr* ne = (NameExpr*)Ctx__s_top(ctx());
  2631. int index = Ctx__add_const_string(ctx(), type_hint);
  2632. Ctx__emit_(ctx(), OP_LOAD_CONST, index, BC_KEEPLINE);
  2633. Ctx__emit_(ctx(),
  2634. OP_ADD_CLASS_ANNOTATION,
  2635. Ctx__add_name(ctx(), ne->name),
  2636. BC_KEEPLINE);
  2637. }
  2638. }
  2639. }
  2640. bool is_assign = false;
  2641. check(try_compile_assignment(self, &is_assign));
  2642. if(!is_assign) {
  2643. if(Ctx__s_size(ctx()) > 0 && Ctx__s_top(ctx())->vt->is_starred) {
  2644. return SyntaxError(self, "can't use starred expression here");
  2645. }
  2646. if(!is_typed_name) {
  2647. Ctx__s_emit_top(ctx());
  2648. if((mode() == SINGLE_MODE) && name_scope(self) == NAME_GLOBAL) {
  2649. Ctx__emit_(ctx(), OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  2650. } else {
  2651. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  2652. }
  2653. } else {
  2654. Ctx__s_pop(ctx());
  2655. }
  2656. }
  2657. consume_end_stmt();
  2658. break;
  2659. }
  2660. }
  2661. return NULL;
  2662. }
  2663. /////////////////////////////////////////////////////////////////
  2664. Error* Compiler__compile(Compiler* self, CodeObject* out) {
  2665. // make sure it is the first time to compile
  2666. assert(self->i == 0);
  2667. // make sure the first token is @sof
  2668. assert(tk(0)->type == TK_SOF);
  2669. push_global_context(self, out);
  2670. advance(); // skip @sof, so prev() is always valid
  2671. match_newlines(); // skip possible leading '\n'
  2672. Error* err;
  2673. if(mode() == EVAL_MODE) {
  2674. check(EXPR_TUPLE(self));
  2675. Ctx__s_emit_top(ctx());
  2676. consume(TK_EOF);
  2677. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  2678. check(pop_context(self));
  2679. return NULL;
  2680. }
  2681. while(!match(TK_EOF)) {
  2682. check(compile_stmt(self));
  2683. match_newlines();
  2684. }
  2685. check(pop_context(self));
  2686. return NULL;
  2687. }
  2688. Error* pk_compile(SourceData_ src, CodeObject* out) {
  2689. Token* tokens;
  2690. int tokens_length;
  2691. Error* err = Lexer__process(src, &tokens, &tokens_length);
  2692. if(err) return err;
  2693. #if 0
  2694. Token* data = (Token*)tokens.data;
  2695. printf("%s\n", src->filename->data);
  2696. for(int i = 0; i < tokens.length; i++) {
  2697. Token* t = data + i;
  2698. c11_string* tmp = c11_string__new2(t->start, t->length);
  2699. if(t->value.index == TokenValue_STR) {
  2700. const char* value_str = t->value._str->data;
  2701. printf("[%d] %s: %s (value._str=%s)\n",
  2702. t->line,
  2703. TokenSymbols[t->type],
  2704. tmp->data,
  2705. value_str);
  2706. } else {
  2707. printf("[%d] %s: %s\n", t->line, TokenSymbols[t->type], tmp->data);
  2708. }
  2709. c11_string__delete(tmp);
  2710. }
  2711. #endif
  2712. Compiler compiler;
  2713. Compiler__ctor(&compiler, src, tokens, tokens_length);
  2714. CodeObject__ctor(out, src, c11_string__sv(src->filename));
  2715. err = Compiler__compile(&compiler, out);
  2716. if(err) {
  2717. // dispose the code object if error occurs
  2718. CodeObject__dtor(out);
  2719. }
  2720. Compiler__dtor(&compiler);
  2721. return err;
  2722. }
  2723. // clang-format off
  2724. const static PrattRule rules[TK__COUNT__] = {
  2725. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  2726. [TK_DOT] = { NULL, exprAttrib, PREC_PRIMARY },
  2727. [TK_LPAREN] = { exprGroup, exprCall, PREC_PRIMARY },
  2728. [TK_LBRACKET] = { exprList, exprSubscr, PREC_PRIMARY },
  2729. [TK_MOD] = { NULL, exprBinaryOp, PREC_FACTOR },
  2730. [TK_ADD] = { NULL, exprBinaryOp, PREC_TERM },
  2731. [TK_SUB] = { exprUnaryOp, exprBinaryOp, PREC_TERM },
  2732. [TK_MUL] = { exprUnaryOp, exprBinaryOp, PREC_FACTOR },
  2733. [TK_INVERT] = { exprUnaryOp, NULL, PREC_UNARY },
  2734. [TK_DIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  2735. [TK_FLOORDIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  2736. [TK_POW] = { exprUnaryOp, exprBinaryOp, PREC_EXPONENT },
  2737. [TK_GT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2738. [TK_LT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2739. [TK_EQ] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2740. [TK_NE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2741. [TK_GE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2742. [TK_LE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2743. [TK_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2744. [TK_IS] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2745. [TK_LSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  2746. [TK_RSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  2747. [TK_AND] = { NULL, exprBinaryOp, PREC_BITWISE_AND },
  2748. [TK_OR] = { NULL, exprBinaryOp, PREC_BITWISE_OR },
  2749. [TK_XOR] = { NULL, exprBinaryOp, PREC_BITWISE_XOR },
  2750. [TK_DECORATOR] = { NULL, exprBinaryOp, PREC_FACTOR },
  2751. [TK_IF] = { NULL, exprTernary, PREC_TERNARY },
  2752. [TK_NOT_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2753. [TK_IS_NOT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  2754. [TK_AND_KW ] = { NULL, exprAnd, PREC_LOGICAL_AND },
  2755. [TK_OR_KW] = { NULL, exprOr, PREC_LOGICAL_OR },
  2756. [TK_NOT_KW] = { exprNot, NULL, PREC_LOGICAL_NOT },
  2757. [TK_WALRUS] = { NULL, exprWalrus, PREC_NAMED_EXPR },
  2758. [TK_TRUE] = { exprLiteral0 },
  2759. [TK_FALSE] = { exprLiteral0 },
  2760. [TK_NONE] = { exprLiteral0 },
  2761. [TK_DOTDOTDOT] = { exprLiteral0 },
  2762. [TK_LAMBDA] = { exprLambda, },
  2763. [TK_ID] = { exprName, },
  2764. [TK_NUM] = { exprLiteral, },
  2765. [TK_STR] = { exprLiteral, },
  2766. [TK_FSTR_BEGIN] = { exprFString, },
  2767. [TK_IMAG] = { exprImag, },
  2768. [TK_BYTES] = { exprBytes, },
  2769. [TK_LBRACE] = { exprMap },
  2770. [TK_COLON] = { exprSlice0, exprSlice1, PREC_PRIMARY }
  2771. };
  2772. // clang-format on
  2773. #undef vtcall
  2774. #undef vtemit_
  2775. #undef vtemit_del
  2776. #undef vtemit_store
  2777. #undef vtemit_inplace
  2778. #undef vtemit_istore
  2779. #undef vtdelete
  2780. #undef EXPR_COMMON_HEADER
  2781. #undef is_compare_expr
  2782. #undef tk
  2783. #undef prev
  2784. #undef curr
  2785. #undef next
  2786. #undef advance
  2787. #undef mode
  2788. #undef ctx
  2789. #undef match_newlines
  2790. #undef consume
  2791. #undef consume_end_stmt
  2792. #undef check
  2793. #undef match