compiler.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. #include "pocketpy/compiler/compiler.hpp"
  2. #include "pocketpy/common/config.h"
  3. #include "pocketpy/compiler/expr.hpp"
  4. #include "pocketpy/interpreter/vm.hpp"
  5. #include "pocketpy/objects/codeobject.hpp"
  6. #include <cstdarg>
  7. namespace pkpy {
  8. #define consume(expected) if(!match(expected)) return SyntaxError("expected '%s', got '%s'", pk_TokenSymbols[expected], pk_TokenSymbols[curr().type]);
  9. #define consume_end_stmt() if(!match_end_stmt()) return SyntaxError("expected statement end")
  10. #define check_newlines_repl() { bool __nml; match_newlines(&__nml); if(__nml) return NeedMoreLines(); }
  11. #define check(B) if((err = B)) return err
  12. PrattRule Compiler::rules[TK__COUNT__];
  13. NameScope Compiler::name_scope() const noexcept{
  14. auto s = contexts.size() > 1 ? NAME_LOCAL : NAME_GLOBAL;
  15. if(unknown_global_scope && s == NAME_GLOBAL) s = NAME_GLOBAL_UNKNOWN;
  16. return s;
  17. }
  18. CodeObject* Compiler::push_global_context() noexcept{
  19. CodeObject* co = CodeObject__new(lexer.src, py_Str__sv(&lexer.src->filename));
  20. co->start_line = __i == 0 ? 1 : prev().line;
  21. contexts.push_back(CodeEmitContext(vm, co, contexts.size()));
  22. return co;
  23. }
  24. FuncDecl_ Compiler::push_f_context(c11_string name, int* out_index) noexcept{
  25. FuncDecl_ decl = FuncDecl__rcnew(lexer.src, name);
  26. decl->code->start_line = __i == 0 ? 1 : prev().line;
  27. decl->nested = name_scope() == NAME_LOCAL;
  28. // add_func_decl
  29. CodeEmitContext* ctx = &contexts.back();
  30. c11_vector__push(FuncDecl_, &ctx->co->func_decls, decl);
  31. *out_index = ctx->co->func_decls.count - 1;
  32. // push new context
  33. contexts.push_back(CodeEmitContext(vm, decl->code, contexts.size()));
  34. contexts.back().func = decl;
  35. return decl;
  36. }
  37. Error* Compiler::pop_context() noexcept{
  38. assert(ctx()->s_size() == 0);
  39. // add a `return None` in the end as a guard
  40. // previously, we only do this if the last opcode is not a return
  41. // however, this is buggy...since there may be a jump to the end (out of bound) even if the last opcode is a return
  42. ctx()->emit_(OP_RETURN_VALUE, 1, BC_KEEPLINE, true);
  43. // find the last valid token
  44. int j = __i - 1;
  45. while(tk(j).type == TK_EOL || tk(j).type == TK_DEDENT || tk(j).type == TK_EOF)
  46. j--;
  47. ctx()->co->end_line = tk(j).line;
  48. // some check here
  49. auto& codes = ctx()->co->codes;
  50. if(ctx()->co->nlocals > PK_MAX_CO_VARNAMES) {
  51. return SyntaxError("maximum number of local variables exceeded");
  52. }
  53. if(ctx()->co->consts.count > 65530) {
  54. return SyntaxError("maximum number of constants exceeded");
  55. }
  56. // pre-compute LOOP_BREAK and LOOP_CONTINUE
  57. for(int i = 0; i < codes.count; i++) {
  58. Bytecode* bc = c11__at(Bytecode, &codes, i);
  59. if(bc->op == OP_LOOP_CONTINUE) {
  60. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  61. Bytecode__set_signed_arg(bc, block->start - i);
  62. } else if(bc->op == OP_LOOP_BREAK) {
  63. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  64. Bytecode__set_signed_arg(bc, (block->end2 != -1 ? block->end2 : block->end) - i);
  65. }
  66. }
  67. // pre-compute func->is_simple
  68. FuncDecl* func = contexts.back().func;
  69. if(func) {
  70. // check generator
  71. c11_vector__foreach(Bytecode, &func->code->codes, bc) {
  72. if(bc->op == OP_YIELD_VALUE || bc->op == OP_FOR_ITER_YIELD_VALUE) {
  73. func->type = FuncType_GENERATOR;
  74. c11_vector__foreach(Bytecode, &func->code->codes, bc) {
  75. if(bc->op == OP_RETURN_VALUE && bc->arg == BC_NOARG) {
  76. return SyntaxError("'return' with argument inside generator function");
  77. }
  78. }
  79. break;
  80. }
  81. }
  82. if(func->type == FuncType_UNSET) {
  83. bool is_simple = true;
  84. if(func->kwargs.count > 0) is_simple = false;
  85. if(func->starred_arg >= 0) is_simple = false;
  86. if(func->starred_kwarg >= 0) is_simple = false;
  87. if(is_simple) {
  88. func->type = FuncType_SIMPLE;
  89. bool is_empty = false;
  90. if(func->code->codes.count == 1) {
  91. Bytecode bc = c11__getitem(Bytecode, &func->code->codes, 0);
  92. if(bc.op == OP_RETURN_VALUE && bc.arg == 1) {
  93. is_empty = true;
  94. }
  95. }
  96. if(is_empty) func->type = FuncType_EMPTY;
  97. } else
  98. func->type = FuncType_NORMAL;
  99. }
  100. assert(func->type != FuncType_UNSET);
  101. }
  102. contexts.back().s_clean();
  103. contexts.pop_back();
  104. return NULL;
  105. }
  106. void Compiler::init_pratt_rules() noexcept{
  107. static bool initialized = false;
  108. if(initialized) return;
  109. initialized = true;
  110. // clang-format off
  111. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  112. #define PK_METHOD(name) &Compiler::name
  113. #define PK_NO_INFIX nullptr, PREC_LOWEST
  114. for(int i = 0; i < TK__COUNT__; i++) rules[i] = { nullptr, PK_NO_INFIX };
  115. rules[TK_DOT] = { nullptr, PK_METHOD(exprAttrib), PREC_PRIMARY };
  116. rules[TK_LPAREN] = { PK_METHOD(exprGroup), PK_METHOD(exprCall), PREC_PRIMARY };
  117. rules[TK_LBRACKET] = { PK_METHOD(exprList), PK_METHOD(exprSubscr), PREC_PRIMARY };
  118. rules[TK_LBRACE] = { PK_METHOD(exprMap), PK_NO_INFIX };
  119. rules[TK_MOD] = { nullptr, PK_METHOD(exprBinaryOp), PREC_FACTOR };
  120. rules[TK_ADD] = { nullptr, PK_METHOD(exprBinaryOp), PREC_TERM };
  121. rules[TK_SUB] = { PK_METHOD(exprUnaryOp), PK_METHOD(exprBinaryOp), PREC_TERM };
  122. rules[TK_MUL] = { PK_METHOD(exprUnaryOp), PK_METHOD(exprBinaryOp), PREC_FACTOR };
  123. rules[TK_INVERT] = { PK_METHOD(exprUnaryOp), nullptr, PREC_UNARY };
  124. rules[TK_DIV] = { nullptr, PK_METHOD(exprBinaryOp), PREC_FACTOR };
  125. rules[TK_FLOORDIV] = { nullptr, PK_METHOD(exprBinaryOp), PREC_FACTOR };
  126. rules[TK_POW] = { PK_METHOD(exprUnaryOp), PK_METHOD(exprBinaryOp), PREC_EXPONENT };
  127. rules[TK_GT] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  128. rules[TK_LT] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  129. rules[TK_EQ] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  130. rules[TK_NE] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  131. rules[TK_GE] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  132. rules[TK_LE] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  133. rules[TK_IN] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  134. rules[TK_IS] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  135. rules[TK_LSHIFT] = { nullptr, PK_METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  136. rules[TK_RSHIFT] = { nullptr, PK_METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  137. rules[TK_AND] = { nullptr, PK_METHOD(exprBinaryOp), PREC_BITWISE_AND };
  138. rules[TK_OR] = { nullptr, PK_METHOD(exprBinaryOp), PREC_BITWISE_OR };
  139. rules[TK_XOR] = { nullptr, PK_METHOD(exprBinaryOp), PREC_BITWISE_XOR };
  140. rules[TK_DECORATOR] = { nullptr, PK_METHOD(exprBinaryOp), PREC_FACTOR };
  141. rules[TK_IF] = { nullptr, PK_METHOD(exprTernary), PREC_TERNARY };
  142. rules[TK_NOT_IN] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  143. rules[TK_IS_NOT] = { nullptr, PK_METHOD(exprBinaryOp), PREC_COMPARISION };
  144. rules[TK_AND_KW ] = { nullptr, PK_METHOD(exprAnd), PREC_LOGICAL_AND };
  145. rules[TK_OR_KW] = { nullptr, PK_METHOD(exprOr), PREC_LOGICAL_OR };
  146. rules[TK_NOT_KW] = { PK_METHOD(exprNot), nullptr, PREC_LOGICAL_NOT };
  147. rules[TK_TRUE] = { PK_METHOD(exprLiteral0), PK_NO_INFIX };
  148. rules[TK_FALSE] = { PK_METHOD(exprLiteral0), PK_NO_INFIX };
  149. rules[TK_NONE] = { PK_METHOD(exprLiteral0), PK_NO_INFIX };
  150. rules[TK_DOTDOTDOT] = { PK_METHOD(exprLiteral0), PK_NO_INFIX };
  151. rules[TK_LAMBDA] = { PK_METHOD(exprLambda), PK_NO_INFIX };
  152. rules[TK_ID] = { PK_METHOD(exprName), PK_NO_INFIX };
  153. rules[TK_NUM] = { PK_METHOD(exprLiteral), PK_NO_INFIX };
  154. rules[TK_STR] = { PK_METHOD(exprLiteral), PK_NO_INFIX };
  155. rules[TK_FSTR] = { PK_METHOD(exprFString), PK_NO_INFIX };
  156. rules[TK_LONG] = { PK_METHOD(exprLong), PK_NO_INFIX };
  157. rules[TK_IMAG] = { PK_METHOD(exprImag), PK_NO_INFIX };
  158. rules[TK_BYTES] = { PK_METHOD(exprBytes), PK_NO_INFIX };
  159. rules[TK_COLON] = { PK_METHOD(exprSlice0), PK_METHOD(exprSlice1), PREC_PRIMARY };
  160. #undef PK_METHOD
  161. #undef PK_NO_INFIX
  162. // clang-format on
  163. }
  164. bool Compiler::match(TokenIndex expected) noexcept{
  165. if(curr().type != expected) return false;
  166. advance();
  167. return true;
  168. }
  169. bool Compiler::match_newlines(bool* need_more_lines) noexcept{
  170. bool consumed = false;
  171. if(curr().type == TK_EOL) {
  172. while(curr().type == TK_EOL) advance();
  173. consumed = true;
  174. }
  175. if(need_more_lines) {
  176. *need_more_lines = (mode() == REPL_MODE && curr().type == TK_EOF);
  177. }
  178. return consumed;
  179. }
  180. bool Compiler::match_end_stmt() noexcept{
  181. if(match(TK_SEMICOLON)) {
  182. match_newlines();
  183. return true;
  184. }
  185. if(match_newlines() || curr().type == TK_EOF) return true;
  186. if(curr().type == TK_DEDENT) return true;
  187. return false;
  188. }
  189. Error* Compiler::EXPR_TUPLE(bool allow_slice) noexcept{
  190. Error* err;
  191. check(parse_expression(PREC_LOWEST + 1, allow_slice));
  192. if(!match(TK_COMMA)) return NULL;
  193. // tuple expression
  194. int count = 1;
  195. do {
  196. if(curr().brackets_level) check_newlines_repl()
  197. if(!is_expression(allow_slice)) break;
  198. check(parse_expression(PREC_LOWEST + 1, allow_slice));
  199. count += 1;
  200. if(curr().brackets_level) check_newlines_repl();
  201. } while(match(TK_COMMA));
  202. TupleExpr* e = make_expr<TupleExpr>(count);
  203. for(int i=count-1; i>=0; i--)
  204. e->items[i] = ctx()->s_popx();
  205. ctx()->s_push(e);
  206. return NULL;
  207. }
  208. Error* Compiler::EXPR_VARS() noexcept{
  209. int count = 0;
  210. do {
  211. consume(TK_ID);
  212. ctx()->s_push(make_expr<NameExpr>(prev().str(), name_scope()));
  213. count += 1;
  214. } while(match(TK_COMMA));
  215. if(count > 1){
  216. TupleExpr* e = make_expr<TupleExpr>(count);
  217. for(int i=count-1; i>=0; i--)
  218. e->items[i] = ctx()->s_popx();
  219. ctx()->s_push(e);
  220. }
  221. return NULL;
  222. }
  223. Error* Compiler::exprLiteral() noexcept{
  224. ctx()->s_push(make_expr<LiteralExpr>(prev().value));
  225. return NULL;
  226. }
  227. Error* Compiler::exprLong() noexcept{
  228. ctx()->s_push(make_expr<LongExpr>(prev().str()));
  229. return NULL;
  230. }
  231. Error* Compiler::exprImag() noexcept{
  232. ctx()->s_push(make_expr<ImagExpr>(std::get<f64>(prev().value)));
  233. return NULL;
  234. }
  235. Error* Compiler::exprBytes() noexcept{
  236. ctx()->s_push(make_expr<BytesExpr>(std::get<Str>(prev().value)));
  237. return NULL;
  238. }
  239. Error* Compiler::exprFString() noexcept{
  240. ctx()->s_push(make_expr<FStringExpr>(std::get<Str>(prev().value)));
  241. return NULL;
  242. }
  243. Error* Compiler::exprLambda() noexcept{
  244. Error* err;
  245. int decl_index;
  246. FuncDecl_ decl = push_f_context({"<lambda>", 8}, &decl_index);
  247. int line = prev().line; // backup line
  248. if(!match(TK_COLON)) {
  249. check(_compile_f_args(decl, false));
  250. consume(TK_COLON);
  251. }
  252. // https://github.com/pocketpy/pocketpy/issues/37
  253. check(parse_expression(PREC_LAMBDA + 1));
  254. ctx()->s_emit_top();
  255. ctx()->emit_(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  256. check(pop_context());
  257. LambdaExpr* e = make_expr<LambdaExpr>(decl_index);
  258. e->line = line;
  259. ctx()->s_push(e);
  260. return NULL;
  261. }
  262. Error* Compiler::exprOr() noexcept{
  263. int line = prev().line;
  264. Error* err;
  265. check(parse_expression(PREC_LOGICAL_OR + 1));
  266. auto e = make_expr<OrExpr>();
  267. e->line = line;
  268. e->rhs = ctx()->s_popx();
  269. e->lhs = ctx()->s_popx();
  270. ctx()->s_push(e);
  271. return NULL;
  272. }
  273. Error* Compiler::exprAnd() noexcept{
  274. int line = prev().line;
  275. Error* err;
  276. check(parse_expression(PREC_LOGICAL_AND + 1));
  277. auto e = make_expr<AndExpr>();
  278. e->line = line;
  279. e->rhs = ctx()->s_popx();
  280. e->lhs = ctx()->s_popx();
  281. ctx()->s_push(e);
  282. return NULL;
  283. }
  284. Error* Compiler::exprTernary() noexcept{
  285. // [true_expr]
  286. Error* err;
  287. int line = prev().line;
  288. check(parse_expression(PREC_TERNARY + 1)); // [true_expr, cond]
  289. consume(TK_ELSE);
  290. check(parse_expression(PREC_TERNARY + 1)); // [true_expr, cond, false_expr]
  291. auto e = make_expr<TernaryExpr>();
  292. e->line = line;
  293. e->false_expr = ctx()->s_popx();
  294. e->cond = ctx()->s_popx();
  295. e->true_expr = ctx()->s_popx();
  296. ctx()->s_push(e);
  297. return NULL;
  298. }
  299. Error* Compiler::exprBinaryOp() noexcept{
  300. Error* err;
  301. int line = prev().line;
  302. TokenIndex op = prev().type;
  303. check(parse_expression(rules[op].precedence + 1));
  304. BinaryExpr* e = make_expr<BinaryExpr>(op);
  305. e->line = line;
  306. e->rhs = ctx()->s_popx();
  307. e->lhs = ctx()->s_popx();
  308. ctx()->s_push(e);
  309. return NULL;
  310. }
  311. Error* Compiler::exprNot() noexcept{
  312. Error* err;
  313. check(parse_expression(PREC_LOGICAL_NOT + 1));
  314. NotExpr* e = make_expr<NotExpr>(ctx()->s_popx());
  315. ctx()->s_push(e);
  316. return NULL;
  317. }
  318. Error* Compiler::exprUnaryOp() noexcept{
  319. Error* err;
  320. TokenIndex op = prev().type;
  321. check(parse_expression(PREC_UNARY + 1));
  322. switch(op) {
  323. case TK_SUB: ctx()->s_push(make_expr<NegatedExpr>(ctx()->s_popx())); break;
  324. case TK_INVERT: ctx()->s_push(make_expr<InvertExpr>(ctx()->s_popx())); break;
  325. case TK_MUL: ctx()->s_push(make_expr<StarredExpr>(ctx()->s_popx(), 1)); break;
  326. case TK_POW: ctx()->s_push(make_expr<StarredExpr>(ctx()->s_popx(), 2)); break;
  327. default: assert(false);
  328. }
  329. return NULL;
  330. }
  331. Error* Compiler::exprGroup() noexcept{
  332. Error* err;
  333. check_newlines_repl()
  334. check(EXPR_TUPLE()); // () is just for change precedence
  335. check_newlines_repl()
  336. consume(TK_RPAREN);
  337. if(ctx()->s_top()->is_tuple()) return NULL;
  338. Expr* g = make_expr<GroupedExpr>(ctx()->s_popx());
  339. ctx()->s_push(g);
  340. return NULL;
  341. }
  342. Error* Compiler::consume_comp(Opcode op0, Opcode op1) noexcept{
  343. // [expr]
  344. Error* err;
  345. bool has_cond = false;
  346. check(EXPR_VARS()); // [expr, vars]
  347. consume(TK_IN);
  348. check(parse_expression(PREC_TERNARY + 1)); // [expr, vars, iter]
  349. check_newlines_repl()
  350. if(match(TK_IF)) {
  351. check(parse_expression(PREC_TERNARY + 1)); // [expr, vars, iter, cond]
  352. has_cond = true;
  353. }
  354. CompExpr* ce = make_expr<CompExpr>(op0, op1);
  355. if(has_cond) ce->cond = ctx()->s_popx();
  356. ce->iter = ctx()->s_popx();
  357. ce->vars = ctx()->s_popx();
  358. ce->expr = ctx()->s_popx();
  359. ctx()->s_push(ce);
  360. check_newlines_repl()
  361. return NULL;
  362. }
  363. Error* Compiler::exprList() noexcept{
  364. Error* err;
  365. int line = prev().line;
  366. int count = 0;
  367. do {
  368. check_newlines_repl()
  369. if(curr().type == TK_RBRACKET) break;
  370. check(EXPR()); count += 1;
  371. check_newlines_repl()
  372. if(count == 1 && match(TK_FOR)) {
  373. check(consume_comp(OP_BUILD_LIST, OP_LIST_APPEND));
  374. consume(TK_RBRACKET);
  375. return NULL;
  376. }
  377. check_newlines_repl()
  378. } while(match(TK_COMMA));
  379. consume(TK_RBRACKET);
  380. ListExpr* e = make_expr<ListExpr>(count);
  381. e->line = line; // override line
  382. for(int i=count-1; i>=0; i--)
  383. e->items[i] = ctx()->s_popx();
  384. ctx()->s_push(e);
  385. return NULL;
  386. }
  387. Error* Compiler::exprMap() noexcept{
  388. Error* err;
  389. bool parsing_dict = false; // {...} may be dict or set
  390. int count = 0;
  391. do {
  392. check_newlines_repl()
  393. if(curr().type == TK_RBRACE) break;
  394. check(EXPR()); // [key]
  395. int star_level = ctx()->s_top()->star_level();
  396. if(star_level == 2 || curr().type == TK_COLON) { parsing_dict = true; }
  397. if(parsing_dict) {
  398. if(star_level == 2) {
  399. DictItemExpr* dict_item = make_expr<DictItemExpr>();
  400. dict_item->key = NULL;
  401. dict_item->value = ctx()->s_popx();
  402. ctx()->s_push(dict_item);
  403. } else {
  404. consume(TK_COLON);
  405. check(EXPR());
  406. DictItemExpr* dict_item = make_expr<DictItemExpr>();
  407. dict_item->value = ctx()->s_popx();
  408. dict_item->key = ctx()->s_popx();
  409. ctx()->s_push(dict_item);
  410. }
  411. }
  412. count += 1;
  413. check_newlines_repl()
  414. if(count == 1 && match(TK_FOR)) {
  415. if(parsing_dict){
  416. check(consume_comp(OP_BUILD_DICT, OP_DICT_ADD));
  417. }else{
  418. check(consume_comp(OP_BUILD_SET, OP_SET_ADD));
  419. }
  420. consume(TK_RBRACE);
  421. return NULL;
  422. }
  423. check_newlines_repl()
  424. } while(match(TK_COMMA));
  425. consume(TK_RBRACE);
  426. SequenceExpr* se;
  427. if(count == 0 || parsing_dict) {
  428. se = make_expr<DictExpr>(count);
  429. } else {
  430. se = make_expr<SetExpr>(count);
  431. }
  432. for(int i=count-1; i>=0; i--)
  433. se->items[i] = ctx()->s_popx();
  434. ctx()->s_push(se);
  435. return NULL;
  436. }
  437. Error* Compiler::exprCall() noexcept{
  438. Error* err;
  439. CallExpr* e = make_expr<CallExpr>();
  440. e->callable = ctx()->s_popx();
  441. ctx()->s_push(e); // push onto the stack in advance
  442. do {
  443. check_newlines_repl()
  444. if(curr().type == TK_RPAREN) break;
  445. if(curr().type == TK_ID && next().type == TK_ASSIGN) {
  446. consume(TK_ID);
  447. StrName key(prev().sv());
  448. consume(TK_ASSIGN);
  449. check(EXPR());
  450. e->kwargs.push_back({key, ctx()->s_popx()});
  451. } else {
  452. check(EXPR());
  453. if(ctx()->s_top()->star_level() == 2) {
  454. // **kwargs
  455. e->kwargs.push_back({"**", ctx()->s_popx()});
  456. } else {
  457. // positional argument
  458. if(!e->kwargs.empty()) return SyntaxError("positional argument follows keyword argument");
  459. e->args.push_back(ctx()->s_popx());
  460. }
  461. }
  462. check_newlines_repl()
  463. } while(match(TK_COMMA));
  464. consume(TK_RPAREN);
  465. return NULL;
  466. }
  467. Error* Compiler::exprName() noexcept{
  468. StrName name(prev().sv());
  469. NameScope scope = name_scope();
  470. if(ctx()->global_names.contains(name)) { scope = NAME_GLOBAL; }
  471. ctx()->s_push(make_expr<NameExpr>(name, scope));
  472. return NULL;
  473. }
  474. Error* Compiler::exprAttrib() noexcept{
  475. consume(TK_ID);
  476. ctx()->s_push(make_expr<AttribExpr>(ctx()->s_popx(), StrName::get(prev().sv())));
  477. return NULL;
  478. }
  479. Error* Compiler::exprSlice0() noexcept{
  480. Error* err;
  481. SliceExpr* slice = make_expr<SliceExpr>();
  482. ctx()->s_push(slice); // push onto the stack in advance
  483. if(is_expression()) { // :<stop>
  484. check(EXPR());
  485. slice->stop = ctx()->s_popx();
  486. // try optional step
  487. if(match(TK_COLON)) { // :<stop>:<step>
  488. check(EXPR());
  489. slice->step = ctx()->s_popx();
  490. }
  491. } else if(match(TK_COLON)) {
  492. if(is_expression()) { // ::<step>
  493. check(EXPR());
  494. slice->step = ctx()->s_popx();
  495. } // else ::
  496. } // else :
  497. return NULL;
  498. }
  499. Error* Compiler::exprSlice1() noexcept{
  500. Error* err;
  501. SliceExpr* slice = make_expr<SliceExpr>();
  502. slice->start = ctx()->s_popx();
  503. ctx()->s_push(slice); // push onto the stack in advance
  504. if(is_expression()) { // <start>:<stop>
  505. check(EXPR());
  506. slice->stop = ctx()->s_popx();
  507. // try optional step
  508. if(match(TK_COLON)) { // <start>:<stop>:<step>
  509. check(EXPR());
  510. slice->step = ctx()->s_popx();
  511. }
  512. } else if(match(TK_COLON)) { // <start>::<step>
  513. check(EXPR());
  514. slice->step = ctx()->s_popx();
  515. } // else <start>:
  516. return NULL;
  517. }
  518. Error* Compiler::exprSubscr() noexcept{
  519. Error* err;
  520. int line = prev().line;
  521. check_newlines_repl()
  522. check(EXPR_TUPLE(true));
  523. check_newlines_repl()
  524. consume(TK_RBRACKET); // [lhs, rhs]
  525. SubscrExpr* e = make_expr<SubscrExpr>();
  526. e->line = line;
  527. e->rhs = ctx()->s_popx(); // [lhs]
  528. e->lhs = ctx()->s_popx(); // []
  529. ctx()->s_push(e);
  530. return NULL;
  531. }
  532. Error* Compiler::exprLiteral0() noexcept{
  533. ctx()->s_push(make_expr<Literal0Expr>(prev().type));
  534. return NULL;
  535. }
  536. Error* Compiler::compile_block_body(PrattCallback callback) noexcept{
  537. Error* err;
  538. if(!callback) callback = &Compiler::compile_stmt;
  539. consume(TK_COLON);
  540. if(curr().type != TK_EOL && curr().type != TK_EOF) {
  541. while(true) {
  542. check(compile_stmt());
  543. bool possible = curr().type != TK_EOL && curr().type != TK_EOF;
  544. if(prev().type != TK_SEMICOLON || !possible) break;
  545. }
  546. return NULL;
  547. }
  548. bool need_more_lines;
  549. bool consumed = match_newlines(&need_more_lines);
  550. if(need_more_lines) return NeedMoreLines();
  551. if(!consumed) return SyntaxError("expected a new line after ':'");
  552. consume(TK_INDENT);
  553. while(curr().type != TK_DEDENT) {
  554. match_newlines();
  555. check((this->*callback)());
  556. match_newlines();
  557. }
  558. consume(TK_DEDENT);
  559. return NULL;
  560. }
  561. // import a [as b]
  562. // import a [as b], c [as d]
  563. Error* Compiler::compile_normal_import() noexcept{
  564. do {
  565. consume(TK_ID);
  566. Str name = prev().str();
  567. ctx()->emit_(OP_IMPORT_PATH, ctx()->add_const_string(name.sv()), prev().line);
  568. if(match(TK_AS)) {
  569. consume(TK_ID);
  570. name = prev().str();
  571. }
  572. ctx()->emit_store_name(name_scope(), StrName(name), prev().line);
  573. } while(match(TK_COMMA));
  574. consume_end_stmt();
  575. return NULL;
  576. }
  577. // from a import b [as c], d [as e]
  578. // from a.b import c [as d]
  579. // from . import a [as b]
  580. // from .a import b [as c]
  581. // from ..a import b [as c]
  582. // from .a.b import c [as d]
  583. // from xxx import *
  584. Error* Compiler::compile_from_import() noexcept{
  585. int dots = 0;
  586. while(true) {
  587. switch(curr().type) {
  588. case TK_DOT: dots += 1; break;
  589. case TK_DOTDOT: dots += 2; break;
  590. case TK_DOTDOTDOT: dots += 3; break;
  591. default: goto __EAT_DOTS_END;
  592. }
  593. advance();
  594. }
  595. __EAT_DOTS_END:
  596. SStream ss;
  597. for(int i = 0; i < dots; i++)
  598. ss << '.';
  599. if(dots > 0) {
  600. // @id is optional if dots > 0
  601. if(match(TK_ID)) {
  602. ss << prev().sv();
  603. while(match(TK_DOT)) {
  604. consume(TK_ID);
  605. ss << "." << prev().sv();
  606. }
  607. }
  608. } else {
  609. // @id is required if dots == 0
  610. consume(TK_ID);
  611. ss << prev().sv();
  612. while(match(TK_DOT)) {
  613. consume(TK_ID);
  614. ss << "." << prev().sv();
  615. }
  616. }
  617. ctx()->emit_(OP_IMPORT_PATH, ctx()->add_const_string(ss.str().sv()), prev().line);
  618. consume(TK_IMPORT);
  619. if(match(TK_MUL)) {
  620. if(name_scope() != NAME_GLOBAL) return SyntaxError("from <module> import * can only be used in global scope");
  621. // pop the module and import __all__
  622. ctx()->emit_(OP_POP_IMPORT_STAR, BC_NOARG, prev().line);
  623. consume_end_stmt();
  624. return NULL;
  625. }
  626. do {
  627. ctx()->emit_(OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  628. consume(TK_ID);
  629. Str name = prev().str();
  630. ctx()->emit_(OP_LOAD_ATTR, StrName(name).index, prev().line);
  631. if(match(TK_AS)) {
  632. consume(TK_ID);
  633. name = prev().str();
  634. }
  635. ctx()->emit_store_name(name_scope(), StrName(name), prev().line);
  636. } while(match(TK_COMMA));
  637. ctx()->emit_(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  638. consume_end_stmt();
  639. return NULL;
  640. }
  641. bool Compiler::is_expression(bool allow_slice) noexcept{
  642. PrattCallback prefix = rules[curr().type].prefix;
  643. return prefix != nullptr && (allow_slice || curr().type != TK_COLON);
  644. }
  645. Error* Compiler::parse_expression(int precedence, bool allow_slice) noexcept{
  646. PrattCallback prefix = rules[curr().type].prefix;
  647. if(prefix == nullptr || (curr().type == TK_COLON && !allow_slice)) {
  648. return SyntaxError("expected an expression, got %s", pk_TokenSymbols[curr().type]);
  649. }
  650. advance();
  651. Error* err;
  652. check((this->*prefix)());
  653. while(rules[curr().type].precedence >= precedence && (allow_slice || curr().type != TK_COLON)) {
  654. TokenIndex op = curr().type;
  655. advance();
  656. PrattCallback infix = rules[op].infix;
  657. assert(infix != nullptr);
  658. check((this->*infix)());
  659. }
  660. return NULL;
  661. }
  662. Error* Compiler::compile_if_stmt() noexcept{
  663. Error* err;
  664. check(EXPR()); // condition
  665. ctx()->s_emit_top();
  666. int patch = ctx()->emit_(OP_POP_JUMP_IF_FALSE, BC_NOARG, prev().line);
  667. err = compile_block_body();
  668. if(err) return err;
  669. if(match(TK_ELIF)) {
  670. int exit_patch = ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, prev().line);
  671. ctx()->patch_jump(patch);
  672. check(compile_if_stmt());
  673. ctx()->patch_jump(exit_patch);
  674. } else if(match(TK_ELSE)) {
  675. int exit_patch = ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, prev().line);
  676. ctx()->patch_jump(patch);
  677. check(compile_block_body());
  678. ctx()->patch_jump(exit_patch);
  679. } else {
  680. ctx()->patch_jump(patch);
  681. }
  682. return NULL;
  683. }
  684. Error* Compiler::compile_while_loop() noexcept{
  685. Error* err;
  686. CodeBlock* block = ctx()->enter_block(CodeBlockType_WHILE_LOOP);
  687. check(EXPR()); // condition
  688. ctx()->s_emit_top();
  689. int patch = ctx()->emit_(OP_POP_JUMP_IF_FALSE, BC_NOARG, prev().line);
  690. check(compile_block_body());
  691. ctx()->emit_(OP_LOOP_CONTINUE, ctx()->get_loop(), BC_KEEPLINE, true);
  692. ctx()->patch_jump(patch);
  693. ctx()->exit_block();
  694. // optional else clause
  695. if(match(TK_ELSE)) {
  696. check(compile_block_body());
  697. block->end2 = ctx()->co->codes.count;
  698. }
  699. return NULL;
  700. }
  701. Error* Compiler::compile_for_loop() noexcept{
  702. Error* err;
  703. check(EXPR_VARS()); // [vars]
  704. consume(TK_IN);
  705. check(EXPR_TUPLE()); // [vars, iter]
  706. ctx()->s_emit_top(); // [vars]
  707. ctx()->emit_(OP_GET_ITER_NEW, BC_NOARG, BC_KEEPLINE);
  708. CodeBlock* block = ctx()->enter_block(CodeBlockType_FOR_LOOP);
  709. int for_codei = ctx()->emit_(OP_FOR_ITER, ctx()->curr_iblock, BC_KEEPLINE);
  710. Expr* vars = ctx()->s_popx();
  711. bool ok = vars->emit_store(ctx());
  712. delete_expr(vars);
  713. if(!ok) return SyntaxError(); // this error occurs in `vars` instead of this line, but...nevermind
  714. ctx()->try_merge_for_iter_store(for_codei);
  715. check(compile_block_body());
  716. ctx()->emit_(OP_LOOP_CONTINUE, ctx()->get_loop(), BC_KEEPLINE, true);
  717. ctx()->exit_block();
  718. // optional else clause
  719. if(match(TK_ELSE)) {
  720. check(compile_block_body());
  721. block->end2 = ctx()->co->codes.count;
  722. }
  723. return NULL;
  724. }
  725. Error* Compiler::compile_try_except() noexcept{
  726. Error* err;
  727. ctx()->enter_block(CodeBlockType_TRY_EXCEPT);
  728. ctx()->emit_(OP_TRY_ENTER, BC_NOARG, prev().line);
  729. check(compile_block_body());
  730. small_vector_2<int, 8> patches;
  731. patches.push_back(ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE));
  732. ctx()->exit_block();
  733. int finally_entry = -1;
  734. if(curr().type != TK_FINALLY) {
  735. do {
  736. StrName as_name;
  737. consume(TK_EXCEPT);
  738. if(is_expression()) {
  739. check(EXPR()); // push assumed type on to the stack
  740. ctx()->s_emit_top();
  741. ctx()->emit_(OP_EXCEPTION_MATCH, BC_NOARG, prev().line);
  742. if(match(TK_AS)) {
  743. consume(TK_ID);
  744. as_name = StrName(prev().sv());
  745. }
  746. } else {
  747. ctx()->emit_(OP_LOAD_TRUE, BC_NOARG, BC_KEEPLINE);
  748. }
  749. int patch = ctx()->emit_(OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  750. // on match
  751. if(!as_name.empty()) {
  752. ctx()->emit_(OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  753. ctx()->emit_store_name(name_scope(), as_name, BC_KEEPLINE);
  754. }
  755. // pop the exception
  756. ctx()->emit_(OP_POP_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  757. check(compile_block_body());
  758. patches.push_back(ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE));
  759. ctx()->patch_jump(patch);
  760. } while(curr().type == TK_EXCEPT);
  761. }
  762. if(match(TK_FINALLY)) {
  763. int patch = ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  764. finally_entry = ctx()->co->codes.count;
  765. check(compile_block_body());
  766. ctx()->emit_(OP_JUMP_ABSOLUTE_TOP, BC_NOARG, BC_KEEPLINE);
  767. ctx()->patch_jump(patch);
  768. }
  769. // no match, re-raise
  770. if(finally_entry != -1) {
  771. i64 target = ctx()->co->codes.count + 2;
  772. ctx()->emit_(OP_LOAD_CONST, ctx()->add_const(VAR(target)), BC_KEEPLINE);
  773. int i = ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  774. Bytecode* bc = c11__at(Bytecode, &ctx()->co->codes, i);
  775. Bytecode__set_signed_arg(bc, finally_entry - i);
  776. }
  777. ctx()->emit_(OP_RE_RAISE, BC_NOARG, BC_KEEPLINE);
  778. // no exception or no match, jump to the end
  779. for(int patch: patches)
  780. ctx()->patch_jump(patch);
  781. if(finally_entry != -1) {
  782. i64 target = ctx()->co->codes.count + 2;
  783. ctx()->emit_(OP_LOAD_CONST, ctx()->add_const(VAR(target)), BC_KEEPLINE);
  784. int i = ctx()->emit_(OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  785. Bytecode* bc = c11__at(Bytecode, &ctx()->co->codes, i);
  786. Bytecode__set_signed_arg(bc, finally_entry - i);
  787. }
  788. return NULL;
  789. }
  790. Error* Compiler::compile_decorated() noexcept{
  791. Error* err;
  792. int count = 0;
  793. do {
  794. check(EXPR());
  795. count += 1;
  796. bool need_more_lines;
  797. bool consumed = match_newlines(&need_more_lines);
  798. if(need_more_lines) return NeedMoreLines();
  799. if(!consumed) return SyntaxError("expected a newline after '@'");
  800. } while(match(TK_DECORATOR));
  801. if(match(TK_CLASS)) {
  802. check(compile_class(count));
  803. } else {
  804. consume(TK_DEF);
  805. check(compile_function(count));
  806. }
  807. return NULL;
  808. }
  809. Error* Compiler::try_compile_assignment(bool* is_assign) noexcept{
  810. Error* err;
  811. switch(curr().type) {
  812. case TK_IADD:
  813. case TK_ISUB:
  814. case TK_IMUL:
  815. case TK_IDIV:
  816. case TK_IFLOORDIV:
  817. case TK_IMOD:
  818. case TK_ILSHIFT:
  819. case TK_IRSHIFT:
  820. case TK_IAND:
  821. case TK_IOR:
  822. case TK_IXOR: {
  823. if(ctx()->s_top()->is_starred()) return SyntaxError();
  824. if(ctx()->is_compiling_class){
  825. return SyntaxError("can't use inplace operator in class definition");
  826. }
  827. advance();
  828. // a[x] += 1; a and x should be evaluated only once
  829. // a.x += 1; a should be evaluated only once
  830. // -1 to remove =; inplace=true
  831. int line = prev().line;
  832. TokenIndex op = (TokenIndex)(prev().type - 1);
  833. // [lhs]
  834. check(EXPR_TUPLE()); // [lhs, rhs]
  835. if(ctx()->s_top()->is_starred()) return SyntaxError();
  836. BinaryExpr* e = make_expr<BinaryExpr>(op, true);
  837. e->line = line;
  838. e->rhs = ctx()->s_popx(); // [lhs]
  839. e->lhs = ctx()->s_popx(); // []
  840. e->emit_(ctx());
  841. bool ok = e->lhs->emit_store_inplace(ctx());
  842. delete_expr(e);
  843. if(!ok) return SyntaxError();
  844. *is_assign = true;
  845. return NULL;
  846. }
  847. case TK_ASSIGN: {
  848. int n = 0;
  849. while(match(TK_ASSIGN)) {
  850. check(EXPR_TUPLE());
  851. n += 1;
  852. }
  853. // stack size is n+1
  854. ctx()->s_emit_top(); // emit and pop
  855. for(int j = 1; j < n; j++)
  856. ctx()->emit_(OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  857. for(int j = 0; j < n; j++) {
  858. if(ctx()->s_top()->is_starred()) return SyntaxError();
  859. bool ok = ctx()->s_top()->emit_store(ctx());
  860. ctx()->s_pop();
  861. if(!ok) return SyntaxError();
  862. }
  863. *is_assign = true;
  864. return NULL;
  865. }
  866. default: *is_assign = false;
  867. }
  868. return NULL;
  869. }
  870. Error* Compiler::compile_stmt() noexcept{
  871. Error* err;
  872. if(match(TK_CLASS)) {
  873. check(compile_class());
  874. return NULL;
  875. }
  876. advance();
  877. int kw_line = prev().line; // backup line number
  878. int curr_loop_block = ctx()->get_loop();
  879. switch(prev().type) {
  880. case TK_BREAK:
  881. if(curr_loop_block < 0) return SyntaxError("'break' outside loop");
  882. ctx()->emit_(OP_LOOP_BREAK, curr_loop_block, kw_line);
  883. consume_end_stmt();
  884. break;
  885. case TK_CONTINUE:
  886. if(curr_loop_block < 0) return SyntaxError("'continue' not properly in loop");
  887. ctx()->emit_(OP_LOOP_CONTINUE, curr_loop_block, kw_line);
  888. consume_end_stmt();
  889. break;
  890. case TK_YIELD:
  891. if(contexts.size() <= 1) return SyntaxError("'yield' outside function");
  892. check(EXPR_TUPLE());
  893. ctx()->s_emit_top();
  894. ctx()->emit_(OP_YIELD_VALUE, BC_NOARG, kw_line);
  895. consume_end_stmt();
  896. break;
  897. case TK_YIELD_FROM:
  898. if(contexts.size() <= 1) return SyntaxError("'yield from' outside function");
  899. check(EXPR_TUPLE());
  900. ctx()->s_emit_top();
  901. ctx()->emit_(OP_GET_ITER_NEW, BC_NOARG, kw_line);
  902. ctx()->enter_block(CodeBlockType_FOR_LOOP);
  903. ctx()->emit_(OP_FOR_ITER_YIELD_VALUE, BC_NOARG, kw_line);
  904. ctx()->emit_(OP_LOOP_CONTINUE, ctx()->get_loop(), kw_line);
  905. ctx()->exit_block();
  906. consume_end_stmt();
  907. break;
  908. case TK_RETURN:
  909. if(contexts.size() <= 1) return SyntaxError("'return' outside function");
  910. if(match_end_stmt()) {
  911. ctx()->emit_(OP_RETURN_VALUE, 1, kw_line);
  912. } else {
  913. check(EXPR_TUPLE());
  914. ctx()->s_emit_top();
  915. consume_end_stmt();
  916. ctx()->emit_(OP_RETURN_VALUE, BC_NOARG, kw_line);
  917. }
  918. break;
  919. /*************************************************/
  920. case TK_IF: check(compile_if_stmt()); break;
  921. case TK_WHILE: check(compile_while_loop()); break;
  922. case TK_FOR: check(compile_for_loop()); break;
  923. case TK_IMPORT: check(compile_normal_import()); break;
  924. case TK_FROM: check(compile_from_import()); break;
  925. case TK_DEF: check(compile_function()); break;
  926. case TK_DECORATOR: check(compile_decorated()); break;
  927. case TK_TRY: check(compile_try_except()); break;
  928. case TK_PASS: consume_end_stmt(); break;
  929. /*************************************************/
  930. case TK_ASSERT: {
  931. check(EXPR()); // condition
  932. ctx()->s_emit_top();
  933. int index = ctx()->emit_(OP_POP_JUMP_IF_TRUE, BC_NOARG, kw_line);
  934. int has_msg = 0;
  935. if(match(TK_COMMA)) {
  936. check(EXPR()); // message
  937. ctx()->s_emit_top();
  938. has_msg = 1;
  939. }
  940. ctx()->emit_(OP_RAISE_ASSERT, has_msg, kw_line);
  941. ctx()->patch_jump(index);
  942. consume_end_stmt();
  943. break;
  944. }
  945. case TK_GLOBAL:
  946. do {
  947. consume(TK_ID);
  948. ctx()->global_names.push_back(StrName(prev().sv()));
  949. } while(match(TK_COMMA));
  950. consume_end_stmt();
  951. break;
  952. case TK_RAISE: {
  953. check(EXPR());
  954. ctx()->s_emit_top();
  955. ctx()->emit_(OP_RAISE, BC_NOARG, kw_line);
  956. consume_end_stmt();
  957. } break;
  958. case TK_DEL: {
  959. check(EXPR_TUPLE());
  960. if(!ctx()->s_top()->emit_del(ctx())) return SyntaxError();
  961. ctx()->s_pop();
  962. consume_end_stmt();
  963. } break;
  964. case TK_WITH: {
  965. check(EXPR()); // [ <expr> ]
  966. ctx()->s_emit_top();
  967. ctx()->enter_block(CodeBlockType_CONTEXT_MANAGER);
  968. Expr* as_name = nullptr;
  969. if(match(TK_AS)) {
  970. consume(TK_ID);
  971. as_name = make_expr<NameExpr>(prev().str(), name_scope());
  972. }
  973. ctx()->emit_(OP_WITH_ENTER, BC_NOARG, prev().line);
  974. // [ <expr> <expr>.__enter__() ]
  975. if(as_name) {
  976. bool ok = as_name->emit_store(ctx());
  977. delete_expr(as_name);
  978. if(!ok) return SyntaxError();
  979. } else {
  980. ctx()->emit_(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  981. }
  982. check(compile_block_body());
  983. ctx()->emit_(OP_WITH_EXIT, BC_NOARG, prev().line);
  984. ctx()->exit_block();
  985. } break;
  986. /*************************************************/
  987. case TK_EQ: {
  988. consume(TK_ID);
  989. if(mode() != EXEC_MODE) return SyntaxError("'label' is only available in EXEC_MODE");
  990. if(!ctx()->add_label(prev().str())) {
  991. Str escaped(prev().str().escape());
  992. return SyntaxError("label %s already exists", escaped.c_str());
  993. }
  994. consume(TK_EQ);
  995. consume_end_stmt();
  996. } break;
  997. case TK_ARROW:
  998. consume(TK_ID);
  999. if(mode() != EXEC_MODE) return SyntaxError("'goto' is only available in EXEC_MODE");
  1000. ctx()->emit_(OP_GOTO, StrName(prev().sv()).index, prev().line);
  1001. consume_end_stmt();
  1002. break;
  1003. /*************************************************/
  1004. // handle dangling expression or assignment
  1005. default: {
  1006. advance(-1); // do revert since we have pre-called advance() at the beginning
  1007. check(EXPR_TUPLE());
  1008. bool is_typed_name = false; // e.g. x: int
  1009. // eat variable's type hint if it is a single name
  1010. if(ctx()->s_top()->is_name()) {
  1011. if(match(TK_COLON)) {
  1012. check(consume_type_hints());
  1013. is_typed_name = true;
  1014. if(ctx()->is_compiling_class) {
  1015. NameExpr* ne = static_cast<NameExpr*>(ctx()->s_top());
  1016. ctx()->emit_(OP_ADD_CLASS_ANNOTATION, ne->name.index, BC_KEEPLINE);
  1017. }
  1018. }
  1019. }
  1020. bool is_assign = false;
  1021. check(try_compile_assignment(&is_assign));
  1022. if(!is_assign) {
  1023. if(ctx()->s_size() > 0 && ctx()->s_top()->is_starred()) {
  1024. return SyntaxError();
  1025. }
  1026. if(!is_typed_name) {
  1027. ctx()->s_emit_top();
  1028. if((mode() == CELL_MODE || mode() == REPL_MODE) && name_scope() == NAME_GLOBAL) {
  1029. ctx()->emit_(OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  1030. } else {
  1031. ctx()->emit_(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  1032. }
  1033. } else {
  1034. ctx()->s_pop();
  1035. }
  1036. }
  1037. consume_end_stmt();
  1038. break;
  1039. }
  1040. }
  1041. return NULL;
  1042. }
  1043. Error* Compiler::consume_type_hints() noexcept{
  1044. Error* err;
  1045. check(EXPR());
  1046. ctx()->s_pop();
  1047. return NULL;
  1048. }
  1049. Error* Compiler::compile_class(int decorators) noexcept{
  1050. Error* err;
  1051. consume(TK_ID);
  1052. int namei = StrName(prev().sv()).index;
  1053. bool has_base = false;
  1054. if(match(TK_LPAREN)) {
  1055. if(is_expression()) {
  1056. check(EXPR());
  1057. has_base = true; // [base]
  1058. }
  1059. consume(TK_RPAREN);
  1060. }
  1061. if(!has_base) {
  1062. ctx()->emit_(OP_LOAD_NONE, BC_NOARG, prev().line);
  1063. } else {
  1064. ctx()->s_emit_top(); // []
  1065. }
  1066. ctx()->emit_(OP_BEGIN_CLASS, namei, BC_KEEPLINE);
  1067. for(auto& c: this->contexts) {
  1068. if(c.is_compiling_class) return SyntaxError("nested class is not allowed");
  1069. }
  1070. ctx()->is_compiling_class = true;
  1071. check(compile_block_body());
  1072. ctx()->is_compiling_class = false;
  1073. if(decorators > 0) {
  1074. ctx()->emit_(OP_BEGIN_CLASS_DECORATION, BC_NOARG, BC_KEEPLINE);
  1075. ctx()->s_emit_decorators(decorators);
  1076. ctx()->emit_(OP_END_CLASS_DECORATION, BC_NOARG, BC_KEEPLINE);
  1077. }
  1078. ctx()->emit_(OP_END_CLASS, namei, BC_KEEPLINE);
  1079. return NULL;
  1080. }
  1081. Error* Compiler::_compile_f_args(FuncDecl* decl, bool enable_type_hints) noexcept{
  1082. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  1083. Error* err;
  1084. do {
  1085. if(state > 3) return SyntaxError();
  1086. if(state == 3) return SyntaxError("**kwargs should be the last argument");
  1087. match_newlines();
  1088. if(match(TK_MUL)) {
  1089. if(state < 1)
  1090. state = 1;
  1091. else
  1092. return SyntaxError("*args should be placed before **kwargs");
  1093. } else if(match(TK_POW)) {
  1094. state = 3;
  1095. }
  1096. consume(TK_ID);
  1097. StrName name(prev().sv());
  1098. // check duplicate argument name
  1099. uint16_t tmp_name;
  1100. c11_vector__foreach(int, &decl->args, j) {
  1101. tmp_name = c11__getitem(uint16_t, &decl->args, *j);
  1102. if(tmp_name == name.index) return SyntaxError("duplicate argument name");
  1103. }
  1104. c11_vector__foreach(FuncDeclKwArg, &decl->kwargs, kv) {
  1105. tmp_name = c11__getitem(uint16_t, &decl->code->varnames, kv->index);
  1106. if(tmp_name == name.index) return SyntaxError("duplicate argument name");
  1107. }
  1108. if(decl->starred_arg != -1) {
  1109. tmp_name = c11__getitem(uint16_t, &decl->code->varnames, decl->starred_arg);
  1110. if(tmp_name == name.index) return SyntaxError("duplicate argument name");
  1111. }
  1112. if(decl->starred_kwarg != -1) {
  1113. tmp_name = c11__getitem(uint16_t, &decl->code->varnames, decl->starred_kwarg);
  1114. if(tmp_name == name.index) return SyntaxError("duplicate argument name");
  1115. }
  1116. // eat type hints
  1117. if(enable_type_hints && match(TK_COLON)) check(consume_type_hints());
  1118. if(state == 0 && curr().type == TK_ASSIGN) state = 2;
  1119. int index = ctx()->add_varname(name);
  1120. switch(state) {
  1121. case 0:
  1122. c11_vector__push(int, &decl->args, index);
  1123. break;
  1124. case 1:
  1125. decl->starred_arg = index;
  1126. state += 1;
  1127. break;
  1128. case 2: {
  1129. consume(TK_ASSIGN);
  1130. PyVar value;
  1131. check(read_literal(&value));
  1132. if(value == nullptr) return SyntaxError("default argument must be a literal");
  1133. FuncDecl__add_kwarg(decl, index, name.index, (const ::PyVar*)&value);
  1134. } break;
  1135. case 3:
  1136. decl->starred_kwarg = index;
  1137. state += 1;
  1138. break;
  1139. }
  1140. } while(match(TK_COMMA));
  1141. return NULL;
  1142. }
  1143. Error* Compiler::compile_function(int decorators) noexcept{
  1144. Error* err;
  1145. consume(TK_ID);
  1146. std::string_view decl_name = prev().sv();
  1147. int decl_index;
  1148. FuncDecl_ decl = push_f_context({decl_name.data(), (int)decl_name.size()}, &decl_index);
  1149. consume(TK_LPAREN);
  1150. if(!match(TK_RPAREN)) {
  1151. check(_compile_f_args(decl, true));
  1152. consume(TK_RPAREN);
  1153. }
  1154. if(match(TK_ARROW)) check(consume_type_hints());
  1155. check(compile_block_body());
  1156. check(pop_context());
  1157. if(decl->code->codes.count >= 2) {
  1158. Bytecode* codes = (Bytecode*)decl->code->codes.data;
  1159. if(codes[0].op == OP_LOAD_CONST && codes[1].op == OP_POP_TOP) {
  1160. // handle optional docstring
  1161. PyVar* c = c11__at(PyVar, &decl->code->consts, codes[0].arg);
  1162. if(is_type(*c, vm->tp_str)) {
  1163. codes[0].op = OP_NO_OP;
  1164. codes[1].op = OP_NO_OP;
  1165. decl->docstring = PK_OBJ_GET(Str, *c).c_str();
  1166. }
  1167. }
  1168. }
  1169. ctx()->emit_(OP_LOAD_FUNCTION, decl_index, prev().line);
  1170. ctx()->s_emit_decorators(decorators);
  1171. if(!ctx()->is_compiling_class) {
  1172. NameExpr* e = make_expr<NameExpr>(StrName(decl_name), name_scope());
  1173. e->emit_store(ctx());
  1174. delete_expr(e);
  1175. } else {
  1176. int index = StrName(decl_name).index;
  1177. ctx()->emit_(OP_STORE_CLASS_ATTR, index, prev().line);
  1178. }
  1179. return NULL;
  1180. }
  1181. PyVar Compiler::to_object(const TokenValue& value) noexcept{
  1182. PyVar obj = nullptr;
  1183. if(std::holds_alternative<i64>(value)) { obj = VAR(std::get<i64>(value)); }
  1184. if(std::holds_alternative<f64>(value)) { obj = VAR(std::get<f64>(value)); }
  1185. if(std::holds_alternative<Str>(value)) { obj = VAR(std::get<Str>(value)); }
  1186. assert(obj != nullptr);
  1187. return obj;
  1188. }
  1189. Error* Compiler::read_literal(PyVar* out) noexcept{
  1190. Error* err;
  1191. advance();
  1192. switch(prev().type) {
  1193. case TK_SUB: {
  1194. consume(TK_NUM);
  1195. PyVar val = to_object(prev().value);
  1196. *out = vm->py_negate(val);
  1197. return NULL;
  1198. }
  1199. case TK_NUM: *out = to_object(prev().value); return NULL;
  1200. case TK_STR: *out = to_object(prev().value); return NULL;
  1201. case TK_TRUE: *out = VAR(true); return NULL;
  1202. case TK_FALSE: *out = VAR(false); return NULL;
  1203. case TK_NONE: *out = vm->None; return NULL;
  1204. case TK_DOTDOTDOT: *out = vm->Ellipsis; return NULL;
  1205. case TK_LPAREN: {
  1206. List cpnts;
  1207. while(true) {
  1208. PyVar elem;
  1209. check(read_literal(&elem));
  1210. cpnts.push_back(elem);
  1211. if(curr().type == TK_RPAREN) break;
  1212. consume(TK_COMMA);
  1213. if(curr().type == TK_RPAREN) break;
  1214. }
  1215. consume(TK_RPAREN);
  1216. *out = VAR(cpnts.to_tuple());
  1217. return NULL;
  1218. }
  1219. default: *out = nullptr; return NULL;
  1220. }
  1221. }
  1222. Compiler::Compiler(VM* vm, std::string_view source, const Str& filename, CompileMode mode, bool unknown_global_scope) noexcept:
  1223. lexer(vm, source, filename, mode){
  1224. this->vm = vm;
  1225. this->unknown_global_scope = unknown_global_scope;
  1226. init_pratt_rules();
  1227. }
  1228. Error* Compiler::compile(CodeObject** out) noexcept{
  1229. assert(__i == 0); // make sure it is the first time to compile
  1230. Error* err;
  1231. check(lexer.run());
  1232. // if(lexer.src.filename()[0] != '<'){
  1233. // printf("%s\n", lexer.src.filename().c_str());
  1234. // for(int i=0; i<lexer.nexts.size(); i++){
  1235. // printf("%s: %s\n", pk_TokenSymbols[tk(i).type], tk(i).str().escape().c_str());
  1236. // }
  1237. // }
  1238. CodeObject* code = push_global_context();
  1239. assert(curr().type == TK_SOF);
  1240. advance(); // skip @sof, so prev() is always valid
  1241. match_newlines(); // skip possible leading '\n'
  1242. if(mode() == EVAL_MODE) {
  1243. check(EXPR_TUPLE());
  1244. ctx()->s_emit_top();
  1245. consume(TK_EOF);
  1246. ctx()->emit_(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1247. check(pop_context());
  1248. *out = code;
  1249. return NULL;
  1250. } else if(mode() == JSON_MODE) {
  1251. check(EXPR());
  1252. Expr* e = ctx()->s_popx();
  1253. if(!e->is_json_object()) return SyntaxError("expect a JSON object, literal or array");
  1254. consume(TK_EOF);
  1255. e->emit_(ctx());
  1256. ctx()->emit_(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1257. check(pop_context());
  1258. *out = code;
  1259. return NULL;
  1260. }
  1261. while(!match(TK_EOF)) {
  1262. check(compile_stmt());
  1263. match_newlines();
  1264. }
  1265. check(pop_context());
  1266. *out = code;
  1267. return NULL;
  1268. }
  1269. Compiler::~Compiler(){
  1270. for(CodeEmitContext& ctx: contexts){
  1271. ctx.s_clean();
  1272. }
  1273. }
  1274. Error* Compiler::SyntaxError(const char* msg, ...) noexcept{
  1275. va_list args;
  1276. va_start(args, msg);
  1277. Error* e = lexer._error(false, "SyntaxError", msg, &args);
  1278. e->lineno = err().line;
  1279. e->cursor = err().start;
  1280. va_end(args);
  1281. return e;
  1282. }
  1283. #undef consume
  1284. #undef consume_end_stmt
  1285. #undef check
  1286. #undef check_newlines_repl
  1287. } // namespace pkpy