compiler.c 93 KB

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