expr.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. #include "pocketpy/expr.h"
  2. namespace pkpy{
  3. inline bool is_identifier(std::string_view s){
  4. if(s.empty()) return false;
  5. if(!isalpha(s[0]) && s[0] != '_') return false;
  6. for(char c: s) if(!isalnum(c) && c != '_') return false;
  7. return true;
  8. }
  9. int CodeEmitContext::get_loop() const {
  10. int index = curr_block_i;
  11. while(index >= 0){
  12. if(co->blocks[index].type == CodeBlockType::FOR_LOOP) break;
  13. if(co->blocks[index].type == CodeBlockType::WHILE_LOOP) break;
  14. index = co->blocks[index].parent;
  15. }
  16. return index;
  17. }
  18. CodeBlock* CodeEmitContext::enter_block(CodeBlockType type){
  19. if(type==CodeBlockType::FOR_LOOP || type==CodeBlockType::CONTEXT_MANAGER) base_stack_size++;
  20. co->blocks.push_back(CodeBlock(
  21. type, curr_block_i, base_stack_size, (int)co->codes.size()
  22. ));
  23. curr_block_i = co->blocks.size()-1;
  24. return &co->blocks[curr_block_i];
  25. }
  26. void CodeEmitContext::exit_block(){
  27. auto curr_type = co->blocks[curr_block_i].type;
  28. if(curr_type == CodeBlockType::FOR_LOOP || curr_type==CodeBlockType::CONTEXT_MANAGER) base_stack_size--;
  29. co->blocks[curr_block_i].end = co->codes.size();
  30. curr_block_i = co->blocks[curr_block_i].parent;
  31. if(curr_block_i < 0) PK_FATAL_ERROR();
  32. if(curr_type == CodeBlockType::FOR_LOOP){
  33. // add a no op here to make block check work
  34. emit_(OP_NO_OP, BC_NOARG, BC_KEEPLINE, true);
  35. }
  36. }
  37. // clear the expression stack and generate bytecode
  38. void CodeEmitContext::emit_expr(){
  39. if(s_expr.size() != 1) throw std::runtime_error("s_expr.size() != 1");
  40. Expr_ expr = s_expr.popx();
  41. expr->emit_(this);
  42. }
  43. int CodeEmitContext::emit_(Opcode opcode, uint16_t arg, int line, bool is_virtual) {
  44. co->codes.push_back(Bytecode{(uint8_t)opcode, arg});
  45. co->iblocks.push_back(curr_block_i);
  46. co->lines.push_back(CodeObject::LineInfo{line, is_virtual});
  47. int i = co->codes.size() - 1;
  48. if(line == BC_KEEPLINE){
  49. if(i >= 1) co->lines[i].lineno = co->lines[i-1].lineno;
  50. else co->lines[i].lineno = 1;
  51. }
  52. return i;
  53. }
  54. void CodeEmitContext::revert_last_emit_(){
  55. co->codes.pop_back();
  56. co->iblocks.pop_back();
  57. co->lines.pop_back();
  58. }
  59. void CodeEmitContext::try_merge_for_iter_store(int i){
  60. // [FOR_ITER, STORE_?, ]
  61. if(co->codes[i].op != OP_FOR_ITER) return;
  62. if(co->codes.size() - i != 2) return;
  63. uint16_t arg = co->codes[i+1].arg;
  64. if(co->codes[i+1].op == OP_STORE_FAST){
  65. revert_last_emit_();
  66. co->codes[i].op = OP_FOR_ITER_STORE_FAST;
  67. co->codes[i].arg = arg;
  68. return;
  69. }
  70. if(co->codes[i+1].op == OP_STORE_GLOBAL){
  71. revert_last_emit_();
  72. co->codes[i].op = OP_FOR_ITER_STORE_GLOBAL;
  73. co->codes[i].arg = arg;
  74. return;
  75. }
  76. }
  77. int CodeEmitContext::emit_int(i64 value, int line){
  78. bool allow_neg_int = is_negative_shift_well_defined() || value >= 0;
  79. if(allow_neg_int && value >= -5 && value <= 16){
  80. uint8_t op = OP_LOAD_INT_NEG_5 + (uint8_t)value + 5;
  81. return emit_((Opcode)op, BC_NOARG, line);
  82. }else{
  83. return emit_(OP_LOAD_CONST, add_const(VAR(value)), line);
  84. }
  85. }
  86. void CodeEmitContext::patch_jump(int index) {
  87. int target = co->codes.size();
  88. co->codes[index].arg = target;
  89. }
  90. bool CodeEmitContext::add_label(StrName name){
  91. if(co->labels.contains(name)) return false;
  92. co->labels.set(name, co->codes.size());
  93. return true;
  94. }
  95. int CodeEmitContext::add_varname(StrName name){
  96. // PK_MAX_CO_VARNAMES will be checked when pop_context(), not here
  97. int index = co->varnames_inv.try_get(name);
  98. if(index >= 0) return index;
  99. co->varnames.push_back(name);
  100. index = co->varnames.size() - 1;
  101. co->varnames_inv.set(name, index);
  102. return index;
  103. }
  104. int CodeEmitContext::add_const_string(std::string_view key){
  105. auto it = _co_consts_string_dedup_map.find(key);
  106. if(it != _co_consts_string_dedup_map.end()){
  107. return it->second;
  108. }else{
  109. co->consts.push_back(VAR(key));
  110. int index = co->consts.size() - 1;
  111. _co_consts_string_dedup_map[std::string(key)] = index;
  112. return index;
  113. }
  114. }
  115. int CodeEmitContext::add_const(PyObject* v){
  116. if(is_type(v, vm->tp_str)){
  117. // warning: should use add_const_string() instead
  118. return add_const_string(PK_OBJ_GET(Str, v).sv());
  119. }else{
  120. // non-string deduplication
  121. auto it = _co_consts_nonstring_dedup_map.find(v);
  122. if(it != _co_consts_nonstring_dedup_map.end()){
  123. return it->second;
  124. }else{
  125. co->consts.push_back(v);
  126. int index = co->consts.size() - 1;
  127. _co_consts_nonstring_dedup_map[v] = index;
  128. return index;
  129. }
  130. }
  131. PK_UNREACHABLE()
  132. }
  133. int CodeEmitContext::add_func_decl(FuncDecl_ decl){
  134. co->func_decls.push_back(decl);
  135. return co->func_decls.size() - 1;
  136. }
  137. void CodeEmitContext::emit_store_name(NameScope scope, StrName name, int line){
  138. switch(scope){
  139. case NAME_LOCAL:
  140. emit_(OP_STORE_FAST, add_varname(name), line);
  141. break;
  142. case NAME_GLOBAL:
  143. emit_(OP_STORE_GLOBAL, StrName(name).index, line);
  144. break;
  145. case NAME_GLOBAL_UNKNOWN:
  146. emit_(OP_STORE_NAME, StrName(name).index, line);
  147. break;
  148. default: PK_FATAL_ERROR(); break;
  149. }
  150. }
  151. void NameExpr::emit_(CodeEmitContext* ctx) {
  152. int index = ctx->co->varnames_inv.try_get(name);
  153. if(scope == NAME_LOCAL && index >= 0){
  154. ctx->emit_(OP_LOAD_FAST, index, line);
  155. }else{
  156. Opcode op = ctx->level <= 1 ? OP_LOAD_GLOBAL : OP_LOAD_NONLOCAL;
  157. if(ctx->is_compiling_class && scope == NAME_GLOBAL){
  158. // if we are compiling a class, we should use OP_LOAD_ATTR_GLOBAL instead of OP_LOAD_GLOBAL
  159. // this supports @property.setter
  160. op = OP_LOAD_CLASS_GLOBAL;
  161. // exec()/eval() won't work with OP_LOAD_ATTR_GLOBAL in class body
  162. }else{
  163. // we cannot determine the scope when calling exec()/eval()
  164. if(scope == NAME_GLOBAL_UNKNOWN) op = OP_LOAD_NAME;
  165. }
  166. ctx->emit_(op, StrName(name).index, line);
  167. }
  168. }
  169. bool NameExpr::emit_del(CodeEmitContext* ctx) {
  170. switch(scope){
  171. case NAME_LOCAL:
  172. ctx->emit_(OP_DELETE_FAST, ctx->add_varname(name), line);
  173. break;
  174. case NAME_GLOBAL:
  175. ctx->emit_(OP_DELETE_GLOBAL, StrName(name).index, line);
  176. break;
  177. case NAME_GLOBAL_UNKNOWN:
  178. ctx->emit_(OP_DELETE_NAME, StrName(name).index, line);
  179. break;
  180. default: PK_FATAL_ERROR(); break;
  181. }
  182. return true;
  183. }
  184. bool NameExpr::emit_store(CodeEmitContext* ctx) {
  185. if(ctx->is_compiling_class){
  186. ctx->emit_(OP_STORE_CLASS_ATTR, name.index, line);
  187. return true;
  188. }
  189. ctx->emit_store_name(scope, name, line);
  190. return true;
  191. }
  192. void InvertExpr::emit_(CodeEmitContext* ctx) {
  193. child->emit_(ctx);
  194. ctx->emit_(OP_UNARY_INVERT, BC_NOARG, line);
  195. }
  196. void StarredExpr::emit_(CodeEmitContext* ctx) {
  197. child->emit_(ctx);
  198. ctx->emit_(OP_UNARY_STAR, level, line);
  199. }
  200. bool StarredExpr::emit_store(CodeEmitContext* ctx) {
  201. if(level != 1) return false;
  202. // simply proxy to child
  203. return child->emit_store(ctx);
  204. }
  205. void NotExpr::emit_(CodeEmitContext* ctx) {
  206. child->emit_(ctx);
  207. ctx->emit_(OP_UNARY_NOT, BC_NOARG, line);
  208. }
  209. void AndExpr::emit_(CodeEmitContext* ctx) {
  210. lhs->emit_(ctx);
  211. int patch = ctx->emit_(OP_JUMP_IF_FALSE_OR_POP, BC_NOARG, line);
  212. rhs->emit_(ctx);
  213. ctx->patch_jump(patch);
  214. }
  215. void OrExpr::emit_(CodeEmitContext* ctx) {
  216. lhs->emit_(ctx);
  217. int patch = ctx->emit_(OP_JUMP_IF_TRUE_OR_POP, BC_NOARG, line);
  218. rhs->emit_(ctx);
  219. ctx->patch_jump(patch);
  220. }
  221. void Literal0Expr::emit_(CodeEmitContext* ctx){
  222. switch (token) {
  223. case TK("None"): ctx->emit_(OP_LOAD_NONE, BC_NOARG, line); break;
  224. case TK("True"): ctx->emit_(OP_LOAD_TRUE, BC_NOARG, line); break;
  225. case TK("False"): ctx->emit_(OP_LOAD_FALSE, BC_NOARG, line); break;
  226. case TK("..."): ctx->emit_(OP_LOAD_ELLIPSIS, BC_NOARG, line); break;
  227. default: PK_FATAL_ERROR();
  228. }
  229. }
  230. void LongExpr::emit_(CodeEmitContext* ctx) {
  231. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string(s.sv()), line);
  232. ctx->emit_(OP_BUILD_LONG, BC_NOARG, line);
  233. }
  234. void ImagExpr::emit_(CodeEmitContext* ctx) {
  235. VM* vm = ctx->vm;
  236. ctx->emit_(OP_LOAD_CONST, ctx->add_const(VAR(value)), line);
  237. ctx->emit_(OP_BUILD_IMAG, BC_NOARG, line);
  238. }
  239. void BytesExpr::emit_(CodeEmitContext* ctx) {
  240. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string(s.sv()), line);
  241. ctx->emit_(OP_BUILD_BYTES, BC_NOARG, line);
  242. }
  243. void LiteralExpr::emit_(CodeEmitContext* ctx) {
  244. VM* vm = ctx->vm;
  245. if(std::holds_alternative<i64>(value)){
  246. i64 _val = std::get<i64>(value);
  247. ctx->emit_int(_val, line);
  248. return;
  249. }
  250. if(std::holds_alternative<f64>(value)){
  251. f64 _val = std::get<f64>(value);
  252. ctx->emit_(OP_LOAD_CONST, ctx->add_const(VAR(_val)), line);
  253. return;
  254. }
  255. if(std::holds_alternative<Str>(value)){
  256. std::string_view key = std::get<Str>(value).sv();
  257. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string(key), line);
  258. return;
  259. }
  260. }
  261. void NegatedExpr::emit_(CodeEmitContext* ctx){
  262. VM* vm = ctx->vm;
  263. // if child is a int of float, do constant folding
  264. if(child->is_literal()){
  265. LiteralExpr* lit = static_cast<LiteralExpr*>(child.get());
  266. if(std::holds_alternative<i64>(lit->value)){
  267. i64 _val = -std::get<i64>(lit->value);
  268. ctx->emit_int(_val, line);
  269. return;
  270. }
  271. if(std::holds_alternative<f64>(lit->value)){
  272. f64 _val = -std::get<f64>(lit->value);
  273. ctx->emit_(OP_LOAD_CONST, ctx->add_const(VAR(_val)), line);
  274. return;
  275. }
  276. }
  277. child->emit_(ctx);
  278. ctx->emit_(OP_UNARY_NEGATIVE, BC_NOARG, line);
  279. }
  280. void SliceExpr::emit_(CodeEmitContext* ctx){
  281. if(start){
  282. start->emit_(ctx);
  283. }else{
  284. ctx->emit_(OP_LOAD_NONE, BC_NOARG, line);
  285. }
  286. if(stop){
  287. stop->emit_(ctx);
  288. }else{
  289. ctx->emit_(OP_LOAD_NONE, BC_NOARG, line);
  290. }
  291. if(step){
  292. step->emit_(ctx);
  293. }else{
  294. ctx->emit_(OP_LOAD_NONE, BC_NOARG, line);
  295. }
  296. ctx->emit_(OP_BUILD_SLICE, BC_NOARG, line);
  297. }
  298. void DictItemExpr::emit_(CodeEmitContext* ctx) {
  299. if(is_starred()){
  300. PK_ASSERT(key == nullptr);
  301. value->emit_(ctx);
  302. }else{
  303. value->emit_(ctx);
  304. key->emit_(ctx); // reverse order
  305. ctx->emit_(OP_BUILD_TUPLE, 2, line);
  306. }
  307. }
  308. bool TupleExpr::emit_store(CodeEmitContext* ctx) {
  309. // TOS is an iterable
  310. // items may contain StarredExpr, we should check it
  311. int starred_i = -1;
  312. for(int i=0; i<items.size(); i++){
  313. if(!items[i]->is_starred()) continue;
  314. if(starred_i == -1) starred_i = i;
  315. else return false; // multiple StarredExpr not allowed
  316. }
  317. if(starred_i == -1){
  318. Bytecode& prev = ctx->co->codes.back();
  319. if(prev.op == OP_BUILD_TUPLE && prev.arg == items.size()){
  320. // build tuple and unpack it is meaningless
  321. prev.op = OP_NO_OP;
  322. prev.arg = BC_NOARG;
  323. }else{
  324. ctx->emit_(OP_UNPACK_SEQUENCE, items.size(), line);
  325. }
  326. }else{
  327. // starred assignment target must be in a tuple
  328. if(items.size() == 1) return false;
  329. // starred assignment target must be the last one (differ from cpython)
  330. if(starred_i != items.size()-1) return false;
  331. // a,*b = [1,2,3]
  332. // stack is [1,2,3] -> [1,[2,3]]
  333. ctx->emit_(OP_UNPACK_EX, items.size()-1, line);
  334. }
  335. // do reverse emit
  336. for(int i=items.size()-1; i>=0; i--){
  337. bool ok = items[i]->emit_store(ctx);
  338. if(!ok) return false;
  339. }
  340. return true;
  341. }
  342. bool TupleExpr::emit_del(CodeEmitContext* ctx){
  343. for(auto& e: items){
  344. bool ok = e->emit_del(ctx);
  345. if(!ok) return false;
  346. }
  347. return true;
  348. }
  349. void CompExpr::emit_(CodeEmitContext* ctx){
  350. ctx->emit_(op0(), 0, line);
  351. iter->emit_(ctx);
  352. ctx->emit_(OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  353. ctx->enter_block(CodeBlockType::FOR_LOOP);
  354. int for_codei = ctx->emit_(OP_FOR_ITER, BC_NOARG, BC_KEEPLINE);
  355. bool ok = vars->emit_store(ctx);
  356. // this error occurs in `vars` instead of this line, but...nevermind
  357. PK_ASSERT(ok); // TODO: raise a SyntaxError instead
  358. ctx->try_merge_for_iter_store(for_codei);
  359. if(cond){
  360. cond->emit_(ctx);
  361. int patch = ctx->emit_(OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  362. expr->emit_(ctx);
  363. ctx->emit_(op1(), BC_NOARG, BC_KEEPLINE);
  364. ctx->patch_jump(patch);
  365. }else{
  366. expr->emit_(ctx);
  367. ctx->emit_(op1(), BC_NOARG, BC_KEEPLINE);
  368. }
  369. ctx->emit_(OP_LOOP_CONTINUE, ctx->get_loop(), BC_KEEPLINE);
  370. ctx->exit_block();
  371. }
  372. void FStringExpr::_load_simple_expr(CodeEmitContext* ctx, Str expr){
  373. bool repr = false;
  374. if(expr.size>=2 && expr.end()[-2]=='!'){
  375. switch(expr.end()[-1]){
  376. case 'r': repr = true; expr = expr.substr(0, expr.size-2); break;
  377. case 's': repr = false; expr = expr.substr(0, expr.size-2); break;
  378. default: break; // nothing happens
  379. }
  380. }
  381. // name or name.name
  382. bool is_fastpath = false;
  383. if(is_identifier(expr.sv())){
  384. ctx->emit_(OP_LOAD_NAME, StrName(expr.sv()).index, line);
  385. is_fastpath = true;
  386. }else{
  387. int dot = expr.index(".");
  388. if(dot > 0){
  389. std::string_view a = expr.sv().substr(0, dot);
  390. std::string_view b = expr.sv().substr(dot+1);
  391. if(is_identifier(a) && is_identifier(b)){
  392. ctx->emit_(OP_LOAD_NAME, StrName(a).index, line);
  393. ctx->emit_(OP_LOAD_ATTR, StrName(b).index, line);
  394. is_fastpath = true;
  395. }
  396. }
  397. }
  398. if(!is_fastpath){
  399. int index = ctx->add_const_string(expr.sv());
  400. ctx->emit_(OP_FSTRING_EVAL, index, line);
  401. }
  402. if(repr){
  403. ctx->emit_(OP_REPR, BC_NOARG, line);
  404. }
  405. }
  406. void FStringExpr::emit_(CodeEmitContext* ctx){
  407. int i = 0; // left index
  408. int j = 0; // right index
  409. int count = 0; // how many string parts
  410. bool flag = false; // true if we are in a expression
  411. const char* fmt_valid_chars = "0-=*#@!~" "<>^" ".fds" "0123456789";
  412. PK_LOCAL_STATIC const std::set<char> fmt_valid_char_set(fmt_valid_chars, fmt_valid_chars + strlen(fmt_valid_chars));
  413. while(j < src.size){
  414. if(flag){
  415. if(src[j] == '}'){
  416. // add expression
  417. Str expr = src.substr(i, j-i);
  418. // BUG: ':' is not a format specifier in f"{stack[2:]}"
  419. int conon = expr.index(":");
  420. if(conon >= 0){
  421. Str spec = expr.substr(conon+1);
  422. // filter some invalid spec
  423. bool ok = true;
  424. for(char c: spec) if(!fmt_valid_char_set.count(c)){ ok = false; break; }
  425. if(ok){
  426. _load_simple_expr(ctx, expr.substr(0, conon));
  427. ctx->emit_(OP_FORMAT_STRING, ctx->add_const_string(spec.sv()), line);
  428. }else{
  429. // ':' is not a spec indicator
  430. _load_simple_expr(ctx, expr);
  431. }
  432. }else{
  433. _load_simple_expr(ctx, expr);
  434. }
  435. flag = false;
  436. count++;
  437. }
  438. }else{
  439. if(src[j] == '{'){
  440. // look at next char
  441. if(j+1 < src.size && src[j+1] == '{'){
  442. // {{ -> {
  443. j++;
  444. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string("{"), line);
  445. count++;
  446. }else{
  447. // { -> }
  448. flag = true;
  449. i = j+1;
  450. }
  451. }else if(src[j] == '}'){
  452. // look at next char
  453. if(j+1 < src.size && src[j+1] == '}'){
  454. // }} -> }
  455. j++;
  456. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string("}"), line);
  457. count++;
  458. }else{
  459. // } -> error
  460. // throw std::runtime_error("f-string: unexpected }");
  461. // just ignore
  462. }
  463. }else{
  464. // literal
  465. i = j;
  466. while(j < src.size && src[j] != '{' && src[j] != '}') j++;
  467. Str literal = src.substr(i, j-i);
  468. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string(literal.sv()), line);
  469. count++;
  470. continue; // skip j++
  471. }
  472. }
  473. j++;
  474. }
  475. if(flag){
  476. // literal
  477. Str literal = src.substr(i, src.size-i);
  478. ctx->emit_(OP_LOAD_CONST, ctx->add_const_string(literal.sv()), line);
  479. count++;
  480. }
  481. ctx->emit_(OP_BUILD_STRING, count, line);
  482. }
  483. void SubscrExpr::emit_(CodeEmitContext* ctx){
  484. a->emit_(ctx);
  485. b->emit_(ctx);
  486. ctx->emit_(OP_LOAD_SUBSCR, BC_NOARG, line);
  487. }
  488. bool SubscrExpr::emit_del(CodeEmitContext* ctx){
  489. a->emit_(ctx);
  490. b->emit_(ctx);
  491. ctx->emit_(OP_DELETE_SUBSCR, BC_NOARG, line);
  492. return true;
  493. }
  494. bool SubscrExpr::emit_store(CodeEmitContext* ctx){
  495. a->emit_(ctx);
  496. b->emit_(ctx);
  497. ctx->emit_(OP_STORE_SUBSCR, BC_NOARG, line);
  498. return true;
  499. }
  500. void AttribExpr::emit_(CodeEmitContext* ctx){
  501. a->emit_(ctx);
  502. ctx->emit_(OP_LOAD_ATTR, b.index, line);
  503. }
  504. bool AttribExpr::emit_del(CodeEmitContext* ctx) {
  505. a->emit_(ctx);
  506. ctx->emit_(OP_DELETE_ATTR, b.index, line);
  507. return true;
  508. }
  509. bool AttribExpr::emit_store(CodeEmitContext* ctx){
  510. a->emit_(ctx);
  511. ctx->emit_(OP_STORE_ATTR, b.index, line);
  512. return true;
  513. }
  514. void AttribExpr::emit_method(CodeEmitContext* ctx) {
  515. a->emit_(ctx);
  516. ctx->emit_(OP_LOAD_METHOD, b.index, line);
  517. }
  518. void CallExpr::emit_(CodeEmitContext* ctx) {
  519. bool vargs = false;
  520. bool vkwargs = false;
  521. for(auto& arg: args) if(arg->is_starred()) vargs = true;
  522. for(auto& item: kwargs) if(item.second->is_starred()) vkwargs = true;
  523. // if callable is a AttrExpr, we should try to use `fast_call` instead of use `boundmethod` proxy
  524. if(callable->is_attrib()){
  525. auto p = static_cast<AttribExpr*>(callable.get());
  526. p->emit_method(ctx); // OP_LOAD_METHOD
  527. }else{
  528. callable->emit_(ctx);
  529. ctx->emit_(OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  530. }
  531. if(vargs || vkwargs){
  532. for(auto& item: args) item->emit_(ctx);
  533. ctx->emit_(OP_BUILD_TUPLE_UNPACK, (uint16_t)args.size(), line);
  534. if(!kwargs.empty()){
  535. for(auto& item: kwargs){
  536. if(item.second->is_starred()){
  537. PK_ASSERT(item.second->star_level() == 2)
  538. item.second->emit_(ctx);
  539. }else{
  540. // k=v
  541. int index = ctx->add_const_string(item.first.sv());
  542. ctx->emit_(OP_LOAD_CONST, index, line);
  543. item.second->emit_(ctx);
  544. ctx->emit_(OP_BUILD_TUPLE, 2, line);
  545. }
  546. }
  547. ctx->emit_(OP_BUILD_DICT_UNPACK, (int)kwargs.size(), line);
  548. ctx->emit_(OP_CALL_TP, 1, line);
  549. }else{
  550. ctx->emit_(OP_CALL_TP, 0, line);
  551. }
  552. }else{
  553. // vectorcall protocol
  554. for(auto& item: args) item->emit_(ctx);
  555. for(auto& item: kwargs){
  556. i64 _val = StrName(item.first.sv()).index;
  557. ctx->emit_int(_val, line);
  558. item.second->emit_(ctx);
  559. }
  560. int KWARGC = kwargs.size();
  561. int ARGC = args.size();
  562. ctx->emit_(OP_CALL, (KWARGC<<8)|ARGC, line);
  563. }
  564. }
  565. bool BinaryExpr::is_compare() const {
  566. switch(op){
  567. case TK("<"): case TK("<="): case TK("=="):
  568. case TK("!="): case TK(">"): case TK(">="): return true;
  569. default: return false;
  570. }
  571. }
  572. void BinaryExpr::_emit_compare(CodeEmitContext* ctx, pod_vector<int>& jmps){
  573. if(lhs->is_compare()){
  574. static_cast<BinaryExpr*>(lhs.get())->_emit_compare(ctx, jmps);
  575. }else{
  576. lhs->emit_(ctx); // [a]
  577. }
  578. rhs->emit_(ctx); // [a, b]
  579. ctx->emit_(OP_DUP_TOP, BC_NOARG, line); // [a, b, b]
  580. ctx->emit_(OP_ROT_THREE, BC_NOARG, line); // [b, a, b]
  581. switch(op){
  582. case TK("<"): ctx->emit_(OP_COMPARE_LT, BC_NOARG, line); break;
  583. case TK("<="): ctx->emit_(OP_COMPARE_LE, BC_NOARG, line); break;
  584. case TK("=="): ctx->emit_(OP_COMPARE_EQ, BC_NOARG, line); break;
  585. case TK("!="): ctx->emit_(OP_COMPARE_NE, BC_NOARG, line); break;
  586. case TK(">"): ctx->emit_(OP_COMPARE_GT, BC_NOARG, line); break;
  587. case TK(">="): ctx->emit_(OP_COMPARE_GE, BC_NOARG, line); break;
  588. default: PK_UNREACHABLE()
  589. }
  590. // [b, RES]
  591. int index = ctx->emit_(OP_SHORTCUT_IF_FALSE_OR_POP, BC_NOARG, line);
  592. jmps.push_back(index);
  593. }
  594. void BinaryExpr::emit_(CodeEmitContext* ctx) {
  595. pod_vector<int> jmps;
  596. if(is_compare() && lhs->is_compare()){
  597. // (a < b) < c
  598. static_cast<BinaryExpr*>(lhs.get())->_emit_compare(ctx, jmps);
  599. // [b, RES]
  600. }else{
  601. // (1 + 2) < c
  602. lhs->emit_(ctx);
  603. }
  604. rhs->emit_(ctx);
  605. switch (op) {
  606. case TK("+"): ctx->emit_(OP_BINARY_ADD, BC_NOARG, line); break;
  607. case TK("-"): ctx->emit_(OP_BINARY_SUB, BC_NOARG, line); break;
  608. case TK("*"): ctx->emit_(OP_BINARY_MUL, BC_NOARG, line); break;
  609. case TK("/"): ctx->emit_(OP_BINARY_TRUEDIV, BC_NOARG, line); break;
  610. case TK("//"): ctx->emit_(OP_BINARY_FLOORDIV, BC_NOARG, line); break;
  611. case TK("%"): ctx->emit_(OP_BINARY_MOD, BC_NOARG, line); break;
  612. case TK("**"): ctx->emit_(OP_BINARY_POW, BC_NOARG, line); break;
  613. case TK("<"): ctx->emit_(OP_COMPARE_LT, BC_NOARG, line); break;
  614. case TK("<="): ctx->emit_(OP_COMPARE_LE, BC_NOARG, line); break;
  615. case TK("=="): ctx->emit_(OP_COMPARE_EQ, BC_NOARG, line); break;
  616. case TK("!="): ctx->emit_(OP_COMPARE_NE, BC_NOARG, line); break;
  617. case TK(">"): ctx->emit_(OP_COMPARE_GT, BC_NOARG, line); break;
  618. case TK(">="): ctx->emit_(OP_COMPARE_GE, BC_NOARG, line); break;
  619. case TK("in"): ctx->emit_(OP_CONTAINS_OP, 0, line); break;
  620. case TK("not in"): ctx->emit_(OP_CONTAINS_OP, 1, line); break;
  621. case TK("is"): ctx->emit_(OP_IS_OP, 0, line); break;
  622. case TK("is not"): ctx->emit_(OP_IS_OP, 1, line); break;
  623. case TK("<<"): ctx->emit_(OP_BITWISE_LSHIFT, BC_NOARG, line); break;
  624. case TK(">>"): ctx->emit_(OP_BITWISE_RSHIFT, BC_NOARG, line); break;
  625. case TK("&"): ctx->emit_(OP_BITWISE_AND, BC_NOARG, line); break;
  626. case TK("|"): ctx->emit_(OP_BITWISE_OR, BC_NOARG, line); break;
  627. case TK("^"): ctx->emit_(OP_BITWISE_XOR, BC_NOARG, line); break;
  628. case TK("@"): ctx->emit_(OP_BINARY_MATMUL, BC_NOARG, line); break;
  629. default: PK_FATAL_ERROR();
  630. }
  631. for(int i: jmps) ctx->patch_jump(i);
  632. }
  633. void TernaryExpr::emit_(CodeEmitContext* ctx){
  634. cond->emit_(ctx);
  635. int patch = ctx->emit_(OP_POP_JUMP_IF_FALSE, BC_NOARG, cond->line);
  636. true_expr->emit_(ctx);
  637. int patch_2 = ctx->emit_(OP_JUMP_ABSOLUTE, BC_NOARG, true_expr->line);
  638. ctx->patch_jump(patch);
  639. false_expr->emit_(ctx);
  640. ctx->patch_jump(patch_2);
  641. }
  642. } // namespace pkpy