compiler.c 102 KB

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