expr.h 22 KB

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