vm.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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(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(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. new_mod->attr()._try_perfect_rehash();
  263. return new_mod;
  264. }
  265. VM::~VM() {
  266. callstack.clear();
  267. s_data.clear();
  268. _all_types.clear();
  269. _modules.clear();
  270. _lazy_modules.clear();
  271. }
  272. PyObject* VM::py_negate(PyObject* obj){
  273. const PyTypeInfo* ti = _inst_type_info(obj);
  274. if(ti->m__neg__) return ti->m__neg__(this, obj);
  275. return call_method(obj, __neg__);
  276. }
  277. bool VM::py_bool(PyObject* obj){
  278. if(is_non_tagged_type(obj, tp_bool)) return obj == True;
  279. if(obj == None) return false;
  280. if(is_int(obj)) return _CAST(i64, obj) != 0;
  281. if(is_float(obj)) return _CAST(f64, obj) != 0.0;
  282. PyObject* self;
  283. PyObject* len_f = get_unbound_method(obj, __len__, &self, false);
  284. if(self != PY_NULL){
  285. PyObject* ret = call_method(self, len_f);
  286. return CAST(i64, ret) > 0;
  287. }
  288. return true;
  289. }
  290. PyObject* VM::py_list(PyObject* it){
  291. auto _lock = heap.gc_scope_lock();
  292. it = py_iter(it);
  293. List list;
  294. PyObject* obj = py_next(it);
  295. while(obj != StopIteration){
  296. list.push_back(obj);
  297. obj = py_next(it);
  298. }
  299. return VAR(std::move(list));
  300. }
  301. void VM::parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step){
  302. auto clip = [](int value, int min, int max){
  303. if(value < min) return min;
  304. if(value > max) return max;
  305. return value;
  306. };
  307. if(s.step == None) step = 1;
  308. else step = CAST(int, s.step);
  309. if(step == 0) ValueError("slice step cannot be zero");
  310. if(step > 0){
  311. if(s.start == None){
  312. start = 0;
  313. }else{
  314. start = CAST(int, s.start);
  315. if(start < 0) start += length;
  316. start = clip(start, 0, length);
  317. }
  318. if(s.stop == None){
  319. stop = length;
  320. }else{
  321. stop = CAST(int, s.stop);
  322. if(stop < 0) stop += length;
  323. stop = clip(stop, 0, length);
  324. }
  325. }else{
  326. if(s.start == None){
  327. start = length - 1;
  328. }else{
  329. start = CAST(int, s.start);
  330. if(start < 0) start += length;
  331. start = clip(start, -1, length - 1);
  332. }
  333. if(s.stop == None){
  334. stop = -1;
  335. }else{
  336. stop = CAST(int, s.stop);
  337. if(stop < 0) stop += length;
  338. stop = clip(stop, -1, length - 1);
  339. }
  340. }
  341. }
  342. i64 VM::py_hash(PyObject* obj){
  343. // https://docs.python.org/3.10/reference/datamodel.html#object.__hash__
  344. const PyTypeInfo* ti = _inst_type_info(obj);
  345. if(ti->m__hash__) return ti->m__hash__(this, obj);
  346. PyObject* self;
  347. PyObject* f = get_unbound_method(obj, __hash__, &self, false);
  348. if(f != nullptr){
  349. PyObject* ret = call_method(self, f);
  350. return CAST(i64, ret);
  351. }
  352. // if it is trivial `object`, return PK_BITS
  353. if(ti == &_all_types[tp_object]) return PK_BITS(obj);
  354. // otherwise, we check if it has a custom __eq__ other than object.__eq__
  355. bool has_custom_eq = false;
  356. if(ti->m__eq__) has_custom_eq = true;
  357. else{
  358. f = get_unbound_method(obj, __eq__, &self, false);
  359. has_custom_eq = f != _t(tp_object)->attr(__eq__);
  360. }
  361. if(has_custom_eq){
  362. TypeError(fmt("unhashable type: ", ti->name.escape()));
  363. return 0;
  364. }else{
  365. return PK_BITS(obj);
  366. }
  367. }
  368. PyObject* VM::format(Str spec, PyObject* obj){
  369. if(spec.empty()) return py_str(obj);
  370. char type;
  371. switch(spec.end()[-1]){
  372. case 'f': case 'd': case 's':
  373. type = spec.end()[-1];
  374. spec = spec.substr(0, spec.length() - 1);
  375. break;
  376. default: type = ' '; break;
  377. }
  378. char pad_c = ' ';
  379. for(char c: std::string_view("0-=*#@!~")){
  380. if(spec[0] == c){
  381. pad_c = c;
  382. spec = spec.substr(1);
  383. break;
  384. }
  385. }
  386. char align;
  387. if(spec[0] == '^'){
  388. align = '^';
  389. spec = spec.substr(1);
  390. }else if(spec[0] == '>'){
  391. align = '>';
  392. spec = spec.substr(1);
  393. }else if(spec[0] == '<'){
  394. align = '<';
  395. spec = spec.substr(1);
  396. }else{
  397. if(is_int(obj) || is_float(obj)) align = '>';
  398. else align = '<';
  399. }
  400. int dot = spec.index(".");
  401. int width, precision;
  402. try{
  403. if(dot >= 0){
  404. if(dot == 0){
  405. width = -1;
  406. }else{
  407. width = std::stoi(spec.substr(0, dot).str());
  408. }
  409. precision = std::stoi(spec.substr(dot+1).str());
  410. }else{
  411. width = std::stoi(spec.str());
  412. precision = -1;
  413. }
  414. }catch(...){
  415. ValueError("invalid format specifer");
  416. UNREACHABLE();
  417. }
  418. if(type != 'f' && dot >= 0) ValueError("precision not allowed in the format specifier");
  419. Str ret;
  420. if(type == 'f'){
  421. f64 val = CAST(f64, obj);
  422. if(precision < 0) precision = 6;
  423. std::stringstream ss;
  424. ss << std::fixed << std::setprecision(precision) << val;
  425. ret = ss.str();
  426. }else if(type == 'd'){
  427. ret = std::to_string(CAST(i64, obj));
  428. }else if(type == 's'){
  429. ret = CAST(Str&, obj);
  430. }else{
  431. ret = CAST(Str&, py_str(obj));
  432. }
  433. if(width != -1 && width > ret.length()){
  434. int pad = width - ret.length();
  435. if(align == '>' || align == '<'){
  436. std::string padding(pad, pad_c);
  437. if(align == '>') ret = padding.c_str() + ret;
  438. else ret = ret + padding.c_str();
  439. }else{ // ^
  440. int pad_left = pad / 2;
  441. int pad_right = pad - pad_left;
  442. std::string padding_left(pad_left, pad_c);
  443. std::string padding_right(pad_right, pad_c);
  444. ret = padding_left.c_str() + ret + padding_right.c_str();
  445. }
  446. }
  447. return VAR(ret);
  448. }
  449. PyObject* VM::new_module(Str name, Str package) {
  450. PyObject* obj = heap._new<DummyModule>(tp_module);
  451. obj->attr().set(__name__, VAR(name));
  452. obj->attr().set(__package__, VAR(package));
  453. // we do not allow override in order to avoid memory leak
  454. // it is because Module objects are not garbage collected
  455. if(_modules.contains(name)){
  456. throw std::runtime_error(fmt("module ", name.escape(), " already exists"));
  457. }
  458. // convert to fullname and set it into _modules
  459. if(!package.empty()) name = package + "." + name;
  460. obj->attr().set(__path__, VAR(name));
  461. _modules.set(name, obj);
  462. return obj;
  463. }
  464. static std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  465. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  466. switch(byte.op){
  467. case OP_LOAD_CONST: case OP_FORMAT_STRING: case OP_IMPORT_PATH:
  468. if(vm != nullptr){
  469. argStr += fmt(" (", CAST(Str, vm->py_repr(co->consts[byte.arg])), ")");
  470. }
  471. break;
  472. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  473. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  474. case OP_BEGIN_CLASS: case OP_RAISE: case OP_GOTO:
  475. case OP_DELETE_GLOBAL: case OP_INC_GLOBAL: case OP_DEC_GLOBAL: case OP_STORE_CLASS_ATTR:
  476. argStr += fmt(" (", StrName(byte.arg).sv(), ")");
  477. break;
  478. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST: case OP_INC_FAST: case OP_DEC_FAST:
  479. argStr += fmt(" (", co->varnames[byte.arg].sv(), ")");
  480. break;
  481. case OP_LOAD_FUNCTION:
  482. argStr += fmt(" (", co->func_decls[byte.arg]->code->name, ")");
  483. break;
  484. }
  485. return argStr;
  486. }
  487. Str VM::disassemble(CodeObject_ co){
  488. auto pad = [](const Str& s, const int n){
  489. if(s.length() >= n) return s.substr(0, n);
  490. return s + std::string(n - s.length(), ' ');
  491. };
  492. std::vector<int> jumpTargets;
  493. for(auto byte : co->codes){
  494. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE || byte.op == OP_SHORTCUT_IF_FALSE_OR_POP){
  495. jumpTargets.push_back(byte.arg);
  496. }
  497. if(byte.op == OP_GOTO){
  498. // TODO: pre-compute jump targets for OP_GOTO
  499. int* target = co->labels.try_get_2(StrName(byte.arg));
  500. if(target != nullptr) jumpTargets.push_back(*target);
  501. }
  502. }
  503. std::stringstream ss;
  504. int prev_line = -1;
  505. for(int i=0; i<co->codes.size(); i++){
  506. const Bytecode& byte = co->codes[i];
  507. Str line = std::to_string(co->lines[i]);
  508. if(co->lines[i] == prev_line) line = "";
  509. else{
  510. if(prev_line != -1) ss << "\n";
  511. prev_line = co->lines[i];
  512. }
  513. std::string pointer;
  514. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  515. pointer = "-> ";
  516. }else{
  517. pointer = " ";
  518. }
  519. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  520. ss << " " << pad(OP_NAMES[byte.op], 25) << " ";
  521. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  522. std::string argStr = _opcode_argstr(this, byte, co.get());
  523. ss << argStr;
  524. // ss << pad(argStr, 40); // may overflow
  525. // ss << co->blocks[byte.block].type;
  526. if(i != co->codes.size() - 1) ss << '\n';
  527. }
  528. for(auto& decl: co->func_decls){
  529. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  530. ss << disassemble(decl->code);
  531. }
  532. ss << "\n";
  533. return Str(ss.str());
  534. }
  535. #if PK_DEBUG_CEVAL_STEP
  536. void VM::_log_s_data(const char* title) {
  537. if(_main == nullptr) return;
  538. if(callstack.empty()) return;
  539. std::stringstream ss;
  540. if(title) ss << title << " | ";
  541. std::map<PyObject**, int> sp_bases;
  542. for(Frame& f: callstack.data()){
  543. if(f._sp_base == nullptr) FATAL_ERROR();
  544. sp_bases[f._sp_base] += 1;
  545. }
  546. FrameId frame = top_frame();
  547. int line = frame->co->lines[frame->_ip];
  548. ss << frame->co->name << ":" << line << " [";
  549. for(PyObject** p=s_data.begin(); p!=s_data.end(); p++){
  550. ss << std::string(sp_bases[p], '|');
  551. if(sp_bases[p] > 0) ss << " ";
  552. PyObject* obj = *p;
  553. if(obj == nullptr) ss << "(nil)";
  554. else if(obj == PY_NULL) ss << "NULL";
  555. else if(is_int(obj)) ss << CAST(i64, obj);
  556. else if(is_float(obj)) ss << CAST(f64, obj);
  557. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  558. else if(obj == None) ss << "None";
  559. else if(obj == True) ss << "True";
  560. else if(obj == False) ss << "False";
  561. else if(is_type(obj, tp_function)){
  562. auto& f = CAST(Function&, obj);
  563. ss << f.decl->code->name << "(...)";
  564. } else if(is_type(obj, tp_type)){
  565. Type t = PK_OBJ_GET(Type, obj);
  566. ss << "<class " + _all_types[t].name.escape() + ">";
  567. } else if(is_type(obj, tp_list)){
  568. auto& t = CAST(List&, obj);
  569. ss << "list(size=" << t.size() << ")";
  570. } else if(is_type(obj, tp_tuple)){
  571. auto& t = CAST(Tuple&, obj);
  572. ss << "tuple(size=" << t.size() << ")";
  573. } else ss << "(" << obj_type_name(this, obj->type) << ")";
  574. ss << ", ";
  575. }
  576. std::string output = ss.str();
  577. if(!s_data.empty()) {
  578. output.pop_back(); output.pop_back();
  579. }
  580. output.push_back(']');
  581. Bytecode byte = frame->co->codes[frame->_ip];
  582. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  583. }
  584. #endif
  585. void VM::init_builtin_types(){
  586. _all_types.push_back({heap._new<Type>(Type(1), Type(0)), -1, nullptr, "object", true});
  587. _all_types.push_back({heap._new<Type>(Type(1), Type(1)), 0, nullptr, "type", false});
  588. tp_object = 0; tp_type = 1;
  589. tp_int = _new_type_object("int");
  590. tp_float = _new_type_object("float");
  591. if(tp_int.index != kTpIntIndex || tp_float.index != kTpFloatIndex) FATAL_ERROR();
  592. tp_bool = _new_type_object("bool");
  593. tp_str = _new_type_object("str");
  594. tp_list = _new_type_object("list");
  595. tp_tuple = _new_type_object("tuple");
  596. tp_slice = _new_type_object("slice");
  597. tp_range = _new_type_object("range");
  598. tp_module = _new_type_object("module");
  599. tp_function = _new_type_object("function");
  600. tp_native_func = _new_type_object("native_func");
  601. tp_bound_method = _new_type_object("bound_method");
  602. tp_super = _new_type_object("super");
  603. tp_exception = _new_type_object("Exception");
  604. tp_bytes = _new_type_object("bytes");
  605. tp_mappingproxy = _new_type_object("mappingproxy");
  606. tp_dict = _new_type_object("dict");
  607. tp_property = _new_type_object("property");
  608. tp_star_wrapper = _new_type_object("_star_wrapper");
  609. this->None = heap._new<Dummy>(_new_type_object("NoneType"));
  610. this->NotImplemented = heap._new<Dummy>(_new_type_object("NotImplementedType"));
  611. this->Ellipsis = heap._new<Dummy>(_new_type_object("ellipsis"));
  612. this->True = heap._new<Dummy>(tp_bool);
  613. this->False = heap._new<Dummy>(tp_bool);
  614. this->StopIteration = heap._new<Dummy>(_new_type_object("StopIterationType"));
  615. this->builtins = new_module("builtins");
  616. // setup public types
  617. builtins->attr().set("type", _t(tp_type));
  618. builtins->attr().set("object", _t(tp_object));
  619. builtins->attr().set("bool", _t(tp_bool));
  620. builtins->attr().set("int", _t(tp_int));
  621. builtins->attr().set("float", _t(tp_float));
  622. builtins->attr().set("str", _t(tp_str));
  623. builtins->attr().set("list", _t(tp_list));
  624. builtins->attr().set("tuple", _t(tp_tuple));
  625. builtins->attr().set("range", _t(tp_range));
  626. builtins->attr().set("bytes", _t(tp_bytes));
  627. builtins->attr().set("dict", _t(tp_dict));
  628. builtins->attr().set("property", _t(tp_property));
  629. builtins->attr().set("StopIteration", StopIteration);
  630. builtins->attr().set("NotImplemented", NotImplemented);
  631. builtins->attr().set("slice", _t(tp_slice));
  632. post_init();
  633. for(int i=0; i<_all_types.size(); i++){
  634. _all_types[i].obj->attr()._try_perfect_rehash();
  635. }
  636. for(auto [k, v]: _modules.items()) v->attr()._try_perfect_rehash();
  637. this->_main = new_module("__main__");
  638. }
  639. // `heap.gc_scope_lock();` needed before calling this function
  640. void VM::_unpack_as_list(ArgsView args, List& list){
  641. for(PyObject* obj: args){
  642. if(is_non_tagged_type(obj, tp_star_wrapper)){
  643. const StarWrapper& w = _CAST(StarWrapper&, obj);
  644. // maybe this check should be done in the compile time
  645. if(w.level != 1) TypeError("expected level 1 star wrapper");
  646. PyObject* _0 = py_iter(w.obj);
  647. PyObject* _1 = py_next(_0);
  648. while(_1 != StopIteration){
  649. list.push_back(_1);
  650. _1 = py_next(_0);
  651. }
  652. }else{
  653. list.push_back(obj);
  654. }
  655. }
  656. }
  657. // `heap.gc_scope_lock();` needed before calling this function
  658. void VM::_unpack_as_dict(ArgsView args, Dict& dict){
  659. for(PyObject* obj: args){
  660. if(is_non_tagged_type(obj, tp_star_wrapper)){
  661. const StarWrapper& w = _CAST(StarWrapper&, obj);
  662. // maybe this check should be done in the compile time
  663. if(w.level != 2) TypeError("expected level 2 star wrapper");
  664. const Dict& other = CAST(Dict&, w.obj);
  665. dict.update(other);
  666. }else{
  667. const Tuple& t = CAST(Tuple&, obj);
  668. if(t.size() != 2) TypeError("expected tuple of length 2");
  669. dict.set(t[0], t[1]);
  670. }
  671. }
  672. }
  673. void VM::_prepare_py_call(PyObject** buffer, ArgsView args, ArgsView kwargs, const FuncDecl_& decl){
  674. const CodeObject* co = decl->code.get();
  675. int co_nlocals = co->varnames.size();
  676. int decl_argc = decl->args.size();
  677. if(args.size() < decl_argc){
  678. vm->TypeError(fmt(
  679. "expected ", decl_argc, " positional arguments, got ", args.size(),
  680. " (", co->name, ')'
  681. ));
  682. }
  683. int i = 0;
  684. // prepare args
  685. for(int index: decl->args) buffer[index] = args[i++];
  686. // set extra varnames to nullptr
  687. for(int j=i; j<co_nlocals; j++) buffer[j] = PY_NULL;
  688. // prepare kwdefaults
  689. for(auto& kv: decl->kwargs) buffer[kv.key] = kv.value;
  690. // handle *args
  691. if(decl->starred_arg != -1){
  692. ArgsView vargs(args.begin() + i, args.end());
  693. buffer[decl->starred_arg] = VAR(vargs.to_tuple());
  694. i += vargs.size();
  695. }else{
  696. // kwdefaults override
  697. for(auto& kv: decl->kwargs){
  698. if(i >= args.size()) break;
  699. buffer[kv.key] = args[i++];
  700. }
  701. if(i < args.size()) TypeError(fmt("too many arguments", " (", decl->code->name, ')'));
  702. }
  703. PyObject* vkwargs;
  704. if(decl->starred_kwarg != -1){
  705. vkwargs = VAR(Dict(this));
  706. buffer[decl->starred_kwarg] = vkwargs;
  707. }else{
  708. vkwargs = nullptr;
  709. }
  710. for(int j=0; j<kwargs.size(); j+=2){
  711. StrName key(CAST(int, kwargs[j]));
  712. int index = co->varnames_inv.try_get(key);
  713. if(index < 0){
  714. if(vkwargs == nullptr){
  715. TypeError(fmt(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  716. }else{
  717. Dict& dict = _CAST(Dict&, vkwargs);
  718. dict.set(VAR(key.sv()), kwargs[j+1]);
  719. }
  720. }else{
  721. buffer[index] = kwargs[j+1];
  722. }
  723. }
  724. }
  725. PyObject* VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  726. PyObject** p1 = s_data._sp - KWARGC*2;
  727. PyObject** p0 = p1 - ARGC - 2;
  728. // [callable, <self>, args..., kwargs...]
  729. // ^p0 ^p1 ^_sp
  730. PyObject* callable = p1[-(ARGC + 2)];
  731. bool method_call = p1[-(ARGC + 1)] != PY_NULL;
  732. // handle boundmethod, do a patch
  733. if(is_non_tagged_type(callable, tp_bound_method)){
  734. if(method_call) FATAL_ERROR();
  735. auto& bm = CAST(BoundMethod&, callable);
  736. callable = bm.func; // get unbound method
  737. p1[-(ARGC + 2)] = bm.func;
  738. p1[-(ARGC + 1)] = bm.self;
  739. method_call = true;
  740. // [unbound, self, args..., kwargs...]
  741. }
  742. ArgsView args(p1 - ARGC - int(method_call), p1);
  743. ArgsView kwargs(p1, s_data._sp);
  744. PyObject* buffer[PK_MAX_CO_VARNAMES];
  745. if(is_non_tagged_type(callable, tp_native_func)){
  746. const auto& f = PK_OBJ_GET(NativeFunc, callable);
  747. PyObject* ret;
  748. if(f.decl != nullptr){
  749. int co_nlocals = f.decl->code->varnames.size();
  750. _prepare_py_call(buffer, args, kwargs, f.decl);
  751. // copy buffer back to stack
  752. s_data.reset(args.begin());
  753. for(int j=0; j<co_nlocals; j++) PUSH(buffer[j]);
  754. ret = f.call(vm, ArgsView(s_data._sp - co_nlocals, s_data._sp));
  755. }else{
  756. if(KWARGC != 0) TypeError("old-style native_func does not accept keyword arguments");
  757. f.check_size(this, args);
  758. ret = f.call(this, args);
  759. }
  760. s_data.reset(p0);
  761. return ret;
  762. }
  763. if(is_non_tagged_type(callable, tp_function)){
  764. /*****************_py_call*****************/
  765. // callable must be a `function` object
  766. if(s_data.is_overflow()) StackOverflowError();
  767. const Function& fn = PK_OBJ_GET(Function, callable);
  768. const FuncDecl_& decl = fn.decl;
  769. const CodeObject* co = decl->code.get();
  770. int co_nlocals = co->varnames.size();
  771. _prepare_py_call(buffer, args, kwargs, decl);
  772. if(co->is_generator){
  773. s_data.reset(p0);
  774. return _py_generator(
  775. Frame(&s_data, nullptr, co, fn._module, callable),
  776. ArgsView(buffer, buffer + co_nlocals)
  777. );
  778. }
  779. // copy buffer back to stack
  780. s_data.reset(args.begin());
  781. for(int j=0; j<co_nlocals; j++) PUSH(buffer[j]);
  782. callstack.emplace(&s_data, p0, co, fn._module, callable, FastLocals(co, args.begin()));
  783. if(op_call) return PY_OP_CALL;
  784. return _run_top_frame();
  785. /*****************_py_call*****************/
  786. }
  787. if(is_non_tagged_type(callable, tp_type)){
  788. if(method_call) FATAL_ERROR();
  789. // [type, NULL, args..., kwargs...]
  790. PyObject* new_f = find_name_in_mro(callable, __new__);
  791. PyObject* obj;
  792. #if PK_DEBUG_EXTRA_CHECK
  793. PK_ASSERT(new_f != nullptr);
  794. #endif
  795. if(new_f == cached_object__new__) {
  796. // fast path for object.__new__
  797. Type t = PK_OBJ_GET(Type, callable);
  798. obj= vm->heap.gcnew<DummyInstance>(t);
  799. }else{
  800. PUSH(new_f);
  801. PUSH(PY_NULL);
  802. PUSH(callable); // cls
  803. for(PyObject* o: args) PUSH(o);
  804. for(PyObject* o: kwargs) PUSH(o);
  805. // if obj is not an instance of callable, the behavior is undefined
  806. obj = vectorcall(ARGC+1, KWARGC);
  807. }
  808. // __init__
  809. PyObject* self;
  810. callable = get_unbound_method(obj, __init__, &self, false);
  811. if (self != PY_NULL) {
  812. // replace `NULL` with `self`
  813. p1[-(ARGC + 2)] = callable;
  814. p1[-(ARGC + 1)] = self;
  815. // [init_f, self, args..., kwargs...]
  816. vectorcall(ARGC, KWARGC);
  817. // We just discard the return value of `__init__`
  818. // in cpython it raises a TypeError if the return value is not None
  819. }else{
  820. // manually reset the stack
  821. s_data.reset(p0);
  822. }
  823. return obj;
  824. }
  825. // handle `__call__` overload
  826. PyObject* self;
  827. PyObject* call_f = get_unbound_method(callable, __call__, &self, false);
  828. if(self != PY_NULL){
  829. p1[-(ARGC + 2)] = call_f;
  830. p1[-(ARGC + 1)] = self;
  831. // [call_f, self, args..., kwargs...]
  832. return vectorcall(ARGC, KWARGC, false);
  833. }
  834. TypeError(OBJ_NAME(_t(callable)).escape() + " object is not callable");
  835. return nullptr;
  836. }
  837. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  838. PyObject* VM::getattr(PyObject* obj, StrName name, bool throw_err){
  839. PyObject* objtype;
  840. // handle super() proxy
  841. if(is_non_tagged_type(obj, tp_super)){
  842. const Super& super = PK_OBJ_GET(Super, obj);
  843. obj = super.first;
  844. objtype = _t(super.second);
  845. }else{
  846. objtype = _t(obj);
  847. }
  848. PyObject* cls_var = find_name_in_mro(objtype, name);
  849. if(cls_var != nullptr){
  850. // handle descriptor
  851. if(is_non_tagged_type(cls_var, tp_property)){
  852. const Property& prop = _CAST(Property&, cls_var);
  853. return call(prop.getter, obj);
  854. }
  855. }
  856. // handle instance __dict__
  857. if(!is_tagged(obj) && obj->is_attr_valid()){
  858. PyObject* val = obj->attr().try_get(name);
  859. if(val != nullptr) return val;
  860. }
  861. if(cls_var != nullptr){
  862. // bound method is non-data descriptor
  863. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  864. return VAR(BoundMethod(obj, cls_var));
  865. }
  866. return cls_var;
  867. }
  868. if(is_non_tagged_type(obj, tp_module)){
  869. Str path = CAST(Str&, obj->attr(__path__));
  870. path = path + "." + name.sv();
  871. PyObject* mod = py_import(path, false);
  872. if(mod != nullptr){
  873. obj->attr().set(name, mod);
  874. return mod;
  875. }
  876. }
  877. if(throw_err) AttributeError(obj, name);
  878. return nullptr;
  879. }
  880. // used by OP_LOAD_METHOD
  881. // try to load a unbound method (fallback to `getattr` if not found)
  882. PyObject* VM::get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err, bool fallback){
  883. *self = PY_NULL;
  884. PyObject* objtype;
  885. // handle super() proxy
  886. if(is_non_tagged_type(obj, tp_super)){
  887. const Super& super = PK_OBJ_GET(Super, obj);
  888. obj = super.first;
  889. objtype = _t(super.second);
  890. }else{
  891. objtype = _t(obj);
  892. }
  893. PyObject* cls_var = find_name_in_mro(objtype, name);
  894. if(fallback){
  895. if(cls_var != nullptr){
  896. // handle descriptor
  897. if(is_non_tagged_type(cls_var, tp_property)){
  898. const Property& prop = _CAST(Property&, cls_var);
  899. return call(prop.getter, obj);
  900. }
  901. }
  902. // handle instance __dict__
  903. if(!is_tagged(obj) && obj->is_attr_valid()){
  904. PyObject* val = obj->attr().try_get(name);
  905. if(val != nullptr) return val;
  906. }
  907. }
  908. if(cls_var != nullptr){
  909. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  910. *self = obj;
  911. }
  912. return cls_var;
  913. }
  914. if(throw_err) AttributeError(obj, name);
  915. return nullptr;
  916. }
  917. void VM::setattr(PyObject* obj, StrName name, PyObject* value){
  918. PyObject* objtype;
  919. // handle super() proxy
  920. if(is_non_tagged_type(obj, tp_super)){
  921. Super& super = PK_OBJ_GET(Super, obj);
  922. obj = super.first;
  923. objtype = _t(super.second);
  924. }else{
  925. objtype = _t(obj);
  926. }
  927. PyObject* cls_var = find_name_in_mro(objtype, name);
  928. if(cls_var != nullptr){
  929. // handle descriptor
  930. if(is_non_tagged_type(cls_var, tp_property)){
  931. const Property& prop = _CAST(Property&, cls_var);
  932. if(prop.setter != vm->None){
  933. call(prop.setter, obj, value);
  934. }else{
  935. TypeError(fmt("readonly attribute: ", name.escape()));
  936. }
  937. return;
  938. }
  939. }
  940. // handle instance __dict__
  941. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  942. obj->attr().set(name, value);
  943. }
  944. PyObject* VM::bind(PyObject* obj, const char* sig, NativeFuncC fn, UserData userdata){
  945. return bind(obj, sig, nullptr, fn, userdata);
  946. }
  947. PyObject* VM::bind(PyObject* obj, const char* sig, const char* docstring, NativeFuncC fn, UserData userdata){
  948. CodeObject_ co;
  949. try{
  950. // fn(a, b, *c, d=1) -> None
  951. co = compile("def " + Str(sig) + " : pass", "<bind>", EXEC_MODE);
  952. }catch(Exception&){
  953. throw std::runtime_error("invalid signature: " + std::string(sig));
  954. }
  955. if(co->func_decls.size() != 1){
  956. throw std::runtime_error("expected 1 function declaration");
  957. }
  958. FuncDecl_ decl = co->func_decls[0];
  959. decl->signature = Str(sig);
  960. if(docstring != nullptr){
  961. decl->docstring = Str(docstring).strip();
  962. }
  963. PyObject* f_obj = VAR(NativeFunc(fn, decl));
  964. PK_OBJ_GET(NativeFunc, f_obj).set_userdata(userdata);
  965. if(obj != nullptr) obj->attr().set(decl->code->name, f_obj);
  966. return f_obj;
  967. }
  968. PyObject* VM::bind_property(PyObject* obj, Str name, NativeFuncC fget, NativeFuncC fset){
  969. PyObject* _0 = heap.gcnew<NativeFunc>(tp_native_func, fget, 1, false);
  970. PyObject* _1 = vm->None;
  971. if(fset != nullptr) _1 = heap.gcnew<NativeFunc>(tp_native_func, fset, 2, false);
  972. Str signature = name;
  973. int pos = name.index(":");
  974. if(pos > 0) name = name.substr(0, pos).strip();
  975. PyObject* prop = VAR(Property(_0, _1, signature));
  976. obj->attr().set(name, prop);
  977. return prop;
  978. }
  979. void VM::_error(Exception e){
  980. if(callstack.empty()){
  981. e.is_re = false;
  982. throw e;
  983. }
  984. PUSH(VAR(std::move(e)));
  985. _raise();
  986. }
  987. void VM::_raise(bool re_raise){
  988. Frame* frame = top_frame().get();
  989. Exception& e = PK_OBJ_GET(Exception, s_data.top());
  990. if(!re_raise){
  991. e._ip_on_error = frame->_ip;
  992. e._code_on_error = (void*)frame->co;
  993. }
  994. bool ok = frame->jump_to_exception_handler();
  995. int actual_ip = frame->_ip;
  996. if(e._ip_on_error >= 0 && e._code_on_error == (void*)frame->co) actual_ip = e._ip_on_error;
  997. int current_line = frame->co->lines[actual_ip]; // current line
  998. auto current_f_name = frame->co->name.sv(); // current function name
  999. if(frame->_callable == nullptr) current_f_name = ""; // not in a function
  1000. e.st_push(frame->co->src, current_line, nullptr, current_f_name);
  1001. if(ok) throw HandledException();
  1002. else throw UnhandledException();
  1003. }
  1004. void ManagedHeap::mark() {
  1005. for(PyObject* obj: _no_gc) PK_OBJ_MARK(obj);
  1006. for(auto& frame : vm->callstack.data()) frame._gc_mark();
  1007. for(PyObject* obj: vm->s_data) PK_OBJ_MARK(obj);
  1008. if(_gc_marker_ex) _gc_marker_ex(vm);
  1009. if(vm->_last_exception) PK_OBJ_MARK(vm->_last_exception);
  1010. if(vm->_c.error != nullptr) PK_OBJ_MARK(vm->_c.error);
  1011. }
  1012. Str obj_type_name(VM *vm, Type type){
  1013. return vm->_all_types[type].name;
  1014. }
  1015. void VM::bind__hash__(Type type, i64 (*f)(VM*, PyObject*)){
  1016. PyObject* obj = _t(type);
  1017. _all_types[type].m__hash__ = f;
  1018. PyObject* nf = bind_method<0>(obj, "__hash__", [](VM* vm, ArgsView args){
  1019. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1020. return VAR(ret);
  1021. });
  1022. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1023. }
  1024. void VM::bind__len__(Type type, i64 (*f)(VM*, PyObject*)){
  1025. PyObject* obj = _t(type);
  1026. _all_types[type].m__len__ = f;
  1027. PyObject* nf = bind_method<0>(obj, "__len__", [](VM* vm, ArgsView args){
  1028. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1029. return VAR(ret);
  1030. });
  1031. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1032. }
  1033. void Dict::_probe_0(PyObject *key, bool &ok, int &i) const{
  1034. ok = false;
  1035. i64 hash = vm->py_hash(key);
  1036. i = hash & _mask;
  1037. // std::cout << CAST(Str, vm->py_repr(key)) << " " << hash << " " << i << std::endl;
  1038. for(int j=0; j<_capacity; j++) {
  1039. if(_items[i].first != nullptr){
  1040. if(vm->py_equals(_items[i].first, key)) { ok = true; break; }
  1041. }else{
  1042. if(_items[i].second == nullptr) break;
  1043. }
  1044. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1045. i = ((5*i) + 1) & _mask;
  1046. // std::cout << CAST(Str, vm->py_repr(key)) << " next: " << i << std::endl;
  1047. }
  1048. }
  1049. void Dict::_probe_1(PyObject *key, bool &ok, int &i) const{
  1050. ok = false;
  1051. i = vm->py_hash(key) & _mask;
  1052. while(_items[i].first != nullptr) {
  1053. if(vm->py_equals(_items[i].first, key)) { ok = true; break; }
  1054. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1055. i = ((5*i) + 1) & _mask;
  1056. }
  1057. }
  1058. void CodeObjectSerializer::write_object(VM *vm, PyObject *obj){
  1059. if(is_int(obj)) write_int(_CAST(i64, obj));
  1060. else if(is_float(obj)) write_float(_CAST(f64, obj));
  1061. else if(is_type(obj, vm->tp_str)) write_str(_CAST(Str&, obj));
  1062. else if(is_type(obj, vm->tp_bool)) write_bool(_CAST(bool, obj));
  1063. else if(obj == vm->None) write_none();
  1064. else if(obj == vm->Ellipsis) write_ellipsis();
  1065. else{
  1066. throw std::runtime_error(fmt(OBJ_NAME(vm->_t(obj)).escape(), " is not serializable"));
  1067. }
  1068. }
  1069. void NativeFunc::check_size(VM* vm, ArgsView args) const{
  1070. if(args.size() != argc && argc != -1) {
  1071. vm->TypeError(fmt("expected ", argc, " arguments, got ", args.size()));
  1072. }
  1073. }
  1074. PyObject* NativeFunc::call(VM *vm, ArgsView args) const {
  1075. return f(vm, args);
  1076. }
  1077. } // namespace pkpy