expr.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "common.h"
  4. #include "lexer.h"
  5. #include "error.h"
  6. #include "ceval.h"
  7. #include "str.h"
  8. namespace pkpy{
  9. struct CodeEmitContext;
  10. struct Expr;
  11. typedef std::unique_ptr<Expr> Expr_;
  12. struct Expr{
  13. int line = 0;
  14. virtual ~Expr() = default;
  15. virtual void emit(CodeEmitContext* ctx) = 0;
  16. virtual std::string str() const = 0;
  17. virtual bool is_starred() const { return false; }
  18. virtual bool is_literal() const { return false; }
  19. virtual bool is_json_object() const { return false; }
  20. virtual bool is_attrib() const { return false; }
  21. // for OP_DELETE_XXX
  22. [[nodiscard]] virtual bool emit_del(CodeEmitContext* ctx) { return false; }
  23. // for OP_STORE_XXX
  24. [[nodiscard]] virtual bool emit_store(CodeEmitContext* ctx) { return false; }
  25. };
  26. struct CodeEmitContext{
  27. VM* vm;
  28. CodeObject_ co;
  29. stack<Expr_> s_expr;
  30. int level;
  31. CodeEmitContext(VM* vm, CodeObject_ co, int level): vm(vm), co(co), level(level) {}
  32. int curr_block_i = 0;
  33. bool is_compiling_class = false;
  34. int for_loop_depth = 0;
  35. bool is_curr_block_loop() const {
  36. return co->blocks[curr_block_i].type == FOR_LOOP || co->blocks[curr_block_i].type == WHILE_LOOP;
  37. }
  38. void enter_block(CodeBlockType type){
  39. if(type == FOR_LOOP) for_loop_depth++;
  40. co->blocks.push_back(CodeBlock(
  41. type, curr_block_i, for_loop_depth, (int)co->codes.size()
  42. ));
  43. curr_block_i = co->blocks.size()-1;
  44. }
  45. void exit_block(){
  46. if(co->blocks[curr_block_i].type == FOR_LOOP) for_loop_depth--;
  47. co->blocks[curr_block_i].end = co->codes.size();
  48. curr_block_i = co->blocks[curr_block_i].parent;
  49. if(curr_block_i < 0) FATAL_ERROR();
  50. }
  51. // clear the expression stack and generate bytecode
  52. void emit_expr(){
  53. if(s_expr.size() != 1){
  54. throw std::runtime_error("s_expr.size() != 1\n" + _log_s_expr());
  55. }
  56. Expr_ expr = s_expr.popx();
  57. expr->emit(this);
  58. }
  59. std::string _log_s_expr(){
  60. std::stringstream ss;
  61. for(auto& e: s_expr.data()) ss << e->str() << " ";
  62. return ss.str();
  63. }
  64. int emit(Opcode opcode, int arg, int line) {
  65. co->codes.push_back(
  66. Bytecode{(uint16_t)opcode, (uint16_t)curr_block_i, arg}
  67. );
  68. co->lines.push_back(line);
  69. int i = co->codes.size() - 1;
  70. if(line==BC_KEEPLINE){
  71. if(i>=1) co->lines[i] = co->lines[i-1];
  72. else co->lines[i] = 1;
  73. }
  74. return i;
  75. }
  76. void patch_jump(int index) {
  77. int target = co->codes.size();
  78. co->codes[index].arg = target;
  79. }
  80. bool add_label(StrName name){
  81. if(co->labels.contains(name)) return false;
  82. co->labels.set(name, co->codes.size());
  83. return true;
  84. }
  85. int add_varname(StrName name){
  86. int index = co->varnames_inv.try_get(name);
  87. if(index >= 0) return index;
  88. co->varnames.push_back(name);
  89. index = co->varnames.size() - 1;
  90. co->varnames_inv.set(name, index);
  91. return index;
  92. }
  93. int add_const(PyObject* v){
  94. // simple deduplication, only works for int/float
  95. for(int i=0; i<co->consts.size(); i++){
  96. if(co->consts[i] == v) return i;
  97. }
  98. co->consts.push_back(v);
  99. return co->consts.size() - 1;
  100. }
  101. int add_func_decl(FuncDecl_ decl){
  102. co->func_decls.push_back(decl);
  103. return co->func_decls.size() - 1;
  104. }
  105. };
  106. struct NameExpr: Expr{
  107. StrName name;
  108. NameScope scope;
  109. NameExpr(StrName name, NameScope scope): name(name), scope(scope) {}
  110. std::string str() const override { return fmt("Name(", name.escape(), ")"); }
  111. void emit(CodeEmitContext* ctx) override {
  112. int index = ctx->co->varnames_inv.try_get(name);
  113. if(scope == NAME_LOCAL && index >= 0){
  114. ctx->emit(OP_LOAD_FAST, index, line);
  115. }else{
  116. Opcode op = ctx->level <= 1 ? OP_LOAD_GLOBAL : OP_LOAD_NONLOCAL;
  117. // we cannot determine the scope when calling exec()/eval()
  118. if(scope == NAME_GLOBAL_UNKNOWN) op = OP_LOAD_NAME;
  119. ctx->emit(op, StrName(name).index, line);
  120. }
  121. }
  122. bool emit_del(CodeEmitContext* ctx) override {
  123. switch(scope){
  124. case NAME_LOCAL:
  125. ctx->emit(OP_DELETE_FAST, ctx->add_varname(name), line);
  126. break;
  127. case NAME_GLOBAL:
  128. ctx->emit(OP_DELETE_GLOBAL, StrName(name).index, line);
  129. break;
  130. case NAME_GLOBAL_UNKNOWN:
  131. ctx->emit(OP_DELETE_NAME, StrName(name).index, line);
  132. break;
  133. default: FATAL_ERROR(); break;
  134. }
  135. return true;
  136. }
  137. bool emit_store(CodeEmitContext* ctx) override {
  138. if(ctx->is_compiling_class){
  139. int index = StrName(name).index;
  140. ctx->emit(OP_STORE_CLASS_ATTR, index, line);
  141. return true;
  142. }
  143. switch(scope){
  144. case NAME_LOCAL:
  145. ctx->emit(OP_STORE_FAST, ctx->add_varname(name), line);
  146. break;
  147. case NAME_GLOBAL:
  148. ctx->emit(OP_STORE_GLOBAL, StrName(name).index, line);
  149. break;
  150. case NAME_GLOBAL_UNKNOWN:
  151. ctx->emit(OP_STORE_NAME, StrName(name).index, line);
  152. break;
  153. default: FATAL_ERROR(); break;
  154. }
  155. return true;
  156. }
  157. };
  158. struct StarredExpr: Expr{
  159. Expr_ child;
  160. StarredExpr(Expr_&& child): child(std::move(child)) {}
  161. std::string str() const override { return "Starred()"; }
  162. bool is_starred() const override { return true; }
  163. void emit(CodeEmitContext* ctx) override {
  164. child->emit(ctx);
  165. ctx->emit(OP_UNPACK_UNLIMITED, BC_NOARG, line);
  166. }
  167. bool emit_store(CodeEmitContext* ctx) override {
  168. // simply proxy to child
  169. return child->emit_store(ctx);
  170. }
  171. };
  172. struct NotExpr: Expr{
  173. Expr_ child;
  174. NotExpr(Expr_&& child): child(std::move(child)) {}
  175. std::string str() const override { return "Not()"; }
  176. void emit(CodeEmitContext* ctx) override {
  177. child->emit(ctx);
  178. ctx->emit(OP_UNARY_NOT, BC_NOARG, line);
  179. }
  180. };
  181. struct AndExpr: Expr{
  182. Expr_ lhs;
  183. Expr_ rhs;
  184. std::string str() const override { return "And()"; }
  185. void emit(CodeEmitContext* ctx) override {
  186. lhs->emit(ctx);
  187. int patch = ctx->emit(OP_JUMP_IF_FALSE_OR_POP, BC_NOARG, line);
  188. rhs->emit(ctx);
  189. ctx->patch_jump(patch);
  190. }
  191. };
  192. struct OrExpr: Expr{
  193. Expr_ lhs;
  194. Expr_ rhs;
  195. std::string str() const override { return "Or()"; }
  196. void emit(CodeEmitContext* ctx) override {
  197. lhs->emit(ctx);
  198. int patch = ctx->emit(OP_JUMP_IF_TRUE_OR_POP, BC_NOARG, line);
  199. rhs->emit(ctx);
  200. ctx->patch_jump(patch);
  201. }
  202. };
  203. // [None, True, False, ...]
  204. struct Literal0Expr: Expr{
  205. TokenIndex token;
  206. Literal0Expr(TokenIndex token): token(token) {}
  207. std::string str() const override { return TK_STR(token); }
  208. void emit(CodeEmitContext* ctx) override {
  209. switch (token) {
  210. case TK("None"): ctx->emit(OP_LOAD_NONE, BC_NOARG, line); break;
  211. case TK("True"): ctx->emit(OP_LOAD_TRUE, BC_NOARG, line); break;
  212. case TK("False"): ctx->emit(OP_LOAD_FALSE, BC_NOARG, line); break;
  213. case TK("..."): ctx->emit(OP_LOAD_ELLIPSIS, BC_NOARG, line); break;
  214. default: FATAL_ERROR();
  215. }
  216. }
  217. bool is_json_object() const override { return true; }
  218. };
  219. // @num, @str which needs to invoke OP_LOAD_CONST
  220. struct LiteralExpr: Expr{
  221. TokenValue value;
  222. LiteralExpr(TokenValue value): value(value) {}
  223. std::string str() const override {
  224. if(std::holds_alternative<i64>(value)){
  225. return std::to_string(std::get<i64>(value));
  226. }
  227. if(std::holds_alternative<f64>(value)){
  228. return std::to_string(std::get<f64>(value));
  229. }
  230. if(std::holds_alternative<Str>(value)){
  231. Str s = std::get<Str>(value).escape();
  232. return s.str();
  233. }
  234. FATAL_ERROR();
  235. }
  236. void emit(CodeEmitContext* ctx) override {
  237. VM* vm = ctx->vm;
  238. PyObject* obj = nullptr;
  239. if(std::holds_alternative<i64>(value)){
  240. i64 _val = std::get<i64>(value);
  241. if(_val >= INT16_MIN && _val <= INT16_MAX){
  242. ctx->emit(OP_LOAD_INTEGER, (int)_val, line);
  243. return;
  244. }
  245. obj = VAR(_val);
  246. }
  247. if(std::holds_alternative<f64>(value)){
  248. obj = VAR(std::get<f64>(value));
  249. }
  250. if(std::holds_alternative<Str>(value)){
  251. obj = VAR(std::get<Str>(value));
  252. }
  253. if(obj == nullptr) FATAL_ERROR();
  254. ctx->emit(OP_LOAD_CONST, ctx->add_const(obj), line);
  255. }
  256. bool is_literal() const override { return true; }
  257. bool is_json_object() const override { return true; }
  258. };
  259. struct NegatedExpr: Expr{
  260. Expr_ child;
  261. NegatedExpr(Expr_&& child): child(std::move(child)) {}
  262. std::string str() const override { return "Negated()"; }
  263. void emit(CodeEmitContext* ctx) override {
  264. VM* vm = ctx->vm;
  265. // if child is a int of float, do constant folding
  266. if(child->is_literal()){
  267. LiteralExpr* lit = static_cast<LiteralExpr*>(child.get());
  268. if(std::holds_alternative<i64>(lit->value)){
  269. i64 _val = -std::get<i64>(lit->value);
  270. if(_val >= INT16_MIN && _val <= INT16_MAX){
  271. ctx->emit(OP_LOAD_INTEGER, (int)_val, line);
  272. }else{
  273. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(_val)), line);
  274. }
  275. return;
  276. }
  277. if(std::holds_alternative<f64>(lit->value)){
  278. PyObject* obj = VAR(-std::get<f64>(lit->value));
  279. ctx->emit(OP_LOAD_CONST, ctx->add_const(obj), line);
  280. return;
  281. }
  282. }
  283. child->emit(ctx);
  284. ctx->emit(OP_UNARY_NEGATIVE, BC_NOARG, line);
  285. }
  286. bool is_json_object() const override {
  287. return child->is_literal();
  288. }
  289. };
  290. struct SliceExpr: Expr{
  291. Expr_ start;
  292. Expr_ stop;
  293. Expr_ step;
  294. std::string str() const override { return "Slice()"; }
  295. void emit(CodeEmitContext* ctx) override {
  296. if(start){
  297. start->emit(ctx);
  298. }else{
  299. ctx->emit(OP_LOAD_NONE, BC_NOARG, line);
  300. }
  301. if(stop){
  302. stop->emit(ctx);
  303. }else{
  304. ctx->emit(OP_LOAD_NONE, BC_NOARG, line);
  305. }
  306. if(step){
  307. step->emit(ctx);
  308. }else{
  309. ctx->emit(OP_LOAD_NONE, BC_NOARG, line);
  310. }
  311. ctx->emit(OP_BUILD_SLICE, BC_NOARG, line);
  312. }
  313. };
  314. struct DictItemExpr: Expr{
  315. Expr_ key;
  316. Expr_ value;
  317. std::string str() const override { return "DictItem()"; }
  318. void emit(CodeEmitContext* ctx) override {
  319. value->emit(ctx);
  320. key->emit(ctx); // reverse order
  321. ctx->emit(OP_BUILD_TUPLE, 2, line);
  322. }
  323. };
  324. struct SequenceExpr: Expr{
  325. std::vector<Expr_> items;
  326. SequenceExpr(std::vector<Expr_>&& items): items(std::move(items)) {}
  327. virtual Opcode opcode() const = 0;
  328. void emit(CodeEmitContext* ctx) override {
  329. for(auto& item: items) item->emit(ctx);
  330. ctx->emit(opcode(), items.size(), line);
  331. }
  332. };
  333. struct ListExpr: SequenceExpr{
  334. using SequenceExpr::SequenceExpr;
  335. std::string str() const override { return "List()"; }
  336. Opcode opcode() const override { return OP_BUILD_LIST; }
  337. bool is_json_object() const override { return true; }
  338. };
  339. struct DictExpr: SequenceExpr{
  340. using SequenceExpr::SequenceExpr;
  341. std::string str() const override { return "Dict()"; }
  342. Opcode opcode() const override { return OP_BUILD_DICT; }
  343. bool is_json_object() const override { return true; }
  344. };
  345. struct SetExpr: SequenceExpr{
  346. using SequenceExpr::SequenceExpr;
  347. std::string str() const override { return "Set()"; }
  348. Opcode opcode() const override { return OP_BUILD_SET; }
  349. };
  350. struct TupleExpr: SequenceExpr{
  351. using SequenceExpr::SequenceExpr;
  352. std::string str() const override { return "Tuple()"; }
  353. Opcode opcode() const override { return OP_BUILD_TUPLE; }
  354. bool emit_store(CodeEmitContext* ctx) override {
  355. // TOS is an iterable
  356. // items may contain StarredExpr, we should check it
  357. int starred_i = -1;
  358. for(int i=0; i<items.size(); i++){
  359. if(!items[i]->is_starred()) continue;
  360. if(starred_i == -1) starred_i = i;
  361. else return false; // multiple StarredExpr not allowed
  362. }
  363. if(starred_i == -1){
  364. ctx->emit(OP_UNPACK_SEQUENCE, items.size(), line);
  365. }else{
  366. // starred assignment target must be in a tuple
  367. if(items.size() == 1) return false;
  368. // starred assignment target must be the last one (differ from cpython)
  369. if(starred_i != items.size()-1) return false;
  370. // a,*b = [1,2,3]
  371. // stack is [1,2,3] -> [1,[2,3]]
  372. ctx->emit(OP_UNPACK_EX, items.size()-1, line);
  373. }
  374. // do reverse emit
  375. for(int i=items.size()-1; i>=0; i--){
  376. bool ok = items[i]->emit_store(ctx);
  377. if(!ok) return false;
  378. }
  379. return true;
  380. }
  381. bool emit_del(CodeEmitContext* ctx) override{
  382. for(auto& e: items){
  383. bool ok = e->emit_del(ctx);
  384. if(!ok) return false;
  385. }
  386. return true;
  387. }
  388. };
  389. struct CompExpr: Expr{
  390. Expr_ expr; // loop expr
  391. Expr_ vars; // loop vars
  392. Expr_ iter; // loop iter
  393. Expr_ cond; // optional if condition
  394. virtual Opcode op0() = 0;
  395. virtual Opcode op1() = 0;
  396. void emit(CodeEmitContext* ctx){
  397. ctx->emit(op0(), 0, line);
  398. iter->emit(ctx);
  399. ctx->emit(OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  400. ctx->enter_block(FOR_LOOP);
  401. ctx->emit(OP_FOR_ITER, BC_NOARG, BC_KEEPLINE);
  402. bool ok = vars->emit_store(ctx);
  403. // this error occurs in `vars` instead of this line, but...nevermind
  404. if(!ok) FATAL_ERROR(); // TODO: raise a SyntaxError instead
  405. if(cond){
  406. cond->emit(ctx);
  407. int patch = ctx->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  408. expr->emit(ctx);
  409. ctx->emit(op1(), BC_NOARG, BC_KEEPLINE);
  410. ctx->patch_jump(patch);
  411. }else{
  412. expr->emit(ctx);
  413. ctx->emit(op1(), BC_NOARG, BC_KEEPLINE);
  414. }
  415. ctx->emit(OP_LOOP_CONTINUE, BC_NOARG, BC_KEEPLINE);
  416. ctx->exit_block();
  417. }
  418. };
  419. struct ListCompExpr: CompExpr{
  420. Opcode op0() override { return OP_BUILD_LIST; }
  421. Opcode op1() override { return OP_LIST_APPEND; }
  422. std::string str() const override { return "ListComp()"; }
  423. };
  424. struct DictCompExpr: CompExpr{
  425. Opcode op0() override { return OP_BUILD_DICT; }
  426. Opcode op1() override { return OP_DICT_ADD; }
  427. std::string str() const override { return "DictComp()"; }
  428. };
  429. struct SetCompExpr: CompExpr{
  430. Opcode op0() override { return OP_BUILD_SET; }
  431. Opcode op1() override { return OP_SET_ADD; }
  432. std::string str() const override { return "SetComp()"; }
  433. };
  434. struct LambdaExpr: Expr{
  435. FuncDecl_ decl;
  436. std::string str() const override { return "Lambda()"; }
  437. LambdaExpr(FuncDecl_ decl): decl(decl) {}
  438. void emit(CodeEmitContext* ctx) override {
  439. int index = ctx->add_func_decl(decl);
  440. ctx->emit(OP_LOAD_FUNCTION, index, line);
  441. }
  442. };
  443. struct FStringExpr: Expr{
  444. Str src;
  445. FStringExpr(const Str& src): src(src) {}
  446. std::string str() const override {
  447. return fmt("f", src.escape());
  448. }
  449. void _load_simple_expr(CodeEmitContext* ctx, Str expr){
  450. int dot = expr.index(".");
  451. if(dot < 0){
  452. ctx->emit(OP_LOAD_NAME, StrName(expr.sv()).index, line);
  453. }else{
  454. StrName name(expr.substr(0, dot).sv());
  455. StrName attr(expr.substr(dot+1).sv());
  456. ctx->emit(OP_LOAD_NAME, name.index, line);
  457. ctx->emit(OP_LOAD_ATTR, attr.index, line);
  458. }
  459. }
  460. void emit(CodeEmitContext* ctx) override {
  461. VM* vm = ctx->vm;
  462. static const std::regex pattern(R"(\{(.*?)\})");
  463. std::cregex_iterator begin(src.begin(), src.end(), pattern);
  464. std::cregex_iterator end;
  465. int size = 0;
  466. int i = 0;
  467. for(auto it = begin; it != end; it++) {
  468. std::cmatch m = *it;
  469. if (i < m.position()) {
  470. Str literal = src.substr(i, m.position() - i);
  471. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(literal)), line);
  472. size++;
  473. }
  474. Str expr = m[1].str();
  475. int conon = expr.index(":");
  476. if(conon >= 0){
  477. _load_simple_expr(ctx, expr.substr(0, conon));
  478. Str spec = expr.substr(conon+1);
  479. ctx->emit(OP_FORMAT_STRING, ctx->add_const(VAR(spec)), line);
  480. }else{
  481. _load_simple_expr(ctx, expr);
  482. }
  483. size++;
  484. i = (int)(m.position() + m.length());
  485. }
  486. if (i < src.length()) {
  487. Str literal = src.substr(i, src.length() - i);
  488. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(literal)), line);
  489. size++;
  490. }
  491. ctx->emit(OP_BUILD_STRING, size, line);
  492. }
  493. };
  494. struct SubscrExpr: Expr{
  495. Expr_ a;
  496. Expr_ b;
  497. std::string str() const override { return "Subscr()"; }
  498. void emit(CodeEmitContext* ctx) override{
  499. a->emit(ctx);
  500. b->emit(ctx);
  501. ctx->emit(OP_LOAD_SUBSCR, BC_NOARG, line);
  502. }
  503. bool emit_del(CodeEmitContext* ctx) override {
  504. a->emit(ctx);
  505. b->emit(ctx);
  506. ctx->emit(OP_DELETE_SUBSCR, BC_NOARG, line);
  507. return true;
  508. }
  509. bool emit_store(CodeEmitContext* ctx) override {
  510. a->emit(ctx);
  511. b->emit(ctx);
  512. ctx->emit(OP_STORE_SUBSCR, BC_NOARG, line);
  513. return true;
  514. }
  515. };
  516. struct AttribExpr: Expr{
  517. Expr_ a;
  518. Str b;
  519. AttribExpr(Expr_ a, const Str& b): a(std::move(a)), b(b) {}
  520. AttribExpr(Expr_ a, Str&& b): a(std::move(a)), b(std::move(b)) {}
  521. std::string str() const override { return "Attrib()"; }
  522. void emit(CodeEmitContext* ctx) override{
  523. a->emit(ctx);
  524. int index = StrName(b).index;
  525. ctx->emit(OP_LOAD_ATTR, index, line);
  526. }
  527. bool emit_del(CodeEmitContext* ctx) override {
  528. a->emit(ctx);
  529. int index = StrName(b).index;
  530. ctx->emit(OP_DELETE_ATTR, index, line);
  531. return true;
  532. }
  533. bool emit_store(CodeEmitContext* ctx) override {
  534. a->emit(ctx);
  535. int index = StrName(b).index;
  536. ctx->emit(OP_STORE_ATTR, index, line);
  537. return true;
  538. }
  539. void emit_method(CodeEmitContext* ctx) {
  540. a->emit(ctx);
  541. int index = StrName(b).index;
  542. ctx->emit(OP_LOAD_METHOD, index, line);
  543. }
  544. bool is_attrib() const override { return true; }
  545. };
  546. struct CallExpr: Expr{
  547. Expr_ callable;
  548. std::vector<Expr_> args;
  549. std::vector<std::pair<Str, Expr_>> kwargs;
  550. std::string str() const override { return "Call()"; }
  551. bool need_unpack() const {
  552. for(auto& item: args) if(item->is_starred()) return true;
  553. return false;
  554. }
  555. void emit(CodeEmitContext* ctx) override {
  556. VM* vm = ctx->vm;
  557. if(need_unpack()) ctx->emit(OP_BEGIN_CALL, BC_NOARG, line);
  558. // if callable is a AttrExpr, we should try to use `fast_call` instead of use `boundmethod` proxy
  559. if(callable->is_attrib()){
  560. auto p = static_cast<AttribExpr*>(callable.get());
  561. p->emit_method(ctx);
  562. }else{
  563. callable->emit(ctx);
  564. ctx->emit(OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  565. }
  566. // emit args
  567. for(auto& item: args) item->emit(ctx);
  568. // emit kwargs
  569. for(auto& item: kwargs){
  570. int index = StrName::get(item.first.sv()).index;
  571. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(index)), line);
  572. item.second->emit(ctx);
  573. }
  574. int KWARGC = (int)kwargs.size();
  575. int ARGC = (int)args.size();
  576. if(need_unpack()) ARGC = 0xFFFF;
  577. ctx->emit(OP_CALL, (KWARGC<<16)|ARGC, line);
  578. }
  579. };
  580. struct BinaryExpr: Expr{
  581. TokenIndex op;
  582. Expr_ lhs;
  583. Expr_ rhs;
  584. std::string str() const override { return TK_STR(op); }
  585. void emit(CodeEmitContext* ctx) override {
  586. lhs->emit(ctx);
  587. rhs->emit(ctx);
  588. switch (op) {
  589. case TK("+"): ctx->emit(OP_BINARY_ADD, BC_NOARG, line); break;
  590. case TK("-"): ctx->emit(OP_BINARY_SUB, BC_NOARG, line); break;
  591. case TK("*"): ctx->emit(OP_BINARY_MUL, BC_NOARG, line); break;
  592. case TK("/"): ctx->emit(OP_BINARY_TRUEDIV, BC_NOARG, line); break;
  593. case TK("//"): ctx->emit(OP_BINARY_FLOORDIV, BC_NOARG, line); break;
  594. case TK("%"): ctx->emit(OP_BINARY_MOD, BC_NOARG, line); break;
  595. case TK("**"): ctx->emit(OP_BINARY_POW, BC_NOARG, line); break;
  596. case TK("<"): ctx->emit(OP_COMPARE_LT, BC_NOARG, line); break;
  597. case TK("<="): ctx->emit(OP_COMPARE_LE, BC_NOARG, line); break;
  598. case TK("=="): ctx->emit(OP_COMPARE_EQ, BC_NOARG, line); break;
  599. case TK("!="): ctx->emit(OP_COMPARE_NE, BC_NOARG, line); break;
  600. case TK(">"): ctx->emit(OP_COMPARE_GT, BC_NOARG, line); break;
  601. case TK(">="): ctx->emit(OP_COMPARE_GE, BC_NOARG, line); break;
  602. case TK("in"): ctx->emit(OP_CONTAINS_OP, 0, line); break;
  603. case TK("not in"): ctx->emit(OP_CONTAINS_OP, 1, line); break;
  604. case TK("is"): ctx->emit(OP_IS_OP, 0, line); break;
  605. case TK("is not"): ctx->emit(OP_IS_OP, 1, line); break;
  606. case TK("<<"): ctx->emit(OP_BITWISE_LSHIFT, BC_NOARG, line); break;
  607. case TK(">>"): ctx->emit(OP_BITWISE_RSHIFT, BC_NOARG, line); break;
  608. case TK("&"): ctx->emit(OP_BITWISE_AND, BC_NOARG, line); break;
  609. case TK("|"): ctx->emit(OP_BITWISE_OR, BC_NOARG, line); break;
  610. case TK("^"): ctx->emit(OP_BITWISE_XOR, BC_NOARG, line); break;
  611. case TK("@"): ctx->emit(OP_BINARY_MATMUL, BC_NOARG, line); break;
  612. default: FATAL_ERROR();
  613. }
  614. }
  615. };
  616. struct TernaryExpr: Expr{
  617. Expr_ cond;
  618. Expr_ true_expr;
  619. Expr_ false_expr;
  620. std::string str() const override { return "Ternary()"; }
  621. void emit(CodeEmitContext* ctx) override {
  622. cond->emit(ctx);
  623. int patch = ctx->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, cond->line);
  624. true_expr->emit(ctx);
  625. int patch_2 = ctx->emit(OP_JUMP_ABSOLUTE, BC_NOARG, true_expr->line);
  626. ctx->patch_jump(patch);
  627. false_expr->emit(ctx);
  628. ctx->patch_jump(patch_2);
  629. }
  630. };
  631. } // namespace pkpy