vm.cpp 43 KB

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