expr.cpp 25 KB

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