expr.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. Bytecode& prev = ctx->co->codes.back();
  365. if(prev.op == OP_BUILD_TUPLE && prev.arg == items.size()){
  366. // build tuple and unpack it is meaningless
  367. prev.op = OP_NO_OP;
  368. prev.arg = BC_NOARG;
  369. }else{
  370. ctx->emit(OP_UNPACK_SEQUENCE, items.size(), line);
  371. }
  372. }else{
  373. // starred assignment target must be in a tuple
  374. if(items.size() == 1) return false;
  375. // starred assignment target must be the last one (differ from cpython)
  376. if(starred_i != items.size()-1) return false;
  377. // a,*b = [1,2,3]
  378. // stack is [1,2,3] -> [1,[2,3]]
  379. ctx->emit(OP_UNPACK_EX, items.size()-1, line);
  380. }
  381. // do reverse emit
  382. for(int i=items.size()-1; i>=0; i--){
  383. bool ok = items[i]->emit_store(ctx);
  384. if(!ok) return false;
  385. }
  386. return true;
  387. }
  388. bool emit_del(CodeEmitContext* ctx) override{
  389. for(auto& e: items){
  390. bool ok = e->emit_del(ctx);
  391. if(!ok) return false;
  392. }
  393. return true;
  394. }
  395. };
  396. struct CompExpr: Expr{
  397. Expr_ expr; // loop expr
  398. Expr_ vars; // loop vars
  399. Expr_ iter; // loop iter
  400. Expr_ cond; // optional if condition
  401. virtual Opcode op0() = 0;
  402. virtual Opcode op1() = 0;
  403. void emit(CodeEmitContext* ctx){
  404. ctx->emit(op0(), 0, line);
  405. iter->emit(ctx);
  406. ctx->emit(OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  407. ctx->enter_block(FOR_LOOP);
  408. ctx->emit(OP_FOR_ITER, BC_NOARG, BC_KEEPLINE);
  409. bool ok = vars->emit_store(ctx);
  410. // this error occurs in `vars` instead of this line, but...nevermind
  411. if(!ok) FATAL_ERROR(); // TODO: raise a SyntaxError instead
  412. if(cond){
  413. cond->emit(ctx);
  414. int patch = ctx->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  415. expr->emit(ctx);
  416. ctx->emit(op1(), BC_NOARG, BC_KEEPLINE);
  417. ctx->patch_jump(patch);
  418. }else{
  419. expr->emit(ctx);
  420. ctx->emit(op1(), BC_NOARG, BC_KEEPLINE);
  421. }
  422. ctx->emit(OP_LOOP_CONTINUE, BC_NOARG, BC_KEEPLINE);
  423. ctx->exit_block();
  424. }
  425. };
  426. struct ListCompExpr: CompExpr{
  427. Opcode op0() override { return OP_BUILD_LIST; }
  428. Opcode op1() override { return OP_LIST_APPEND; }
  429. std::string str() const override { return "ListComp()"; }
  430. };
  431. struct DictCompExpr: CompExpr{
  432. Opcode op0() override { return OP_BUILD_DICT; }
  433. Opcode op1() override { return OP_DICT_ADD; }
  434. std::string str() const override { return "DictComp()"; }
  435. };
  436. struct SetCompExpr: CompExpr{
  437. Opcode op0() override { return OP_BUILD_SET; }
  438. Opcode op1() override { return OP_SET_ADD; }
  439. std::string str() const override { return "SetComp()"; }
  440. };
  441. struct LambdaExpr: Expr{
  442. FuncDecl_ decl;
  443. std::string str() const override { return "Lambda()"; }
  444. LambdaExpr(FuncDecl_ decl): decl(decl) {}
  445. void emit(CodeEmitContext* ctx) override {
  446. int index = ctx->add_func_decl(decl);
  447. ctx->emit(OP_LOAD_FUNCTION, index, line);
  448. }
  449. };
  450. struct FStringExpr: Expr{
  451. Str src;
  452. FStringExpr(const Str& src): src(src) {}
  453. std::string str() const override {
  454. return fmt("f", src.escape());
  455. }
  456. void _load_simple_expr(CodeEmitContext* ctx, Str expr){
  457. int dot = expr.index(".");
  458. if(dot < 0){
  459. ctx->emit(OP_LOAD_NAME, StrName(expr.sv()).index, line);
  460. }else{
  461. StrName name(expr.substr(0, dot).sv());
  462. StrName attr(expr.substr(dot+1).sv());
  463. ctx->emit(OP_LOAD_NAME, name.index, line);
  464. ctx->emit(OP_LOAD_ATTR, attr.index, line);
  465. }
  466. }
  467. void emit(CodeEmitContext* ctx) override {
  468. VM* vm = ctx->vm;
  469. static const std::regex pattern(R"(\{(.*?)\})");
  470. std::cregex_iterator begin(src.begin(), src.end(), pattern);
  471. std::cregex_iterator end;
  472. int size = 0;
  473. int i = 0;
  474. for(auto it = begin; it != end; it++) {
  475. std::cmatch m = *it;
  476. if (i < m.position()) {
  477. Str literal = src.substr(i, m.position() - i);
  478. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(literal)), line);
  479. size++;
  480. }
  481. Str expr = m[1].str();
  482. int conon = expr.index(":");
  483. if(conon >= 0){
  484. _load_simple_expr(ctx, expr.substr(0, conon));
  485. Str spec = expr.substr(conon+1);
  486. ctx->emit(OP_FORMAT_STRING, ctx->add_const(VAR(spec)), line);
  487. }else{
  488. _load_simple_expr(ctx, expr);
  489. }
  490. size++;
  491. i = (int)(m.position() + m.length());
  492. }
  493. if (i < src.length()) {
  494. Str literal = src.substr(i, src.length() - i);
  495. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(literal)), line);
  496. size++;
  497. }
  498. ctx->emit(OP_BUILD_STRING, size, line);
  499. }
  500. };
  501. struct SubscrExpr: Expr{
  502. Expr_ a;
  503. Expr_ b;
  504. std::string str() const override { return "Subscr()"; }
  505. void emit(CodeEmitContext* ctx) override{
  506. a->emit(ctx);
  507. b->emit(ctx);
  508. ctx->emit(OP_LOAD_SUBSCR, BC_NOARG, line);
  509. }
  510. bool emit_del(CodeEmitContext* ctx) override {
  511. a->emit(ctx);
  512. b->emit(ctx);
  513. ctx->emit(OP_DELETE_SUBSCR, BC_NOARG, line);
  514. return true;
  515. }
  516. bool emit_store(CodeEmitContext* ctx) override {
  517. a->emit(ctx);
  518. b->emit(ctx);
  519. ctx->emit(OP_STORE_SUBSCR, BC_NOARG, line);
  520. return true;
  521. }
  522. };
  523. struct AttribExpr: Expr{
  524. Expr_ a;
  525. Str b;
  526. AttribExpr(Expr_ a, const Str& b): a(std::move(a)), b(b) {}
  527. AttribExpr(Expr_ a, Str&& b): a(std::move(a)), b(std::move(b)) {}
  528. std::string str() const override { return "Attrib()"; }
  529. void emit(CodeEmitContext* ctx) override{
  530. a->emit(ctx);
  531. int index = StrName(b).index;
  532. ctx->emit(OP_LOAD_ATTR, index, line);
  533. }
  534. bool emit_del(CodeEmitContext* ctx) override {
  535. a->emit(ctx);
  536. int index = StrName(b).index;
  537. ctx->emit(OP_DELETE_ATTR, index, line);
  538. return true;
  539. }
  540. bool emit_store(CodeEmitContext* ctx) override {
  541. a->emit(ctx);
  542. int index = StrName(b).index;
  543. ctx->emit(OP_STORE_ATTR, index, line);
  544. return true;
  545. }
  546. void emit_method(CodeEmitContext* ctx) {
  547. a->emit(ctx);
  548. int index = StrName(b).index;
  549. ctx->emit(OP_LOAD_METHOD, index, line);
  550. }
  551. bool is_attrib() const override { return true; }
  552. };
  553. struct CallExpr: Expr{
  554. Expr_ callable;
  555. std::vector<Expr_> args;
  556. std::vector<std::pair<Str, Expr_>> kwargs;
  557. std::string str() const override { return "Call()"; }
  558. bool need_unpack() const {
  559. for(auto& item: args) if(item->is_starred()) return true;
  560. return false;
  561. }
  562. void emit(CodeEmitContext* ctx) override {
  563. VM* vm = ctx->vm;
  564. if(need_unpack()) ctx->emit(OP_BEGIN_CALL, BC_NOARG, line);
  565. // if callable is a AttrExpr, we should try to use `fast_call` instead of use `boundmethod` proxy
  566. if(callable->is_attrib()){
  567. auto p = static_cast<AttribExpr*>(callable.get());
  568. p->emit_method(ctx);
  569. }else{
  570. callable->emit(ctx);
  571. ctx->emit(OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  572. }
  573. // emit args
  574. for(auto& item: args) item->emit(ctx);
  575. // emit kwargs
  576. for(auto& item: kwargs){
  577. int index = StrName::get(item.first.sv()).index;
  578. ctx->emit(OP_LOAD_CONST, ctx->add_const(VAR(index)), line);
  579. item.second->emit(ctx);
  580. }
  581. int KWARGC = (int)kwargs.size();
  582. int ARGC = (int)args.size();
  583. if(need_unpack()) ARGC = 0xFFFF;
  584. ctx->emit(OP_CALL, (KWARGC<<16)|ARGC, line);
  585. }
  586. };
  587. struct BinaryExpr: Expr{
  588. TokenIndex op;
  589. Expr_ lhs;
  590. Expr_ rhs;
  591. std::string str() const override { return TK_STR(op); }
  592. void emit(CodeEmitContext* ctx) override {
  593. lhs->emit(ctx);
  594. rhs->emit(ctx);
  595. switch (op) {
  596. case TK("+"): ctx->emit(OP_BINARY_ADD, BC_NOARG, line); break;
  597. case TK("-"): ctx->emit(OP_BINARY_SUB, BC_NOARG, line); break;
  598. case TK("*"): ctx->emit(OP_BINARY_MUL, BC_NOARG, line); break;
  599. case TK("/"): ctx->emit(OP_BINARY_TRUEDIV, BC_NOARG, line); break;
  600. case TK("//"): ctx->emit(OP_BINARY_FLOORDIV, BC_NOARG, line); break;
  601. case TK("%"): ctx->emit(OP_BINARY_MOD, BC_NOARG, line); break;
  602. case TK("**"): ctx->emit(OP_BINARY_POW, BC_NOARG, line); break;
  603. case TK("<"): ctx->emit(OP_COMPARE_LT, BC_NOARG, line); break;
  604. case TK("<="): ctx->emit(OP_COMPARE_LE, BC_NOARG, line); break;
  605. case TK("=="): ctx->emit(OP_COMPARE_EQ, BC_NOARG, line); break;
  606. case TK("!="): ctx->emit(OP_COMPARE_NE, BC_NOARG, line); break;
  607. case TK(">"): ctx->emit(OP_COMPARE_GT, BC_NOARG, line); break;
  608. case TK(">="): ctx->emit(OP_COMPARE_GE, BC_NOARG, line); break;
  609. case TK("in"): ctx->emit(OP_CONTAINS_OP, 0, line); break;
  610. case TK("not in"): ctx->emit(OP_CONTAINS_OP, 1, line); break;
  611. case TK("is"): ctx->emit(OP_IS_OP, 0, line); break;
  612. case TK("is not"): ctx->emit(OP_IS_OP, 1, line); break;
  613. case TK("<<"): ctx->emit(OP_BITWISE_LSHIFT, BC_NOARG, line); break;
  614. case TK(">>"): ctx->emit(OP_BITWISE_RSHIFT, BC_NOARG, line); break;
  615. case TK("&"): ctx->emit(OP_BITWISE_AND, BC_NOARG, line); break;
  616. case TK("|"): ctx->emit(OP_BITWISE_OR, BC_NOARG, line); break;
  617. case TK("^"): ctx->emit(OP_BITWISE_XOR, BC_NOARG, line); break;
  618. case TK("@"): ctx->emit(OP_BINARY_MATMUL, BC_NOARG, line); break;
  619. default: FATAL_ERROR();
  620. }
  621. }
  622. };
  623. struct TernaryExpr: Expr{
  624. Expr_ cond;
  625. Expr_ true_expr;
  626. Expr_ false_expr;
  627. std::string str() const override { return "Ternary()"; }
  628. void emit(CodeEmitContext* ctx) override {
  629. cond->emit(ctx);
  630. int patch = ctx->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, cond->line);
  631. true_expr->emit(ctx);
  632. int patch_2 = ctx->emit(OP_JUMP_ABSOLUTE, BC_NOARG, true_expr->line);
  633. ctx->patch_jump(patch);
  634. false_expr->emit(ctx);
  635. ctx->patch_jump(patch_2);
  636. }
  637. };
  638. } // namespace pkpy