vm.cpp 43 KB

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