vm.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. #include "pocketpy/vm.h"
  2. namespace pkpy{
  3. VM::VM(bool enable_os) : heap(this), enable_os(enable_os) {
  4. this->vm = this;
  5. this->_c.error = nullptr;
  6. _stdout = [](VM* vm, const char* buf, int size) {
  7. PK_UNUSED(vm);
  8. std::cout.write(buf, size);
  9. };
  10. _stderr = [](VM* vm, const char* buf, int size) {
  11. PK_UNUSED(vm);
  12. std::cerr.write(buf, size);
  13. };
  14. callstack.reserve(8);
  15. _main = nullptr;
  16. _last_exception = nullptr;
  17. _import_handler = [](const Str& name) {
  18. PK_UNUSED(name);
  19. return Bytes();
  20. };
  21. init_builtin_types();
  22. }
  23. PyObject* VM::py_str(PyObject* obj){
  24. const PyTypeInfo* ti = _inst_type_info(obj);
  25. if(ti->m__str__) return ti->m__str__(this, obj);
  26. PyObject* self;
  27. PyObject* f = get_unbound_method(obj, __str__, &self, false);
  28. if(self != PY_NULL) return call_method(self, f);
  29. return py_repr(obj);
  30. }
  31. PyObject* VM::py_repr(PyObject* obj){
  32. const PyTypeInfo* ti = _inst_type_info(obj);
  33. if(ti->m__repr__) return ti->m__repr__(this, obj);
  34. return call_method(obj, __repr__);
  35. }
  36. PyObject* VM::py_json(PyObject* obj){
  37. const PyTypeInfo* ti = _inst_type_info(obj);
  38. if(ti->m__json__) return ti->m__json__(this, obj);
  39. return call_method(obj, __json__);
  40. }
  41. PyObject* VM::py_iter(PyObject* obj){
  42. const PyTypeInfo* ti = _inst_type_info(obj);
  43. if(ti->m__iter__) return ti->m__iter__(this, obj);
  44. PyObject* self;
  45. PyObject* iter_f = get_unbound_method(obj, __iter__, &self, false);
  46. if(self != PY_NULL) return call_method(self, iter_f);
  47. TypeError(OBJ_NAME(_t(obj)).escape() + " object is not iterable");
  48. return nullptr;
  49. }
  50. FrameId VM::top_frame(){
  51. #if PK_DEBUG_EXTRA_CHECK
  52. if(callstack.empty()) FATAL_ERROR();
  53. #endif
  54. return FrameId(&callstack.data(), callstack.size()-1);
  55. }
  56. void VM::_pop_frame(){
  57. Frame* frame = &callstack.top();
  58. s_data.reset(frame->_sp_base);
  59. callstack.pop();
  60. }
  61. PyObject* VM::find_name_in_mro(PyObject* cls, StrName name){
  62. PyObject* val;
  63. do{
  64. val = cls->attr().try_get(name);
  65. if(val != nullptr) return val;
  66. Type base = _all_types[PK_OBJ_GET(Type, cls)].base;
  67. if(base.index == -1) break;
  68. cls = _all_types[base].obj;
  69. }while(true);
  70. return nullptr;
  71. }
  72. bool VM::isinstance(PyObject* obj, Type base){
  73. Type obj_t = PK_OBJ_GET(Type, _t(obj));
  74. return issubclass(obj_t, base);
  75. }
  76. bool VM::issubclass(Type cls, Type base){
  77. do{
  78. if(cls == base) return true;
  79. Type next = _all_types[cls].base;
  80. if(next.index == -1) break;
  81. cls = next;
  82. }while(true);
  83. return false;
  84. }
  85. PyObject* VM::exec(Str source, Str filename, CompileMode mode, PyObject* _module){
  86. if(_module == nullptr) _module = _main;
  87. try {
  88. CodeObject_ code = compile(source, filename, mode);
  89. #if PK_DEBUG_DIS_EXEC
  90. if(_module == _main) std::cout << disassemble(code) << '\n';
  91. #endif
  92. return _exec(code, _module);
  93. }catch (const Exception& e){
  94. Str sum = e.summary() + "\n";
  95. _stderr(this, sum.data, sum.size);
  96. }
  97. #if !PK_DEBUG_FULL_EXCEPTION
  98. catch (const std::exception& e) {
  99. Str msg = "An std::exception occurred! It could be a bug.\n";
  100. msg = msg + e.what() + "\n";
  101. _stderr(this, msg.data, msg.size);
  102. }
  103. #endif
  104. callstack.clear();
  105. s_data.clear();
  106. return nullptr;
  107. }
  108. PyObject* VM::exec(Str source){
  109. return exec(source, "main.py", EXEC_MODE);
  110. }
  111. PyObject* VM::eval(Str source){
  112. return exec(source, "<eval>", EVAL_MODE);
  113. }
  114. PyObject* VM::new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled){
  115. PyObject* obj = heap._new<Type>(tp_type, _all_types.size());
  116. const PyTypeInfo& base_info = _all_types[base];
  117. if(!base_info.subclass_enabled){
  118. TypeError(fmt("type ", base_info.name.escape(), " is not `subclass_enabled`"));
  119. }
  120. PyTypeInfo info{
  121. obj,
  122. base,
  123. mod,
  124. name.sv(),
  125. subclass_enabled,
  126. };
  127. if(mod != nullptr) mod->attr().set(name, obj);
  128. _all_types.push_back(info);
  129. return obj;
  130. }
  131. Type VM::_new_type_object(StrName name, Type base) {
  132. PyObject* obj = new_type_object(nullptr, name, base, false);
  133. return PK_OBJ_GET(Type, obj);
  134. }
  135. PyObject* VM::_find_type_object(const Str& type){
  136. PyObject* obj = builtins->attr().try_get_likely_found(type);
  137. if(obj == nullptr){
  138. for(auto& t: _all_types) if(t.name == type) return t.obj;
  139. throw std::runtime_error(fmt("type not found: ", type));
  140. }
  141. check_non_tagged_type(obj, tp_type);
  142. return obj;
  143. }
  144. Type VM::_type(const Str& type){
  145. PyObject* obj = _find_type_object(type);
  146. return PK_OBJ_GET(Type, obj);
  147. }
  148. PyTypeInfo* VM::_type_info(const Str& type){
  149. PyObject* obj = builtins->attr().try_get_likely_found(type);
  150. if(obj == nullptr){
  151. for(auto& t: _all_types) if(t.name == type) return &t;
  152. FATAL_ERROR();
  153. }
  154. return &_all_types[PK_OBJ_GET(Type, obj)];
  155. }
  156. PyTypeInfo* VM::_type_info(Type type){
  157. return &_all_types[type];
  158. }
  159. const PyTypeInfo* VM::_inst_type_info(PyObject* obj){
  160. if(is_int(obj)) return &_all_types[tp_int];
  161. if(is_float(obj)) return &_all_types[tp_float];
  162. return &_all_types[obj->type];
  163. }
  164. bool VM::py_equals(PyObject* lhs, PyObject* rhs){
  165. if(lhs == rhs) return true;
  166. const PyTypeInfo* ti = _inst_type_info(lhs);
  167. PyObject* res;
  168. if(ti->m__eq__){
  169. res = ti->m__eq__(this, lhs, rhs);
  170. if(res != vm->NotImplemented) return res == vm->True;
  171. }
  172. res = call_method(lhs, __eq__, rhs);
  173. if(res != vm->NotImplemented) return res == vm->True;
  174. ti = _inst_type_info(rhs);
  175. if(ti->m__eq__){
  176. res = ti->m__eq__(this, rhs, lhs);
  177. if(res != vm->NotImplemented) return res == vm->True;
  178. }
  179. res = call_method(rhs, __eq__, lhs);
  180. if(res != vm->NotImplemented) return res == vm->True;
  181. return false;
  182. }
  183. int VM::normalized_index(int index, int size){
  184. if(index < 0) index += size;
  185. if(index < 0 || index >= size){
  186. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  187. }
  188. return index;
  189. }
  190. PyObject* VM::py_next(PyObject* obj){
  191. const PyTypeInfo* ti = _inst_type_info(obj);
  192. if(ti->m__next__) return ti->m__next__(this, obj);
  193. return call_method(obj, __next__);
  194. }
  195. PyObject* VM::py_import(Str path, bool throw_err){
  196. if(path.empty()) vm->ValueError("empty module name");
  197. auto f_join = [](const std::vector<std::string_view>& cpnts){
  198. std::stringstream ss;
  199. for(int i=0; i<cpnts.size(); i++){
  200. if(i != 0) ss << ".";
  201. ss << cpnts[i];
  202. }
  203. return Str(ss.str());
  204. };
  205. if(path[0] == '.'){
  206. if(_import_context.pending.empty()){
  207. ImportError("relative import outside of package");
  208. }
  209. Str curr_path = _import_context.pending.back();
  210. bool curr_is_init = _import_context.pending_is_init.back();
  211. // convert relative path to absolute path
  212. std::vector<std::string_view> cpnts = curr_path.split(".");
  213. int prefix = 0; // how many dots in the prefix
  214. for(int i=0; i<path.length(); i++){
  215. if(path[i] == '.') prefix++;
  216. else break;
  217. }
  218. if(prefix > cpnts.size()) ImportError("attempted relative import beyond top-level package");
  219. path = path.substr(prefix); // remove prefix
  220. for(int i=(int)curr_is_init; i<prefix; i++) cpnts.pop_back();
  221. if(!path.empty()) cpnts.push_back(path.sv());
  222. path = f_join(cpnts);
  223. }
  224. // std::cout << "py_import(" << path.escape() << ")" << std::endl;
  225. PK_ASSERT(path.begin()[0] != '.');
  226. PK_ASSERT(path.end()[-1] != '.');
  227. auto path_cpnts = path.split(".");
  228. // check circular import
  229. if(_import_context.pending.size() > 128){
  230. ImportError("maximum recursion depth exceeded while importing");
  231. }
  232. StrName name(path); // path to StrName
  233. PyObject* ext_mod = _modules.try_get(name);
  234. if(ext_mod != nullptr) return ext_mod;
  235. // try import
  236. Str filename = path.replace('.', kPlatformSep) + ".py";
  237. Str source;
  238. bool is_init = false;
  239. auto it = _lazy_modules.find(name);
  240. if(it == _lazy_modules.end()){
  241. Bytes b = _import_handler(filename);
  242. if(!b){
  243. filename = path.replace('.', kPlatformSep).str() + kPlatformSep + "__init__.py";
  244. is_init = true;
  245. b = _import_handler(filename);
  246. }
  247. if(!b){
  248. if(throw_err) ImportError(fmt("module ", path.escape(), " not found"));
  249. else return nullptr;
  250. }
  251. source = Str(b.str());
  252. }else{
  253. source = it->second;
  254. _lazy_modules.erase(it);
  255. }
  256. auto _ = _import_context.scope(path, is_init);
  257. CodeObject_ code = compile(source, filename, EXEC_MODE);
  258. Str name_cpnt = path_cpnts.back();
  259. path_cpnts.pop_back();
  260. PyObject* new_mod = new_module(name_cpnt, f_join(path_cpnts));
  261. _exec(code, new_mod);
  262. return new_mod;
  263. }
  264. VM::~VM() {
  265. callstack.clear();
  266. s_data.clear();
  267. _all_types.clear();
  268. _modules.clear();
  269. _lazy_modules.clear();
  270. }
  271. PyObject* VM::py_negate(PyObject* obj){
  272. const PyTypeInfo* ti = _inst_type_info(obj);
  273. if(ti->m__neg__) return ti->m__neg__(this, obj);
  274. return call_method(obj, __neg__);
  275. }
  276. bool VM::py_bool(PyObject* obj){
  277. if(is_non_tagged_type(obj, tp_bool)) return obj == True;
  278. if(obj == None) return false;
  279. if(is_int(obj)) return _CAST(i64, obj) != 0;
  280. if(is_float(obj)) return _CAST(f64, obj) != 0.0;
  281. PyObject* self;
  282. PyObject* len_f = get_unbound_method(obj, __len__, &self, false);
  283. if(self != PY_NULL){
  284. PyObject* ret = call_method(self, len_f);
  285. return CAST(i64, ret) > 0;
  286. }
  287. return true;
  288. }
  289. PyObject* VM::py_list(PyObject* it){
  290. auto _lock = heap.gc_scope_lock();
  291. it = py_iter(it);
  292. List list;
  293. PyObject* obj = py_next(it);
  294. while(obj != StopIteration){
  295. list.push_back(obj);
  296. obj = py_next(it);
  297. }
  298. return VAR(std::move(list));
  299. }
  300. void VM::parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step){
  301. auto clip = [](int value, int min, int max){
  302. if(value < min) return min;
  303. if(value > max) return max;
  304. return value;
  305. };
  306. if(s.step == None) step = 1;
  307. else step = CAST(int, s.step);
  308. if(step == 0) ValueError("slice step cannot be zero");
  309. if(step > 0){
  310. if(s.start == None){
  311. start = 0;
  312. }else{
  313. start = CAST(int, s.start);
  314. if(start < 0) start += length;
  315. start = clip(start, 0, length);
  316. }
  317. if(s.stop == None){
  318. stop = length;
  319. }else{
  320. stop = CAST(int, s.stop);
  321. if(stop < 0) stop += length;
  322. stop = clip(stop, 0, length);
  323. }
  324. }else{
  325. if(s.start == None){
  326. start = length - 1;
  327. }else{
  328. start = CAST(int, s.start);
  329. if(start < 0) start += length;
  330. start = clip(start, -1, length - 1);
  331. }
  332. if(s.stop == None){
  333. stop = -1;
  334. }else{
  335. stop = CAST(int, s.stop);
  336. if(stop < 0) stop += length;
  337. stop = clip(stop, -1, length - 1);
  338. }
  339. }
  340. }
  341. i64 VM::py_hash(PyObject* obj){
  342. // https://docs.python.org/3.10/reference/datamodel.html#object.__hash__
  343. const PyTypeInfo* ti = _inst_type_info(obj);
  344. if(ti->m__hash__) return ti->m__hash__(this, obj);
  345. PyObject* self;
  346. PyObject* f = get_unbound_method(obj, __hash__, &self, false);
  347. if(f != nullptr){
  348. PyObject* ret = call_method(self, f);
  349. return CAST(i64, ret);
  350. }
  351. // if it is trivial `object`, return PK_BITS
  352. if(ti == &_all_types[tp_object]) return PK_BITS(obj);
  353. // otherwise, we check if it has a custom __eq__ other than object.__eq__
  354. bool has_custom_eq = false;
  355. if(ti->m__eq__) has_custom_eq = true;
  356. else{
  357. f = get_unbound_method(obj, __eq__, &self, false);
  358. has_custom_eq = f != _t(tp_object)->attr(__eq__);
  359. }
  360. if(has_custom_eq){
  361. TypeError(fmt("unhashable type: ", ti->name.escape()));
  362. return 0;
  363. }else{
  364. return PK_BITS(obj);
  365. }
  366. }
  367. PyObject* VM::format(Str spec, PyObject* obj){
  368. if(spec.empty()) return py_str(obj);
  369. char type;
  370. switch(spec.end()[-1]){
  371. case 'f': case 'd': case 's':
  372. type = spec.end()[-1];
  373. spec = spec.substr(0, spec.length() - 1);
  374. break;
  375. default: type = ' '; break;
  376. }
  377. char pad_c = ' ';
  378. for(char c: std::string_view("0-=*#@!~")){
  379. if(spec[0] == c){
  380. pad_c = c;
  381. spec = spec.substr(1);
  382. break;
  383. }
  384. }
  385. char align;
  386. if(spec[0] == '^'){
  387. align = '^';
  388. spec = spec.substr(1);
  389. }else if(spec[0] == '>'){
  390. align = '>';
  391. spec = spec.substr(1);
  392. }else if(spec[0] == '<'){
  393. align = '<';
  394. spec = spec.substr(1);
  395. }else{
  396. if(is_int(obj) || is_float(obj)) align = '>';
  397. else align = '<';
  398. }
  399. int dot = spec.index(".");
  400. int width, precision;
  401. try{
  402. if(dot >= 0){
  403. if(dot == 0){
  404. width = -1;
  405. }else{
  406. width = std::stoi(spec.substr(0, dot).str());
  407. }
  408. precision = std::stoi(spec.substr(dot+1).str());
  409. }else{
  410. width = std::stoi(spec.str());
  411. precision = -1;
  412. }
  413. }catch(...){
  414. ValueError("invalid format specifer");
  415. UNREACHABLE();
  416. }
  417. if(type != 'f' && dot >= 0) ValueError("precision not allowed in the format specifier");
  418. Str ret;
  419. if(type == 'f'){
  420. f64 val = CAST(f64, obj);
  421. if(precision < 0) precision = 6;
  422. std::stringstream ss;
  423. ss << std::fixed << std::setprecision(precision) << val;
  424. ret = ss.str();
  425. }else if(type == 'd'){
  426. ret = std::to_string(CAST(i64, obj));
  427. }else if(type == 's'){
  428. ret = CAST(Str&, obj);
  429. }else{
  430. ret = CAST(Str&, py_str(obj));
  431. }
  432. if(width != -1 && width > ret.length()){
  433. int pad = width - ret.length();
  434. if(align == '>' || align == '<'){
  435. std::string padding(pad, pad_c);
  436. if(align == '>') ret = padding.c_str() + ret;
  437. else ret = ret + padding.c_str();
  438. }else{ // ^
  439. int pad_left = pad / 2;
  440. int pad_right = pad - pad_left;
  441. std::string padding_left(pad_left, pad_c);
  442. std::string padding_right(pad_right, pad_c);
  443. ret = padding_left.c_str() + ret + padding_right.c_str();
  444. }
  445. }
  446. return VAR(ret);
  447. }
  448. PyObject* VM::new_module(Str name, Str package) {
  449. PyObject* obj = heap._new<DummyModule>(tp_module);
  450. obj->attr().set(__name__, VAR(name));
  451. obj->attr().set(__package__, VAR(package));
  452. // we do not allow override in order to avoid memory leak
  453. // it is because Module objects are not garbage collected
  454. if(_modules.contains(name)){
  455. throw std::runtime_error(fmt("module ", name.escape(), " already exists"));
  456. }
  457. // convert to fullname and set it into _modules
  458. if(!package.empty()) name = package + "." + name;
  459. obj->attr().set(__path__, VAR(name));
  460. _modules.set(name, obj);
  461. return obj;
  462. }
  463. static std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  464. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  465. switch(byte.op){
  466. case OP_LOAD_CONST: case OP_FORMAT_STRING: case OP_IMPORT_PATH:
  467. if(vm != nullptr){
  468. argStr += fmt(" (", CAST(Str, vm->py_repr(co->consts[byte.arg])), ")");
  469. }
  470. break;
  471. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  472. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  473. case OP_BEGIN_CLASS: case OP_RAISE: case OP_GOTO:
  474. case OP_DELETE_GLOBAL: case OP_INC_GLOBAL: case OP_DEC_GLOBAL: case OP_STORE_CLASS_ATTR:
  475. argStr += fmt(" (", StrName(byte.arg).sv(), ")");
  476. break;
  477. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST: case OP_INC_FAST: case OP_DEC_FAST:
  478. argStr += fmt(" (", co->varnames[byte.arg].sv(), ")");
  479. break;
  480. case OP_LOAD_FUNCTION:
  481. argStr += fmt(" (", co->func_decls[byte.arg]->code->name, ")");
  482. break;
  483. }
  484. return argStr;
  485. }
  486. Str VM::disassemble(CodeObject_ co){
  487. auto pad = [](const Str& s, const int n){
  488. if(s.length() >= n) return s.substr(0, n);
  489. return s + std::string(n - s.length(), ' ');
  490. };
  491. std::vector<int> jumpTargets;
  492. for(auto byte : co->codes){
  493. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE || byte.op == OP_SHORTCUT_IF_FALSE_OR_POP){
  494. jumpTargets.push_back(byte.arg);
  495. }
  496. if(byte.op == OP_GOTO){
  497. // TODO: pre-compute jump targets for OP_GOTO
  498. int* target = co->labels.try_get_2_likely_found(StrName(byte.arg));
  499. if(target != nullptr) jumpTargets.push_back(*target);
  500. }
  501. }
  502. std::stringstream ss;
  503. int prev_line = -1;
  504. for(int i=0; i<co->codes.size(); i++){
  505. const Bytecode& byte = co->codes[i];
  506. Str line = std::to_string(co->lines[i]);
  507. if(co->lines[i] == prev_line) line = "";
  508. else{
  509. if(prev_line != -1) ss << "\n";
  510. prev_line = co->lines[i];
  511. }
  512. std::string pointer;
  513. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  514. pointer = "-> ";
  515. }else{
  516. pointer = " ";
  517. }
  518. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  519. ss << " " << pad(OP_NAMES[byte.op], 25) << " ";
  520. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  521. std::string argStr = _opcode_argstr(this, byte, co.get());
  522. ss << argStr;
  523. // ss << pad(argStr, 40); // may overflow
  524. // ss << co->blocks[byte.block].type;
  525. if(i != co->codes.size() - 1) ss << '\n';
  526. }
  527. for(auto& decl: co->func_decls){
  528. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  529. ss << disassemble(decl->code);
  530. }
  531. ss << "\n";
  532. return Str(ss.str());
  533. }
  534. #if PK_DEBUG_CEVAL_STEP
  535. void VM::_log_s_data(const char* title) {
  536. if(_main == nullptr) return;
  537. if(callstack.empty()) return;
  538. std::stringstream ss;
  539. if(title) ss << title << " | ";
  540. std::map<PyObject**, int> sp_bases;
  541. for(Frame& f: callstack.data()){
  542. if(f._sp_base == nullptr) FATAL_ERROR();
  543. sp_bases[f._sp_base] += 1;
  544. }
  545. FrameId frame = top_frame();
  546. int line = frame->co->lines[frame->_ip];
  547. ss << frame->co->name << ":" << line << " [";
  548. for(PyObject** p=s_data.begin(); p!=s_data.end(); p++){
  549. ss << std::string(sp_bases[p], '|');
  550. if(sp_bases[p] > 0) ss << " ";
  551. PyObject* obj = *p;
  552. if(obj == nullptr) ss << "(nil)";
  553. else if(obj == PY_NULL) ss << "NULL";
  554. else if(is_int(obj)) ss << CAST(i64, obj);
  555. else if(is_float(obj)) ss << CAST(f64, obj);
  556. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  557. else if(obj == None) ss << "None";
  558. else if(obj == True) ss << "True";
  559. else if(obj == False) ss << "False";
  560. else if(is_type(obj, tp_function)){
  561. auto& f = CAST(Function&, obj);
  562. ss << f.decl->code->name << "(...)";
  563. } else if(is_type(obj, tp_type)){
  564. Type t = PK_OBJ_GET(Type, obj);
  565. ss << "<class " + _all_types[t].name.escape() + ">";
  566. } else if(is_type(obj, tp_list)){
  567. auto& t = CAST(List&, obj);
  568. ss << "list(size=" << t.size() << ")";
  569. } else if(is_type(obj, tp_tuple)){
  570. auto& t = CAST(Tuple&, obj);
  571. ss << "tuple(size=" << t.size() << ")";
  572. } else ss << "(" << obj_type_name(this, obj->type) << ")";
  573. ss << ", ";
  574. }
  575. std::string output = ss.str();
  576. if(!s_data.empty()) {
  577. output.pop_back(); output.pop_back();
  578. }
  579. output.push_back(']');
  580. Bytecode byte = frame->co->codes[frame->_ip];
  581. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  582. }
  583. #endif
  584. void VM::init_builtin_types(){
  585. _all_types.push_back({heap._new<Type>(Type(1), Type(0)), -1, nullptr, "object", true});
  586. _all_types.push_back({heap._new<Type>(Type(1), Type(1)), 0, nullptr, "type", false});
  587. tp_object = 0; tp_type = 1;
  588. tp_int = _new_type_object("int");
  589. tp_float = _new_type_object("float");
  590. if(tp_int.index != kTpIntIndex || tp_float.index != kTpFloatIndex) FATAL_ERROR();
  591. tp_bool = _new_type_object("bool");
  592. tp_str = _new_type_object("str");
  593. tp_list = _new_type_object("list");
  594. tp_tuple = _new_type_object("tuple");
  595. tp_slice = _new_type_object("slice");
  596. tp_range = _new_type_object("range");
  597. tp_module = _new_type_object("module");
  598. tp_function = _new_type_object("function");
  599. tp_native_func = _new_type_object("native_func");
  600. tp_bound_method = _new_type_object("bound_method");
  601. tp_super = _new_type_object("super");
  602. tp_exception = _new_type_object("Exception");
  603. tp_bytes = _new_type_object("bytes");
  604. tp_mappingproxy = _new_type_object("mappingproxy");
  605. tp_dict = _new_type_object("dict");
  606. tp_property = _new_type_object("property");
  607. tp_star_wrapper = _new_type_object("_star_wrapper");
  608. this->None = heap._new<Dummy>(_new_type_object("NoneType"));
  609. this->NotImplemented = heap._new<Dummy>(_new_type_object("NotImplementedType"));
  610. this->Ellipsis = heap._new<Dummy>(_new_type_object("ellipsis"));
  611. this->True = heap._new<Dummy>(tp_bool);
  612. this->False = heap._new<Dummy>(tp_bool);
  613. this->StopIteration = heap._new<Dummy>(_new_type_object("StopIterationType"));
  614. this->builtins = new_module("builtins");
  615. // setup public types
  616. builtins->attr().set("type", _t(tp_type));
  617. builtins->attr().set("object", _t(tp_object));
  618. builtins->attr().set("bool", _t(tp_bool));
  619. builtins->attr().set("int", _t(tp_int));
  620. builtins->attr().set("float", _t(tp_float));
  621. builtins->attr().set("str", _t(tp_str));
  622. builtins->attr().set("list", _t(tp_list));
  623. builtins->attr().set("tuple", _t(tp_tuple));
  624. builtins->attr().set("range", _t(tp_range));
  625. builtins->attr().set("bytes", _t(tp_bytes));
  626. builtins->attr().set("dict", _t(tp_dict));
  627. builtins->attr().set("property", _t(tp_property));
  628. builtins->attr().set("StopIteration", StopIteration);
  629. builtins->attr().set("NotImplemented", NotImplemented);
  630. builtins->attr().set("slice", _t(tp_slice));
  631. post_init();
  632. this->_main = new_module("__main__");
  633. }
  634. // `heap.gc_scope_lock();` needed before calling this function
  635. void VM::_unpack_as_list(ArgsView args, List& list){
  636. for(PyObject* obj: args){
  637. if(is_non_tagged_type(obj, tp_star_wrapper)){
  638. const StarWrapper& w = _CAST(StarWrapper&, obj);
  639. // maybe this check should be done in the compile time
  640. if(w.level != 1) TypeError("expected level 1 star wrapper");
  641. PyObject* _0 = py_iter(w.obj);
  642. PyObject* _1 = py_next(_0);
  643. while(_1 != StopIteration){
  644. list.push_back(_1);
  645. _1 = py_next(_0);
  646. }
  647. }else{
  648. list.push_back(obj);
  649. }
  650. }
  651. }
  652. // `heap.gc_scope_lock();` needed before calling this function
  653. void VM::_unpack_as_dict(ArgsView args, Dict& dict){
  654. for(PyObject* obj: args){
  655. if(is_non_tagged_type(obj, tp_star_wrapper)){
  656. const StarWrapper& w = _CAST(StarWrapper&, obj);
  657. // maybe this check should be done in the compile time
  658. if(w.level != 2) TypeError("expected level 2 star wrapper");
  659. const Dict& other = CAST(Dict&, w.obj);
  660. dict.update(other);
  661. }else{
  662. const Tuple& t = CAST(Tuple&, obj);
  663. if(t.size() != 2) TypeError("expected tuple of length 2");
  664. dict.set(t[0], t[1]);
  665. }
  666. }
  667. }
  668. void VM::_prepare_py_call(PyObject** buffer, ArgsView args, ArgsView kwargs, const FuncDecl_& decl){
  669. const CodeObject* co = decl->code.get();
  670. int co_nlocals = co->varnames.size();
  671. int decl_argc = decl->args.size();
  672. if(args.size() < decl_argc){
  673. vm->TypeError(fmt(
  674. co->name, "() takes ", decl_argc, " positional arguments but ", args.size(), " were given"
  675. ));
  676. UNREACHABLE();
  677. }
  678. int i = 0;
  679. // prepare args
  680. for(int index: decl->args) buffer[index] = args[i++];
  681. // set extra varnames to PY_NULL
  682. for(int j=i; j<co_nlocals; j++) buffer[j] = PY_NULL;
  683. // prepare kwdefaults
  684. for(auto& kv: decl->kwargs) buffer[kv.key] = kv.value;
  685. // handle *args
  686. if(decl->starred_arg != -1){
  687. ArgsView vargs(args.begin() + i, args.end());
  688. buffer[decl->starred_arg] = VAR(vargs.to_tuple());
  689. i += vargs.size();
  690. }else{
  691. // kwdefaults override
  692. for(auto& kv: decl->kwargs){
  693. if(i >= args.size()) break;
  694. buffer[kv.key] = args[i++];
  695. }
  696. if(i < args.size()) TypeError(fmt("too many arguments", " (", decl->code->name, ')'));
  697. }
  698. PyObject* vkwargs;
  699. if(decl->starred_kwarg != -1){
  700. vkwargs = VAR(Dict(this));
  701. buffer[decl->starred_kwarg] = vkwargs;
  702. }else{
  703. vkwargs = nullptr;
  704. }
  705. for(int j=0; j<kwargs.size(); j+=2){
  706. StrName key(CAST(int, kwargs[j]));
  707. int index = co->varnames_inv.try_get_likely_found(key);
  708. if(index < 0){
  709. if(vkwargs == nullptr){
  710. TypeError(fmt(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  711. }else{
  712. Dict& dict = _CAST(Dict&, vkwargs);
  713. dict.set(VAR(key.sv()), kwargs[j+1]);
  714. }
  715. }else{
  716. buffer[index] = kwargs[j+1];
  717. }
  718. }
  719. }
  720. PyObject* VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  721. PyObject** p1 = s_data._sp - KWARGC*2;
  722. PyObject** p0 = p1 - ARGC - 2;
  723. // [callable, <self>, args..., kwargs...]
  724. // ^p0 ^p1 ^_sp
  725. PyObject* callable = p1[-(ARGC + 2)];
  726. bool method_call = p1[-(ARGC + 1)] != PY_NULL;
  727. // handle boundmethod, do a patch
  728. if(is_non_tagged_type(callable, tp_bound_method)){
  729. if(method_call) FATAL_ERROR();
  730. auto& bm = CAST(BoundMethod&, callable);
  731. callable = bm.func; // get unbound method
  732. p1[-(ARGC + 2)] = bm.func;
  733. p1[-(ARGC + 1)] = bm.self;
  734. method_call = true;
  735. // [unbound, self, args..., kwargs...]
  736. }
  737. ArgsView args(p1 - ARGC - int(method_call), p1);
  738. ArgsView kwargs(p1, s_data._sp);
  739. PyObject** _base = args.begin();
  740. PyObject* buffer[PK_MAX_CO_VARNAMES];
  741. if(is_non_tagged_type(callable, tp_native_func)){
  742. const auto& f = PK_OBJ_GET(NativeFunc, callable);
  743. PyObject* ret;
  744. if(f.decl != nullptr){
  745. int co_nlocals = f.decl->code->varnames.size();
  746. _prepare_py_call(buffer, args, kwargs, f.decl);
  747. // copy buffer back to stack
  748. s_data.reset(_base + co_nlocals);
  749. for(int j=0; j<co_nlocals; j++) _base[j] = buffer[j];
  750. ret = f.call(vm, ArgsView(s_data._sp - co_nlocals, s_data._sp));
  751. }else{
  752. if(KWARGC != 0) TypeError("old-style native_func does not accept keyword arguments");
  753. f.check_size(this, args);
  754. ret = f.call(this, args);
  755. }
  756. s_data.reset(p0);
  757. return ret;
  758. }
  759. if(is_non_tagged_type(callable, tp_function)){
  760. /*****************_py_call*****************/
  761. // callable must be a `function` object
  762. if(s_data.is_overflow()) StackOverflowError();
  763. const Function& fn = PK_OBJ_GET(Function, callable);
  764. const FuncDecl_& decl = fn.decl;
  765. const CodeObject* co = decl->code.get();
  766. int co_nlocals = co->varnames.size();
  767. if(decl->is_simple){
  768. if(args.size() != decl->args.size()){
  769. TypeError(fmt(
  770. co->name, "() takes ", decl->args.size(), " positional arguments but ", args.size(), " were given"
  771. ));
  772. UNREACHABLE();
  773. }
  774. if(!kwargs.empty()){
  775. TypeError(fmt(co->name, "() takes no keyword arguments"));
  776. UNREACHABLE();
  777. }
  778. s_data.reset(_base + co_nlocals);
  779. int i = 0;
  780. // prepare args
  781. for(int index: decl->args) _base[index] = args[i++];
  782. // set extra varnames to PY_NULL
  783. for(int j=i; j<co_nlocals; j++) _base[j] = PY_NULL;
  784. goto __FAST_CALL;
  785. }
  786. _prepare_py_call(buffer, args, kwargs, decl);
  787. if(co->is_generator){
  788. s_data.reset(p0);
  789. return _py_generator(
  790. Frame(&s_data, nullptr, co, fn._module, callable),
  791. ArgsView(buffer, buffer + co_nlocals)
  792. );
  793. }
  794. // copy buffer back to stack
  795. s_data.reset(_base + co_nlocals);
  796. for(int j=0; j<co_nlocals; j++) _base[j] = buffer[j];
  797. __FAST_CALL:
  798. callstack.emplace(&s_data, p0, co, fn._module, callable, FastLocals(co, args.begin()));
  799. if(op_call) return PY_OP_CALL;
  800. return _run_top_frame();
  801. /*****************_py_call*****************/
  802. }
  803. if(is_non_tagged_type(callable, tp_type)){
  804. if(method_call) FATAL_ERROR();
  805. // [type, NULL, args..., kwargs...]
  806. PyObject* new_f = find_name_in_mro(callable, __new__);
  807. PyObject* obj;
  808. #if PK_DEBUG_EXTRA_CHECK
  809. PK_ASSERT(new_f != nullptr);
  810. #endif
  811. if(new_f == cached_object__new__) {
  812. // fast path for object.__new__
  813. Type t = PK_OBJ_GET(Type, callable);
  814. obj= vm->heap.gcnew<DummyInstance>(t);
  815. }else{
  816. PUSH(new_f);
  817. PUSH(PY_NULL);
  818. PUSH(callable); // cls
  819. for(PyObject* o: args) PUSH(o);
  820. for(PyObject* o: kwargs) PUSH(o);
  821. // if obj is not an instance of callable, the behavior is undefined
  822. obj = vectorcall(ARGC+1, KWARGC);
  823. }
  824. // __init__
  825. PyObject* self;
  826. callable = get_unbound_method(obj, __init__, &self, false);
  827. if (self != PY_NULL) {
  828. // replace `NULL` with `self`
  829. p1[-(ARGC + 2)] = callable;
  830. p1[-(ARGC + 1)] = self;
  831. // [init_f, self, args..., kwargs...]
  832. vectorcall(ARGC, KWARGC);
  833. // We just discard the return value of `__init__`
  834. // in cpython it raises a TypeError if the return value is not None
  835. }else{
  836. // manually reset the stack
  837. s_data.reset(p0);
  838. }
  839. return obj;
  840. }
  841. // handle `__call__` overload
  842. PyObject* self;
  843. PyObject* call_f = get_unbound_method(callable, __call__, &self, false);
  844. if(self != PY_NULL){
  845. p1[-(ARGC + 2)] = call_f;
  846. p1[-(ARGC + 1)] = self;
  847. // [call_f, self, args..., kwargs...]
  848. return vectorcall(ARGC, KWARGC, false);
  849. }
  850. TypeError(OBJ_NAME(_t(callable)).escape() + " object is not callable");
  851. return nullptr;
  852. }
  853. void VM::delattr(PyObject *_0, StrName _name){
  854. if(is_tagged(_0) || !_0->is_attr_valid()) TypeError("cannot delete attribute");
  855. if(!_0->attr().del(_name)) AttributeError(_0, _name);
  856. }
  857. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  858. PyObject* VM::getattr(PyObject* obj, StrName name, bool throw_err){
  859. PyObject* objtype;
  860. // handle super() proxy
  861. if(is_non_tagged_type(obj, tp_super)){
  862. const Super& super = PK_OBJ_GET(Super, obj);
  863. obj = super.first;
  864. objtype = _t(super.second);
  865. }else{
  866. objtype = _t(obj);
  867. }
  868. PyObject* cls_var = find_name_in_mro(objtype, name);
  869. if(cls_var != nullptr){
  870. // handle descriptor
  871. if(is_non_tagged_type(cls_var, tp_property)){
  872. const Property& prop = _CAST(Property&, cls_var);
  873. return call(prop.getter, obj);
  874. }
  875. }
  876. // handle instance __dict__
  877. if(!is_tagged(obj) && obj->is_attr_valid()){
  878. PyObject* val = obj->attr().try_get_likely_found(name);
  879. if(val != nullptr) return val;
  880. }
  881. if(cls_var != nullptr){
  882. // bound method is non-data descriptor
  883. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  884. return VAR(BoundMethod(obj, cls_var));
  885. }
  886. return cls_var;
  887. }
  888. if(is_non_tagged_type(obj, tp_module)){
  889. Str path = CAST(Str&, obj->attr(__path__));
  890. path = path + "." + name.sv();
  891. PyObject* mod = py_import(path, false);
  892. if(mod != nullptr){
  893. obj->attr().set(name, mod);
  894. return mod;
  895. }
  896. }
  897. if(throw_err) AttributeError(obj, name);
  898. return nullptr;
  899. }
  900. // used by OP_LOAD_METHOD
  901. // try to load a unbound method (fallback to `getattr` if not found)
  902. PyObject* VM::get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err, bool fallback){
  903. *self = PY_NULL;
  904. PyObject* objtype;
  905. // handle super() proxy
  906. if(is_non_tagged_type(obj, tp_super)){
  907. const Super& super = PK_OBJ_GET(Super, obj);
  908. obj = super.first;
  909. objtype = _t(super.second);
  910. }else{
  911. objtype = _t(obj);
  912. }
  913. PyObject* cls_var = find_name_in_mro(objtype, name);
  914. if(fallback){
  915. if(cls_var != nullptr){
  916. // handle descriptor
  917. if(is_non_tagged_type(cls_var, tp_property)){
  918. const Property& prop = _CAST(Property&, cls_var);
  919. return call(prop.getter, obj);
  920. }
  921. }
  922. // handle instance __dict__
  923. if(!is_tagged(obj) && obj->is_attr_valid()){
  924. PyObject* val = obj->attr().try_get(name);
  925. if(val != nullptr) return val;
  926. }
  927. }
  928. if(cls_var != nullptr){
  929. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  930. *self = obj;
  931. }
  932. return cls_var;
  933. }
  934. if(throw_err) AttributeError(obj, name);
  935. return nullptr;
  936. }
  937. void VM::setattr(PyObject* obj, StrName name, PyObject* value){
  938. PyObject* objtype;
  939. // handle super() proxy
  940. if(is_non_tagged_type(obj, tp_super)){
  941. Super& super = PK_OBJ_GET(Super, obj);
  942. obj = super.first;
  943. objtype = _t(super.second);
  944. }else{
  945. objtype = _t(obj);
  946. }
  947. PyObject* cls_var = find_name_in_mro(objtype, name);
  948. if(cls_var != nullptr){
  949. // handle descriptor
  950. if(is_non_tagged_type(cls_var, tp_property)){
  951. const Property& prop = _CAST(Property&, cls_var);
  952. if(prop.setter != vm->None){
  953. call(prop.setter, obj, value);
  954. }else{
  955. TypeError(fmt("readonly attribute: ", name.escape()));
  956. }
  957. return;
  958. }
  959. }
  960. // handle instance __dict__
  961. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  962. obj->attr().set(name, value);
  963. }
  964. PyObject* VM::bind(PyObject* obj, const char* sig, NativeFuncC fn, UserData userdata){
  965. return bind(obj, sig, nullptr, fn, userdata);
  966. }
  967. PyObject* VM::bind(PyObject* obj, const char* sig, const char* docstring, NativeFuncC fn, UserData userdata){
  968. CodeObject_ co;
  969. try{
  970. // fn(a, b, *c, d=1) -> None
  971. co = compile("def " + Str(sig) + " : pass", "<bind>", EXEC_MODE);
  972. }catch(Exception&){
  973. throw std::runtime_error("invalid signature: " + std::string(sig));
  974. }
  975. if(co->func_decls.size() != 1){
  976. throw std::runtime_error("expected 1 function declaration");
  977. }
  978. FuncDecl_ decl = co->func_decls[0];
  979. decl->signature = Str(sig);
  980. if(docstring != nullptr){
  981. decl->docstring = Str(docstring).strip();
  982. }
  983. PyObject* f_obj = VAR(NativeFunc(fn, decl));
  984. PK_OBJ_GET(NativeFunc, f_obj).set_userdata(userdata);
  985. if(obj != nullptr) obj->attr().set(decl->code->name, f_obj);
  986. return f_obj;
  987. }
  988. PyObject* VM::bind_property(PyObject* obj, Str name, NativeFuncC fget, NativeFuncC fset){
  989. PyObject* _0 = heap.gcnew<NativeFunc>(tp_native_func, fget, 1, false);
  990. PyObject* _1 = vm->None;
  991. if(fset != nullptr) _1 = heap.gcnew<NativeFunc>(tp_native_func, fset, 2, false);
  992. Str signature = name;
  993. int pos = name.index(":");
  994. if(pos > 0) name = name.substr(0, pos).strip();
  995. PyObject* prop = VAR(Property(_0, _1, signature));
  996. obj->attr().set(name, prop);
  997. return prop;
  998. }
  999. void VM::_error(Exception e){
  1000. if(callstack.empty()){
  1001. e.is_re = false;
  1002. throw e;
  1003. }
  1004. PUSH(VAR(std::move(e)));
  1005. _raise();
  1006. }
  1007. void VM::_raise(bool re_raise){
  1008. Frame* frame = top_frame().get();
  1009. Exception& e = PK_OBJ_GET(Exception, s_data.top());
  1010. if(!re_raise){
  1011. e._ip_on_error = frame->_ip;
  1012. e._code_on_error = (void*)frame->co;
  1013. }
  1014. bool ok = frame->jump_to_exception_handler();
  1015. int actual_ip = frame->_ip;
  1016. if(e._ip_on_error >= 0 && e._code_on_error == (void*)frame->co) actual_ip = e._ip_on_error;
  1017. int current_line = frame->co->lines[actual_ip]; // current line
  1018. auto current_f_name = frame->co->name.sv(); // current function name
  1019. if(frame->_callable == nullptr) current_f_name = ""; // not in a function
  1020. e.st_push(frame->co->src, current_line, nullptr, current_f_name);
  1021. if(ok) throw HandledException();
  1022. else throw UnhandledException();
  1023. }
  1024. void ManagedHeap::mark() {
  1025. for(PyObject* obj: _no_gc) PK_OBJ_MARK(obj);
  1026. for(auto& frame : vm->callstack.data()) frame._gc_mark();
  1027. for(PyObject* obj: vm->s_data) PK_OBJ_MARK(obj);
  1028. if(_gc_marker_ex) _gc_marker_ex(vm);
  1029. if(vm->_last_exception) PK_OBJ_MARK(vm->_last_exception);
  1030. if(vm->_c.error != nullptr) PK_OBJ_MARK(vm->_c.error);
  1031. }
  1032. Str obj_type_name(VM *vm, Type type){
  1033. return vm->_all_types[type].name;
  1034. }
  1035. void VM::bind__hash__(Type type, i64 (*f)(VM*, PyObject*)){
  1036. PyObject* obj = _t(type);
  1037. _all_types[type].m__hash__ = f;
  1038. PyObject* nf = bind_method<0>(obj, "__hash__", [](VM* vm, ArgsView args){
  1039. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1040. return VAR(ret);
  1041. });
  1042. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1043. }
  1044. void VM::bind__len__(Type type, i64 (*f)(VM*, PyObject*)){
  1045. PyObject* obj = _t(type);
  1046. _all_types[type].m__len__ = f;
  1047. PyObject* nf = bind_method<0>(obj, "__len__", [](VM* vm, ArgsView args){
  1048. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1049. return VAR(ret);
  1050. });
  1051. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1052. }
  1053. void Dict::_probe_0(PyObject *key, bool &ok, int &i) const{
  1054. ok = false;
  1055. i64 hash = vm->py_hash(key);
  1056. i = hash & _mask;
  1057. // std::cout << CAST(Str, vm->py_repr(key)) << " " << hash << " " << i << std::endl;
  1058. for(int j=0; j<_capacity; j++) {
  1059. if(_items[i].first != nullptr){
  1060. if(vm->py_equals(_items[i].first, key)) { ok = true; break; }
  1061. }else{
  1062. if(_items[i].second == nullptr) break;
  1063. }
  1064. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1065. i = ((5*i) + 1) & _mask;
  1066. // std::cout << CAST(Str, vm->py_repr(key)) << " next: " << i << std::endl;
  1067. }
  1068. }
  1069. void Dict::_probe_1(PyObject *key, bool &ok, int &i) const{
  1070. ok = false;
  1071. i = vm->py_hash(key) & _mask;
  1072. while(_items[i].first != nullptr) {
  1073. if(vm->py_equals(_items[i].first, key)) { ok = true; break; }
  1074. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1075. i = ((5*i) + 1) & _mask;
  1076. }
  1077. }
  1078. void CodeObjectSerializer::write_object(VM *vm, PyObject *obj){
  1079. if(is_int(obj)) write_int(_CAST(i64, obj));
  1080. else if(is_float(obj)) write_float(_CAST(f64, obj));
  1081. else if(is_type(obj, vm->tp_str)) write_str(_CAST(Str&, obj));
  1082. else if(is_type(obj, vm->tp_bool)) write_bool(_CAST(bool, obj));
  1083. else if(obj == vm->None) write_none();
  1084. else if(obj == vm->Ellipsis) write_ellipsis();
  1085. else{
  1086. throw std::runtime_error(fmt(OBJ_NAME(vm->_t(obj)).escape(), " is not serializable"));
  1087. }
  1088. }
  1089. void NativeFunc::check_size(VM* vm, ArgsView args) const{
  1090. if(args.size() != argc && argc != -1) {
  1091. vm->TypeError(fmt("expected ", argc, " arguments, got ", args.size()));
  1092. }
  1093. }
  1094. PyObject* NativeFunc::call(VM *vm, ArgsView args) const {
  1095. return f(vm, args);
  1096. }
  1097. } // namespace pkpy