vm.cpp 44 KB

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