vm.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. #include "pocketpy/vm.h"
  2. static const char* OP_NAMES[] = {
  3. #define OPCODE(name) #name,
  4. #include "pocketpy/opcodes.h"
  5. #undef OPCODE
  6. };
  7. namespace pkpy{
  8. struct JsonSerializer{
  9. VM* vm;
  10. PyVar root;
  11. SStream ss;
  12. JsonSerializer(VM* vm, PyVar root) : vm(vm), root(root) {}
  13. template<typename T>
  14. void write_array(T& arr){
  15. ss << '[';
  16. for(int i=0; i<arr.size(); i++){
  17. if(i != 0) ss << ", ";
  18. write_object(arr[i]);
  19. }
  20. ss << ']';
  21. }
  22. void write_dict(Dict& dict){
  23. ss << '{';
  24. bool first = true;
  25. dict.apply([&](PyVar k, PyVar v){
  26. if(!first) ss << ", ";
  27. first = false;
  28. if(!is_type(k, VM::tp_str)){
  29. vm->TypeError(_S("json keys must be string, got ", _type_name(vm, vm->_tp(k))));
  30. }
  31. ss << _CAST(Str&, k).escape(false) << ": ";
  32. write_object(v);
  33. });
  34. ss << '}';
  35. }
  36. void write_object(PyVar obj){
  37. Type obj_t = vm->_tp(obj);
  38. if(obj == vm->None){
  39. ss << "null";
  40. }else if(obj_t == vm->tp_int){
  41. ss << _CAST(i64, obj);
  42. }else if(obj_t == vm->tp_float){
  43. f64 val = _CAST(f64, obj);
  44. if(std::isinf(val) || std::isnan(val)) vm->ValueError("cannot jsonify 'nan' or 'inf'");
  45. ss << val;
  46. }else if(obj_t == vm->tp_bool){
  47. ss << (obj == vm->True ? "true" : "false");
  48. }else if(obj_t == vm->tp_str){
  49. _CAST(Str&, obj).escape_(ss, false);
  50. }else if(obj_t == vm->tp_list){
  51. write_array<List>(_CAST(List&, obj));
  52. }else if(obj_t == vm->tp_tuple){
  53. write_array<Tuple>(_CAST(Tuple&, obj));
  54. }else if(obj_t == vm->tp_dict){
  55. write_dict(_CAST(Dict&, obj));
  56. }else{
  57. vm->TypeError(_S("unrecognized type ", _type_name(vm, obj_t).escape()));
  58. }
  59. }
  60. Str serialize(){
  61. auto _lock = vm->heap.gc_scope_lock();
  62. write_object(root);
  63. return ss.str();
  64. }
  65. };
  66. VM::VM(bool enable_os) : heap(this), enable_os(enable_os) {
  67. this->vm = this;
  68. this->__c.error = nullptr;
  69. _ceval_on_step = nullptr;
  70. _stdout = [](const char* buf, int size) { std::cout.write(buf, size); };
  71. _stderr = [](const char* buf, int size) { std::cerr.write(buf, size); };
  72. _main = nullptr;
  73. __last_exception = nullptr;
  74. _import_handler = [](const char* name, int* out_size) -> unsigned char*{ return nullptr; };
  75. __init_builtin_types();
  76. }
  77. Str VM::py_str(PyVar obj){
  78. const PyTypeInfo* ti = _tp_info(obj);
  79. if(ti->m__str__) return ti->m__str__(this, obj);
  80. PyVar self;
  81. PyVar f = get_unbound_method(obj, __str__, &self, false);
  82. if(self != PY_NULL){
  83. PyVar retval = call_method(self, f);
  84. if(!is_type(retval, tp_str)){
  85. throw std::runtime_error("object.__str__ must return str");
  86. }
  87. return PK_OBJ_GET(Str, retval);
  88. }
  89. return py_repr(obj);
  90. }
  91. Str VM::py_repr(PyVar obj){
  92. const PyTypeInfo* ti = _tp_info(obj);
  93. if(ti->m__repr__) return ti->m__repr__(this, obj);
  94. PyVar retval = call_method(obj, __repr__);
  95. if(!is_type(retval, tp_str)){
  96. throw std::runtime_error("object.__repr__ must return str");
  97. }
  98. return PK_OBJ_GET(Str, retval);
  99. }
  100. Str VM::py_json(PyVar obj){
  101. auto j = JsonSerializer(this, obj);
  102. return j.serialize();
  103. }
  104. PyVar VM::py_iter(PyVar obj){
  105. const PyTypeInfo* ti = _tp_info(obj);
  106. if(ti->m__iter__) return ti->m__iter__(this, obj);
  107. PyVar self;
  108. PyVar iter_f = get_unbound_method(obj, __iter__, &self, false);
  109. if(self != PY_NULL) return call_method(self, iter_f);
  110. TypeError(_type_name(vm, _tp(obj)).escape() + " object is not iterable");
  111. return nullptr;
  112. }
  113. ArgsView VM::cast_array_view(PyVar obj){
  114. if(is_type(obj, VM::tp_list)){
  115. List& list = PK_OBJ_GET(List, obj);
  116. return ArgsView(list.begin(), list.end());
  117. }else if(is_type(obj, VM::tp_tuple)){
  118. Tuple& tuple = PK_OBJ_GET(Tuple, obj);
  119. return ArgsView(tuple.begin(), tuple.end());
  120. }
  121. TypeError(_S("expected list or tuple, got ", _type_name(this, _tp(obj)).escape()));
  122. PK_UNREACHABLE();
  123. }
  124. void VM::set_main_argv(int argc, char** argv){
  125. PyVar mod = vm->_modules["sys"];
  126. List argv_(argc);
  127. for(int i=0; i<argc; i++) argv_[i] = VAR(std::string_view(argv[i]));
  128. mod->attr().set("argv", VAR(std::move(argv_)));
  129. }
  130. PyVar VM::find_name_in_mro(Type cls, StrName name){
  131. PyVar val;
  132. do{
  133. val = _t(cls)->attr().try_get(name);
  134. if(val != nullptr) return val;
  135. cls = _all_types[cls].base;
  136. if(!cls) break;
  137. }while(true);
  138. return nullptr;
  139. }
  140. bool VM::isinstance(PyVar obj, Type base){
  141. return issubclass(_tp(obj), base);
  142. }
  143. bool VM::issubclass(Type cls, Type base){
  144. do{
  145. if(cls == base) return true;
  146. Type next = _all_types[cls].base;
  147. if(!next) break;
  148. cls = next;
  149. }while(true);
  150. return false;
  151. }
  152. PyVar VM::exec(std::string_view source, Str filename, CompileMode mode, PyVar _module){
  153. if(_module == nullptr) _module = _main;
  154. try {
  155. #if PK_DEBUG_PRECOMPILED_EXEC == 1
  156. Str precompiled = vm->precompile(source, filename, mode);
  157. source = precompiled.sv();
  158. #endif
  159. CodeObject_ code = compile(source, filename, mode);
  160. return _exec(code, _module);
  161. }catch (const Exception& e){
  162. stderr_write(e.summary() + "\n");
  163. }
  164. catch(const std::exception& e) {
  165. Str msg = "An std::exception occurred! It could be a bug.\n";
  166. msg = msg + e.what() + "\n";
  167. stderr_write(msg);
  168. }
  169. catch(NeedMoreLines){
  170. throw;
  171. }
  172. catch(...) {
  173. Str msg = "An unknown exception occurred! It could be a bug. Please report it to @blueloveTH on GitHub.\n";
  174. stderr_write(msg);
  175. }
  176. callstack.clear();
  177. s_data.clear();
  178. return nullptr;
  179. }
  180. PyVar VM::exec(std::string_view source){
  181. return exec(source, "main.py", EXEC_MODE);
  182. }
  183. PyVar VM::eval(std::string_view source){
  184. return exec(source, "<eval>", EVAL_MODE);
  185. }
  186. PyVar VM::new_type_object(PyVar mod, StrName name, Type base, bool subclass_enabled, PyTypeInfo::Vt vt){
  187. PyVar obj = heap._new<Type>(tp_type, Type(_all_types.size()));
  188. const PyTypeInfo& base_info = _all_types[base];
  189. if(!base_info.subclass_enabled){
  190. Str error = _S("type ", base_info.name.escape(), " is not `subclass_enabled`");
  191. throw std::runtime_error(error.c_str());
  192. }
  193. _all_types.emplace_back(obj, base, mod, name, subclass_enabled, vt);
  194. return obj;
  195. }
  196. bool VM::py_eq(PyVar lhs, PyVar rhs){
  197. if(is_int(lhs) && is_int(rhs)) return lhs.as<i64>() == rhs.as<i64>();
  198. const PyTypeInfo* ti = _tp_info(lhs);
  199. PyVar res;
  200. if(ti->m__eq__){
  201. res = ti->m__eq__(this, lhs, rhs);
  202. if(!is_not_implemented(res)) return res == vm->True;
  203. }
  204. res = call_method(lhs, __eq__, rhs);
  205. if(!is_not_implemented(res)) return res == vm->True;
  206. ti = _tp_info(rhs);
  207. if(ti->m__eq__){
  208. res = ti->m__eq__(this, rhs, lhs);
  209. if(!is_not_implemented(res)) return res == vm->True;
  210. }
  211. res = call_method(rhs, __eq__, lhs);
  212. if(!is_not_implemented(res)) return res == vm->True;
  213. return false;
  214. }
  215. PyVar VM::py_op(std::string_view name){
  216. PyVar func;
  217. auto it = __cached_op_funcs.find(name);
  218. if(it == __cached_op_funcs.end()){
  219. func = py_import("operator")->attr(StrName::get(name));
  220. __cached_op_funcs[name] = func;
  221. }else{
  222. func = it->second;
  223. }
  224. return func;
  225. }
  226. i64 VM::normalized_index(i64 index, int size){
  227. if(index < 0) index += size;
  228. if(index < 0 || index >= size){
  229. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  230. }
  231. return index;
  232. }
  233. PyVar VM::_py_next(const PyTypeInfo* ti, PyVar obj){
  234. if(ti->m__next__){
  235. unsigned n = ti->m__next__(this, obj);
  236. return __pack_next_retval(n);
  237. }
  238. return call_method(obj, __next__);
  239. }
  240. PyVar VM::py_next(PyVar obj){
  241. const PyTypeInfo* ti = _tp_info(obj);
  242. return _py_next(ti, obj);
  243. }
  244. bool VM::py_callable(PyVar obj){
  245. Type cls = vm->_tp(obj);
  246. switch(cls.index){
  247. case VM::tp_function.index: return true;
  248. case VM::tp_native_func.index: return true;
  249. case VM::tp_bound_method.index: return true;
  250. case VM::tp_type.index: return true;
  251. }
  252. return vm->find_name_in_mro(cls, __call__) != nullptr;
  253. }
  254. PyVar VM::__minmax_reduce(bool (VM::*op)(PyVar, PyVar), PyVar args, PyVar key){
  255. auto _lock = heap.gc_scope_lock();
  256. const Tuple& args_tuple = PK_OBJ_GET(Tuple, args); // from *args, it must be a tuple
  257. if(key==vm->None && args_tuple.size()==2){
  258. // fast path
  259. PyVar a = args_tuple[0];
  260. PyVar b = args_tuple[1];
  261. return (this->*op)(a, b) ? a : b;
  262. }
  263. if(args_tuple.size() == 0) TypeError("expected at least 1 argument, got 0");
  264. ArgsView view(nullptr, nullptr);
  265. if(args_tuple.size()==1){
  266. view = cast_array_view(args_tuple[0]);
  267. }else{
  268. view = ArgsView(args_tuple);
  269. }
  270. if(view.empty()) ValueError("arg is an empty sequence");
  271. PyVar res = view[0];
  272. if(key == vm->None){
  273. for(int i=1; i<view.size(); i++){
  274. if((this->*op)(view[i], res)) res = view[i];
  275. }
  276. }else{
  277. auto _lock = heap.gc_scope_lock();
  278. for(int i=1; i<view.size(); i++){
  279. PyVar a = call(key, view[i]);
  280. PyVar b = call(key, res);
  281. if((this->*op)(a, b)) res = view[i];
  282. }
  283. }
  284. return res;
  285. }
  286. PyVar VM::py_import(Str path, bool throw_err){
  287. if(path.empty()) vm->ValueError("empty module name");
  288. static auto f_join = [](const pod_vector<std::string_view>& cpnts){
  289. SStream ss;
  290. for(int i=0; i<cpnts.size(); i++){
  291. if(i != 0) ss << ".";
  292. ss << cpnts[i];
  293. }
  294. return ss.str();
  295. };
  296. if(path[0] == '.'){
  297. if(__import_context.pending.empty()){
  298. ImportError("relative import outside of package");
  299. }
  300. Str curr_path = __import_context.pending.back();
  301. bool curr_is_init = __import_context.pending_is_init.back();
  302. // convert relative path to absolute path
  303. pod_vector<std::string_view> cpnts = curr_path.split('.');
  304. int prefix = 0; // how many dots in the prefix
  305. for(int i=0; i<path.length(); i++){
  306. if(path[i] == '.') prefix++;
  307. else break;
  308. }
  309. if(prefix > cpnts.size()) ImportError("attempted relative import beyond top-level package");
  310. path = path.substr(prefix); // remove prefix
  311. for(int i=(int)curr_is_init; i<prefix; i++) cpnts.pop_back();
  312. if(!path.empty()) cpnts.push_back(path.sv());
  313. path = f_join(cpnts);
  314. }
  315. PK_ASSERT(path.begin()[0] != '.' && path.end()[-1] != '.');
  316. // check existing module
  317. StrName name(path);
  318. PyVar ext_mod = _modules.try_get(name);
  319. if(ext_mod != nullptr) return ext_mod;
  320. pod_vector<std::string_view> path_cpnts = path.split('.');
  321. // check circular import
  322. if(__import_context.pending.size() > 128){
  323. ImportError("maximum recursion depth exceeded while importing");
  324. }
  325. // try import
  326. Str filename = path.replace('.', PK_PLATFORM_SEP) + ".py";
  327. Str source;
  328. bool is_init = false;
  329. auto it = _lazy_modules.find(name);
  330. if(it == _lazy_modules.end()){
  331. int out_size;
  332. unsigned char* out = _import_handler(filename.c_str(), &out_size);
  333. if(out == nullptr){
  334. filename = path.replace('.', PK_PLATFORM_SEP).str() + PK_PLATFORM_SEP + "__init__.py";
  335. is_init = true;
  336. out = _import_handler(filename.c_str(), &out_size);
  337. }
  338. if(out == nullptr){
  339. if(throw_err) ImportError(_S("module ", path.escape(), " not found"));
  340. else return nullptr;
  341. }
  342. PK_ASSERT(out_size >= 0)
  343. source = Str(std::string_view((char*)out, out_size));
  344. free(out);
  345. }else{
  346. source = it->second;
  347. _lazy_modules.erase(it);
  348. }
  349. auto _ = __import_context.scope(path, is_init);
  350. CodeObject_ code = compile(source, filename, EXEC_MODE);
  351. Str name_cpnt = path_cpnts.back();
  352. path_cpnts.pop_back();
  353. PyVar new_mod = new_module(name_cpnt, f_join(path_cpnts));
  354. _exec(code, new_mod);
  355. return new_mod;
  356. }
  357. VM::~VM() {
  358. // clear managed heap
  359. for(PyObject* obj: heap.gen) heap._delete(obj);
  360. for(PyObject* obj: heap._no_gc) heap._delete(obj);
  361. // clear everything
  362. callstack.clear();
  363. s_data.clear();
  364. _all_types.clear();
  365. _modules.clear();
  366. _lazy_modules.clear();
  367. }
  368. PyVar VM::py_negate(PyVar obj){
  369. const PyTypeInfo* ti = _tp_info(obj);
  370. if(ti->m__neg__) return ti->m__neg__(this, obj);
  371. return call_method(obj, __neg__);
  372. }
  373. bool VM::__py_bool_non_trivial(PyVar obj){
  374. if(obj == None) return false;
  375. if(is_int(obj)) return _CAST(i64, obj) != 0;
  376. if(is_float(obj)) return _CAST(f64, obj) != 0.0;
  377. PyVar self;
  378. PyVar len_f = get_unbound_method(obj, __len__, &self, false);
  379. if(self != PY_NULL){
  380. PyVar ret = call_method(self, len_f);
  381. return CAST(i64, ret) != 0;
  382. }
  383. return true;
  384. }
  385. void VM::__obj_gc_mark(PyObject* obj){
  386. obj->gc_marked = true;
  387. const PyTypeInfo* ti = _tp_info(obj->type);
  388. if(ti->vt._gc_mark) ti->vt._gc_mark(obj->_value_ptr(), this);
  389. if(obj->is_attr_valid()){
  390. obj->attr().apply([this](StrName _, PyVar obj){
  391. PK_OBJ_MARK(obj);
  392. });
  393. }
  394. }
  395. List VM::py_list(PyVar it){
  396. auto _lock = heap.gc_scope_lock();
  397. it = py_iter(it);
  398. List list;
  399. const PyTypeInfo* info = _tp_info(it);
  400. PyVar obj = _py_next(info, it);
  401. while(obj != StopIteration){
  402. list.push_back(obj);
  403. obj = _py_next(info, it);
  404. }
  405. return list;
  406. }
  407. void VM::parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step){
  408. auto clip = [](int value, int min, int max){
  409. if(value < min) return min;
  410. if(value > max) return max;
  411. return value;
  412. };
  413. if(s.step == None) step = 1;
  414. else step = CAST(int, s.step);
  415. if(step == 0) ValueError("slice step cannot be zero");
  416. if(step > 0){
  417. if(s.start == None){
  418. start = 0;
  419. }else{
  420. start = CAST(int, s.start);
  421. if(start < 0) start += length;
  422. start = clip(start, 0, length);
  423. }
  424. if(s.stop == None){
  425. stop = length;
  426. }else{
  427. stop = CAST(int, s.stop);
  428. if(stop < 0) stop += length;
  429. stop = clip(stop, 0, length);
  430. }
  431. }else{
  432. if(s.start == None){
  433. start = length - 1;
  434. }else{
  435. start = CAST(int, s.start);
  436. if(start < 0) start += length;
  437. start = clip(start, -1, length - 1);
  438. }
  439. if(s.stop == None){
  440. stop = -1;
  441. }else{
  442. stop = CAST(int, s.stop);
  443. if(stop < 0) stop += length;
  444. stop = clip(stop, -1, length - 1);
  445. }
  446. }
  447. }
  448. i64 VM::py_hash(PyVar obj){
  449. // https://docs.python.org/3.10/reference/datamodel.html#object.__hash__
  450. const PyTypeInfo* ti = _tp_info(obj);
  451. if(ti->m__hash__) return ti->m__hash__(this, obj);
  452. PyVar self;
  453. PyVar f = get_unbound_method(obj, __hash__, &self, false);
  454. if(f != nullptr){
  455. PyVar ret = call_method(self, f);
  456. return CAST(i64, ret);
  457. }
  458. // if it is trivial `object`, return PK_BITS
  459. if(ti == &_all_types[tp_object]) return obj.hash();
  460. // otherwise, we check if it has a custom __eq__ other than object.__eq__
  461. bool has_custom_eq = false;
  462. if(ti->m__eq__) has_custom_eq = true;
  463. else{
  464. f = get_unbound_method(obj, __eq__, &self, false);
  465. has_custom_eq = f != _t(tp_object)->attr(__eq__);
  466. }
  467. if(has_custom_eq){
  468. TypeError(_S("unhashable type: ", ti->name.escape()));
  469. PK_UNREACHABLE()
  470. }else{
  471. return obj.hash();
  472. }
  473. }
  474. PyVar VM::__py_exec_internal(const CodeObject_& code, PyVar globals, PyVar locals){
  475. Frame* frame = &vm->callstack.top();
  476. // fast path
  477. if(globals == vm->None && locals == vm->None){
  478. return vm->_exec(code.get(), frame->_module, frame->_callable, frame->_locals);
  479. }
  480. auto _lock = heap.gc_scope_lock(); // for safety
  481. PyVar globals_obj = nullptr;
  482. Dict* globals_dict = nullptr;
  483. NameDict_ locals_closure = nullptr;
  484. Dict* locals_dict = nullptr;
  485. if(globals == vm->None){
  486. globals_obj = frame->_module;
  487. }else{
  488. if(is_type(globals, VM::tp_mappingproxy)){
  489. globals_obj = PK_OBJ_GET(MappingProxy, globals).obj;
  490. }else{
  491. check_compatible_type(globals, VM::tp_dict);
  492. // make a temporary object and copy globals into it
  493. globals_obj = new_object<DummyInstance>(VM::tp_object);
  494. globals_obj->_enable_instance_dict();
  495. globals_dict = &PK_OBJ_GET(Dict, globals);
  496. globals_dict->apply([&](PyVar k, PyVar v){
  497. globals_obj->attr().set(CAST(Str&, k), v);
  498. });
  499. }
  500. }
  501. PyVar retval = nullptr;
  502. if(locals == vm->None){
  503. retval = vm->_exec(code, globals_obj); // only globals
  504. }else{
  505. check_compatible_type(locals, VM::tp_dict);
  506. locals_dict = &PK_OBJ_GET(Dict, locals);
  507. locals_closure = std::make_shared<NameDict>();
  508. locals_dict->apply([&](PyVar k, PyVar v){
  509. locals_closure->set(CAST(Str&, k), v);
  510. });
  511. PyVar _callable = VAR(Function(__dynamic_func_decl, globals_obj, nullptr, locals_closure));
  512. retval = vm->_exec(code.get(), globals_obj, _callable, vm->s_data._sp);
  513. }
  514. if(globals_dict){
  515. globals_dict->clear();
  516. globals_obj->attr().apply([&](StrName k, PyVar v){
  517. globals_dict->set(vm, VAR(k.sv()), v);
  518. });
  519. }
  520. if(locals_dict){
  521. locals_dict->clear();
  522. locals_closure->apply([&](StrName k, PyVar v){
  523. locals_dict->set(vm, VAR(k.sv()), v);
  524. });
  525. }
  526. return retval;
  527. }
  528. void VM::py_exec(std::string_view source, PyVar globals, PyVar locals){
  529. CodeObject_ code = vm->compile(source, "<exec>", EXEC_MODE, true);
  530. __py_exec_internal(code, globals, locals);
  531. }
  532. PyVar VM::py_eval(std::string_view source, PyVar globals, PyVar locals){
  533. CodeObject_ code = vm->compile(source, "<eval>", EVAL_MODE, true);
  534. return __py_exec_internal(code, globals, locals);
  535. }
  536. PyVar VM::__format_object(PyVar obj, Str spec){
  537. if(spec.empty()) return VAR(py_str(obj));
  538. char type;
  539. switch(spec.end()[-1]){
  540. case 'f': case 'd': case 's':
  541. type = spec.end()[-1];
  542. spec = spec.substr(0, spec.length() - 1);
  543. break;
  544. default: type = ' '; break;
  545. }
  546. char pad_c = ' ';
  547. for(char c: std::string_view("0-=*#@!~")){
  548. if(spec[0] == c){
  549. pad_c = c;
  550. spec = spec.substr(1);
  551. break;
  552. }
  553. }
  554. char align;
  555. if(spec[0] == '^'){
  556. align = '^';
  557. spec = spec.substr(1);
  558. }else if(spec[0] == '>'){
  559. align = '>';
  560. spec = spec.substr(1);
  561. }else if(spec[0] == '<'){
  562. align = '<';
  563. spec = spec.substr(1);
  564. }else{
  565. if(is_int(obj) || is_float(obj)) align = '>';
  566. else align = '<';
  567. }
  568. int dot = spec.index(".");
  569. int width, precision;
  570. try{
  571. if(dot >= 0){
  572. if(dot == 0){
  573. width = -1;
  574. }else{
  575. width = std::stoi(spec.substr(0, dot).str());
  576. }
  577. precision = std::stoi(spec.substr(dot+1).str());
  578. }else{
  579. width = std::stoi(spec.str());
  580. precision = -1;
  581. }
  582. }catch(...){
  583. ValueError("invalid format specifer");
  584. }
  585. if(type != 'f' && dot >= 0) ValueError("precision not allowed in the format specifier");
  586. Str ret;
  587. if(type == 'f'){
  588. f64 val = CAST(f64, obj);
  589. if(precision < 0) precision = 6;
  590. SStream ss;
  591. ss.setprecision(precision);
  592. ss << val;
  593. ret = ss.str();
  594. }else if(type == 'd'){
  595. ret = std::to_string(CAST(i64, obj));
  596. }else if(type == 's'){
  597. ret = CAST(Str&, obj);
  598. }else{
  599. ret = py_str(obj);
  600. }
  601. if(width != -1 && width > ret.length()){
  602. int pad = width - ret.length();
  603. if(align == '>' || align == '<'){
  604. std::string padding(pad, pad_c);
  605. if(align == '>') ret = padding.c_str() + ret;
  606. else ret = ret + padding.c_str();
  607. }else{ // ^
  608. int pad_left = pad / 2;
  609. int pad_right = pad - pad_left;
  610. std::string padding_left(pad_left, pad_c);
  611. std::string padding_right(pad_right, pad_c);
  612. ret = padding_left.c_str() + ret + padding_right.c_str();
  613. }
  614. }
  615. return VAR(ret);
  616. }
  617. PyVar VM::new_module(Str name, Str package) {
  618. PyVar obj = heap._new<DummyModule>(tp_module);
  619. obj->attr().set(__name__, VAR(name));
  620. obj->attr().set(__package__, VAR(package));
  621. // convert to fullname
  622. if(!package.empty()) name = package + "." + name;
  623. obj->attr().set(__path__, VAR(name));
  624. // we do not allow override in order to avoid memory leak
  625. // it is because Module objects are not garbage collected
  626. if(_modules.contains(name)){
  627. throw std::runtime_error(_S("module ", name.escape(), " already exists").str());
  628. }
  629. // set it into _modules
  630. _modules.set(name, obj);
  631. return obj;
  632. }
  633. static std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  634. std::string argStr = std::to_string(byte.arg);
  635. switch(byte.op){
  636. case OP_LOAD_CONST: case OP_FORMAT_STRING: case OP_IMPORT_PATH:
  637. if(vm != nullptr){
  638. argStr += _S(" (", vm->py_repr(co->consts[byte.arg]), ")").sv();
  639. }
  640. break;
  641. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  642. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  643. case OP_BEGIN_CLASS: case OP_GOTO:
  644. case OP_DELETE_GLOBAL: case OP_INC_GLOBAL: case OP_DEC_GLOBAL: case OP_STORE_CLASS_ATTR: case OP_FOR_ITER_STORE_GLOBAL:
  645. argStr += _S(" (", StrName(byte.arg).sv(), ")").sv();
  646. break;
  647. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST: case OP_INC_FAST: case OP_DEC_FAST:
  648. case OP_FOR_ITER_STORE_FAST: case OP_LOAD_SUBSCR_FAST: case OP_STORE_SUBSCR_FAST:
  649. argStr += _S(" (", co->varnames[byte.arg].sv(), ")").sv();
  650. break;
  651. case OP_LOAD_FUNCTION:
  652. argStr += _S(" (", co->func_decls[byte.arg]->code->name, ")").sv();
  653. break;
  654. }
  655. return argStr;
  656. }
  657. Str VM::disassemble(CodeObject_ co){
  658. auto pad = [](const Str& s, const int n){
  659. if(s.length() >= n) return s.substr(0, n);
  660. return s + std::string(n - s.length(), ' ');
  661. };
  662. std::vector<int> jumpTargets;
  663. for(auto byte : co->codes){
  664. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE || byte.op == OP_SHORTCUT_IF_FALSE_OR_POP || byte.op == OP_LOOP_CONTINUE){
  665. jumpTargets.push_back(byte.arg);
  666. }
  667. if(byte.op == OP_GOTO){
  668. // TODO: pre-compute jump targets for OP_GOTO
  669. int* target = co->labels.try_get_2_likely_found(StrName(byte.arg));
  670. if(target != nullptr) jumpTargets.push_back(*target);
  671. }
  672. }
  673. SStream ss;
  674. int prev_line = -1;
  675. for(int i=0; i<co->codes.size(); i++){
  676. const Bytecode& byte = co->codes[i];
  677. Str line = std::to_string(co->lines[i].lineno);
  678. if(co->lines[i].lineno == prev_line) line = "";
  679. else{
  680. if(prev_line != -1) ss << "\n";
  681. prev_line = co->lines[i].lineno;
  682. }
  683. std::string pointer;
  684. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  685. pointer = "-> ";
  686. }else{
  687. pointer = " ";
  688. }
  689. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  690. std::string bc_name(OP_NAMES[byte.op]);
  691. if(co->lines[i].is_virtual) bc_name += '*';
  692. ss << " " << pad(bc_name, 25) << " ";
  693. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  694. std::string argStr = _opcode_argstr(this, byte, co.get());
  695. ss << argStr;
  696. // ss << pad(argStr, 40); // may overflow
  697. // ss << co->blocks[byte.block].type;
  698. if(i != co->codes.size() - 1) ss << '\n';
  699. }
  700. for(auto& decl: co->func_decls){
  701. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  702. ss << disassemble(decl->code);
  703. }
  704. ss << "\n";
  705. return Str(ss.str());
  706. }
  707. #if PK_DEBUG_CEVAL_STEP
  708. void VM::__log_s_data(const char* title) {
  709. if(_main == nullptr) return;
  710. if(callstack.empty()) return;
  711. SStream ss;
  712. if(title) ss << title << " | ";
  713. std::map<PyVar*, int> sp_bases;
  714. callstack.apply([&](Frame& f){
  715. if(f._sp_base == nullptr) PK_FATAL_ERROR();
  716. sp_bases[f._sp_base] += 1;
  717. });
  718. Frame* frame = &callstack.top();
  719. int line = frame->curr_lineno();
  720. ss << frame->co->name << ":" << line << " [";
  721. for(PyVar* p=s_data.begin(); p!=s_data.end(); p++){
  722. ss << std::string(sp_bases[p], '|');
  723. if(sp_bases[p] > 0) ss << " ";
  724. PyVar obj = *p;
  725. if(obj == nullptr) ss << "(nil)";
  726. else if(obj == PY_NULL) ss << "NULL";
  727. else if(is_int(obj)) ss << CAST(i64, obj);
  728. else if(is_float(obj)) ss << CAST(f64, obj);
  729. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  730. else if(obj == None) ss << "None";
  731. else if(obj == True) ss << "True";
  732. else if(obj == False) ss << "False";
  733. else if(is_type(obj, tp_function)){
  734. auto& f = CAST(Function&, obj);
  735. ss << f.decl->code->name << "(...)";
  736. } else if(is_type(obj, tp_type)){
  737. Type t = PK_OBJ_GET(Type, obj);
  738. ss << "<class " + _all_types[t].name.escape() + ">";
  739. } else if(is_type(obj, tp_list)){
  740. auto& t = CAST(List&, obj);
  741. ss << "list(size=" << t.size() << ")";
  742. } else if(is_type(obj, tp_tuple)){
  743. auto& t = CAST(Tuple&, obj);
  744. ss << "tuple(size=" << t.size() << ")";
  745. } else ss << "(" << _type_name(this, obj.type) << ")";
  746. ss << ", ";
  747. }
  748. std::string output = ss.str().str();
  749. if(!s_data.empty()) {
  750. output.pop_back(); output.pop_back();
  751. }
  752. output.push_back(']');
  753. Bytecode byte = frame->co->codes[frame->_ip];
  754. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  755. }
  756. #endif
  757. void VM::__init_builtin_types(){
  758. _all_types.emplace_back(nullptr, Type(), nullptr, "", false); // 0 is not used
  759. _all_types.emplace_back(heap._new<Type>(tp_type, tp_object), Type(), nullptr, "object", true);
  760. _all_types.emplace_back(heap._new<Type>(tp_type, tp_type), tp_object, nullptr, "type", false);
  761. auto validate = [](Type type, PyVar ret){
  762. Type ret_t = PK_OBJ_GET(Type, ret);
  763. if(ret_t != type) exit(-3);
  764. };
  765. validate(tp_int, new_type_object(nullptr, "int", tp_object, false));
  766. validate(tp_float, new_type_object(nullptr, "float", tp_object, false));
  767. validate(tp_bool, new_type_object(nullptr, "bool", tp_object, false));
  768. validate(tp_str, new_type_object<Str>(nullptr, "str", tp_object, false));
  769. validate(tp_list, new_type_object<List>(nullptr, "list", tp_object, false));
  770. validate(tp_tuple, new_type_object<Tuple>(nullptr, "tuple", tp_object, false));
  771. validate(tp_slice, new_type_object<Slice>(nullptr, "slice", tp_object, false));
  772. validate(tp_range, new_type_object<Range>(nullptr, "range", tp_object, false));
  773. validate(tp_module, new_type_object<DummyModule>(nullptr, "module", tp_object, false));
  774. validate(tp_function, new_type_object<Function>(nullptr, "function", tp_object, false));
  775. validate(tp_native_func, new_type_object<NativeFunc>(nullptr, "native_func", tp_object, false));
  776. validate(tp_bound_method, new_type_object<BoundMethod>(nullptr, "bound_method", tp_object, false));
  777. validate(tp_super, new_type_object<Super>(nullptr, "super", tp_object, false));
  778. validate(tp_exception, new_type_object<Exception>(nullptr, "Exception", tp_object, true));
  779. validate(tp_bytes, new_type_object<Bytes>(nullptr, "bytes", tp_object, false));
  780. validate(tp_mappingproxy, new_type_object<MappingProxy>(nullptr, "mappingproxy", tp_object, false));
  781. validate(tp_dict, new_type_object<Dict>(nullptr, "dict", tp_object, true));
  782. validate(tp_property, new_type_object<Property>(nullptr, "property", tp_object, false));
  783. validate(tp_star_wrapper, new_type_object<StarWrapper>(nullptr, "_star_wrapper", tp_object, false));
  784. validate(tp_staticmethod, new_type_object<StaticMethod>(nullptr, "staticmethod", tp_object, false));
  785. validate(tp_classmethod, new_type_object<ClassMethod>(nullptr, "classmethod", tp_object, false));
  786. validate(tp_none, new_type_object(nullptr, "NoneType", tp_object, false));
  787. validate(tp_not_implemented, new_type_object(nullptr, "NotImplementedType", tp_object, false));
  788. validate(tp_ellipsis, new_type_object(nullptr, "ellipsis", tp_object, false));
  789. // SyntaxError and IndentationError must be created here
  790. PyVar SyntaxError = new_type_object(nullptr, "SyntaxError", tp_exception, true);
  791. PyVar IndentationError = new_type_object(nullptr, "IndentationError", PK_OBJ_GET(Type, SyntaxError), true);
  792. this->StopIteration = new_type_object(nullptr, "StopIteration", tp_exception, true);
  793. this->builtins = new_module("builtins");
  794. // setup public types
  795. builtins->attr().set("type", _t(tp_type));
  796. builtins->attr().set("object", _t(tp_object));
  797. builtins->attr().set("bool", _t(tp_bool));
  798. builtins->attr().set("int", _t(tp_int));
  799. builtins->attr().set("float", _t(tp_float));
  800. builtins->attr().set("str", _t(tp_str));
  801. builtins->attr().set("list", _t(tp_list));
  802. builtins->attr().set("tuple", _t(tp_tuple));
  803. builtins->attr().set("range", _t(tp_range));
  804. builtins->attr().set("bytes", _t(tp_bytes));
  805. builtins->attr().set("dict", _t(tp_dict));
  806. builtins->attr().set("property", _t(tp_property));
  807. builtins->attr().set("StopIteration", StopIteration);
  808. builtins->attr().set("NotImplemented", NotImplemented);
  809. builtins->attr().set("slice", _t(tp_slice));
  810. builtins->attr().set("Exception", _t(tp_exception));
  811. builtins->attr().set("SyntaxError", SyntaxError);
  812. builtins->attr().set("IndentationError", IndentationError);
  813. __post_init_builtin_types();
  814. this->_main = new_module("__main__");
  815. }
  816. // `heap.gc_scope_lock();` needed before calling this function
  817. void VM::__unpack_as_list(ArgsView args, List& list){
  818. for(PyVar obj: args){
  819. if(is_type(obj, tp_star_wrapper)){
  820. const StarWrapper& w = _CAST(StarWrapper&, obj);
  821. // maybe this check should be done in the compile time
  822. if(w.level != 1) TypeError("expected level 1 star wrapper");
  823. PyVar _0 = py_iter(w.obj);
  824. const PyTypeInfo* info = _tp_info(_0);
  825. PyVar _1 = _py_next(info, _0);
  826. while(_1 != StopIteration){
  827. list.push_back(_1);
  828. _1 = _py_next(info, _0);
  829. }
  830. }else{
  831. list.push_back(obj);
  832. }
  833. }
  834. }
  835. // `heap.gc_scope_lock();` needed before calling this function
  836. void VM::__unpack_as_dict(ArgsView args, Dict& dict){
  837. for(PyVar obj: args){
  838. if(is_type(obj, tp_star_wrapper)){
  839. const StarWrapper& w = _CAST(StarWrapper&, obj);
  840. // maybe this check should be done in the compile time
  841. if(w.level != 2) TypeError("expected level 2 star wrapper");
  842. const Dict& other = CAST(Dict&, w.obj);
  843. dict.update(this, other);
  844. }else{
  845. const Tuple& t = CAST(Tuple&, obj);
  846. if(t.size() != 2) TypeError("expected tuple of length 2");
  847. dict.set(this, t[0], t[1]);
  848. }
  849. }
  850. }
  851. void VM::__prepare_py_call(PyVar* buffer, ArgsView args, ArgsView kwargs, const FuncDecl_& decl){
  852. const CodeObject* co = decl->code.get();
  853. int co_nlocals = co->varnames.size();
  854. int decl_argc = decl->args.size();
  855. if(args.size() < decl_argc){
  856. vm->TypeError(_S(
  857. co->name, "() takes ", decl_argc, " positional arguments but ", args.size(), " were given"
  858. ));
  859. }
  860. int i = 0;
  861. // prepare args
  862. for(int index: decl->args) buffer[index] = args[i++];
  863. // set extra varnames to PY_NULL
  864. for(int j=i; j<co_nlocals; j++) buffer[j] = PY_NULL;
  865. // prepare kwdefaults
  866. for(auto& kv: decl->kwargs) buffer[kv.index] = kv.value;
  867. // handle *args
  868. if(decl->starred_arg != -1){
  869. ArgsView vargs(args.begin() + i, args.end());
  870. buffer[decl->starred_arg] = VAR(vargs.to_tuple());
  871. i += vargs.size();
  872. }else{
  873. // kwdefaults override
  874. for(auto& kv: decl->kwargs){
  875. if(i >= args.size()) break;
  876. buffer[kv.index] = args[i++];
  877. }
  878. if(i < args.size()) TypeError(_S("too many arguments", " (", decl->code->name, ')'));
  879. }
  880. PyVar vkwargs;
  881. if(decl->starred_kwarg != -1){
  882. vkwargs = VAR(Dict());
  883. buffer[decl->starred_kwarg] = vkwargs;
  884. }else{
  885. vkwargs = nullptr;
  886. }
  887. for(int j=0; j<kwargs.size(); j+=2){
  888. StrName key(_CAST(uint16_t, kwargs[j]));
  889. int index = decl->kw_to_index.try_get_likely_found(key);
  890. // if key is an explicit key, set as local variable
  891. if(index >= 0){
  892. buffer[index] = kwargs[j+1];
  893. }else{
  894. // otherwise, set as **kwargs if possible
  895. if(vkwargs == nullptr){
  896. TypeError(_S(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  897. }else{
  898. Dict& dict = _CAST(Dict&, vkwargs);
  899. dict.set(this, VAR(key.sv()), kwargs[j+1]);
  900. }
  901. }
  902. }
  903. }
  904. PyVar VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  905. PyVar* p1 = s_data._sp - KWARGC*2;
  906. PyVar* p0 = p1 - ARGC - 2;
  907. // [callable, <self>, args..., kwargs...]
  908. // ^p0 ^p1 ^_sp
  909. PyVar callable = p1[-ARGC-2];
  910. Type callable_t = _tp(callable);
  911. // handle boundmethod, do a patch
  912. if(callable_t == tp_bound_method){
  913. PK_DEBUG_ASSERT(p0[1] == PY_NULL)
  914. BoundMethod& bm = PK_OBJ_GET(BoundMethod, callable);
  915. callable = bm.func; // get unbound method
  916. callable_t = _tp(callable);
  917. p1[-(ARGC + 2)] = bm.func;
  918. p1[-(ARGC + 1)] = bm.self;
  919. // [unbound, self, args..., kwargs...]
  920. }
  921. ArgsView args(p0[1]==PY_NULL ? (p0+2) : (p0+1), p1);
  922. ArgsView kwargs(p1, s_data._sp);
  923. PyVar* _base = args.begin();
  924. PyVar* buffer = __vectorcall_buffer;
  925. if(callable_t == tp_function){
  926. /*****************_py_call*****************/
  927. // check stack overflow
  928. if(s_data.is_overflow()) StackOverflowError();
  929. const Function& fn = PK_OBJ_GET(Function, callable);
  930. const CodeObject* co = fn.decl->code.get();
  931. int co_nlocals = co->varnames.size();
  932. switch(fn.decl->type){
  933. case FuncType::UNSET: PK_FATAL_ERROR(); break;
  934. case FuncType::NORMAL:
  935. __prepare_py_call(buffer, args, kwargs, fn.decl);
  936. // copy buffer back to stack
  937. s_data.reset(_base + co_nlocals);
  938. for(int j=0; j<co_nlocals; j++) _base[j] = buffer[j];
  939. break;
  940. case FuncType::SIMPLE:
  941. if(args.size() != fn.decl->args.size()) TypeError(_S(co->name, "() takes ", fn.decl->args.size(), " positional arguments but ", args.size(), " were given"));
  942. if(!kwargs.empty()) TypeError(_S(co->name, "() takes no keyword arguments"));
  943. // [callable, <self>, args..., local_vars...]
  944. // ^p0 ^p1 ^_sp
  945. s_data.reset(_base + co_nlocals);
  946. // initialize local variables to PY_NULL
  947. for(PyVar* p=p1; p!=s_data._sp; p++) *p = PY_NULL;
  948. break;
  949. case FuncType::EMPTY:
  950. if(args.size() != fn.decl->args.size()) TypeError(_S(co->name, "() takes ", fn.decl->args.size(), " positional arguments but ", args.size(), " were given"));
  951. if(!kwargs.empty()) TypeError(_S(co->name, "() takes no keyword arguments"));
  952. s_data.reset(p0);
  953. return None;
  954. case FuncType::GENERATOR:
  955. __prepare_py_call(buffer, args, kwargs, fn.decl);
  956. s_data.reset(p0);
  957. return __py_generator(
  958. Frame(nullptr, co, fn._module, callable, nullptr),
  959. ArgsView(buffer, buffer + co_nlocals)
  960. );
  961. };
  962. // simple or normal
  963. callstack.emplace(p0, co, fn._module, callable, args.begin());
  964. if(op_call) return PY_OP_CALL;
  965. return __run_top_frame();
  966. /*****************_py_call*****************/
  967. }
  968. if(callable_t == tp_native_func){
  969. const auto& f = PK_OBJ_GET(NativeFunc, callable);
  970. PyVar ret;
  971. if(f.decl != nullptr){
  972. int co_nlocals = f.decl->code->varnames.size();
  973. __prepare_py_call(buffer, args, kwargs, f.decl);
  974. // copy buffer back to stack
  975. s_data.reset(_base + co_nlocals);
  976. for(int j=0; j<co_nlocals; j++) _base[j] = buffer[j];
  977. ret = f.call(vm, ArgsView(s_data._sp - co_nlocals, s_data._sp));
  978. }else{
  979. if(KWARGC != 0) TypeError("old-style native_func does not accept keyword arguments");
  980. f.check_size(this, args);
  981. ret = f.call(this, args);
  982. }
  983. s_data.reset(p0);
  984. return ret;
  985. }
  986. if(callable_t == tp_type){
  987. // [type, NULL, args..., kwargs...]
  988. PyVar new_f = find_name_in_mro(PK_OBJ_GET(Type, callable), __new__);
  989. PyVar obj;
  990. PK_DEBUG_ASSERT(new_f != nullptr && p0[1]==PY_NULL);
  991. if(new_f == __cached_object_new) {
  992. // fast path for object.__new__
  993. obj = vm->new_object<DummyInstance>(PK_OBJ_GET(Type, callable));
  994. }else{
  995. PUSH(new_f);
  996. PUSH(PY_NULL);
  997. PUSH(callable); // cls
  998. for(PyVar o: args) PUSH(o);
  999. for(PyVar o: kwargs) PUSH(o);
  1000. // if obj is not an instance of `cls`, the behavior is undefined
  1001. obj = vectorcall(ARGC+1, KWARGC);
  1002. }
  1003. // __init__
  1004. PyVar self;
  1005. callable = get_unbound_method(obj, __init__, &self, false);
  1006. if (callable != nullptr) {
  1007. callable_t = _tp(callable);
  1008. // replace `NULL` with `self`
  1009. p1[-(ARGC + 2)] = callable;
  1010. p1[-(ARGC + 1)] = self;
  1011. // [init_f, self, args..., kwargs...]
  1012. vectorcall(ARGC, KWARGC);
  1013. // We just discard the return value of `__init__`
  1014. // in cpython it raises a TypeError if the return value is not None
  1015. }else{
  1016. // manually reset the stack
  1017. s_data.reset(p0);
  1018. }
  1019. return obj;
  1020. }
  1021. // handle `__call__` overload
  1022. PyVar self;
  1023. PyVar call_f = get_unbound_method(callable, __call__, &self, false);
  1024. if(self != PY_NULL){
  1025. p1[-(ARGC + 2)] = call_f;
  1026. p1[-(ARGC + 1)] = self;
  1027. // [call_f, self, args..., kwargs...]
  1028. return vectorcall(ARGC, KWARGC, op_call);
  1029. }
  1030. TypeError(_type_name(vm, callable_t).escape() + " object is not callable");
  1031. PK_UNREACHABLE()
  1032. }
  1033. void VM::delattr(PyVar _0, StrName _name){
  1034. const PyTypeInfo* ti = _tp_info(_0);
  1035. if(ti->m__delattr__ && ti->m__delattr__(this, _0, _name)) return;
  1036. if(is_tagged(_0) || !_0->is_attr_valid()) TypeError("cannot delete attribute");
  1037. if(!_0->attr().del(_name)) AttributeError(_0, _name);
  1038. }
  1039. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  1040. PyVar VM::getattr(PyVar obj, StrName name, bool throw_err){
  1041. Type objtype(0);
  1042. // handle super() proxy
  1043. if(is_type(obj, tp_super)){
  1044. const Super& super = PK_OBJ_GET(Super, obj);
  1045. obj = super.first;
  1046. objtype = super.second;
  1047. }else{
  1048. objtype = _tp(obj);
  1049. }
  1050. PyVar cls_var = find_name_in_mro(objtype, name);
  1051. if(cls_var != nullptr){
  1052. // handle descriptor
  1053. if(is_type(cls_var, tp_property)){
  1054. const Property& prop = PK_OBJ_GET(Property, cls_var);
  1055. return call(prop.getter, obj);
  1056. }
  1057. }
  1058. // handle instance __dict__
  1059. if(!is_tagged(obj) && obj->is_attr_valid()){
  1060. PyVar val;
  1061. if(obj.type == tp_type){
  1062. val = find_name_in_mro(PK_OBJ_GET(Type, obj), name);
  1063. if(val != nullptr){
  1064. if(is_tagged(val)) return val;
  1065. if(val.type == tp_staticmethod) return PK_OBJ_GET(StaticMethod, val).func;
  1066. if(val.type == tp_classmethod) return VAR(BoundMethod(obj, PK_OBJ_GET(ClassMethod, val).func));
  1067. return val;
  1068. }
  1069. }else{
  1070. val = obj->attr().try_get_likely_found(name);
  1071. if(val != nullptr) return val;
  1072. }
  1073. }
  1074. if(cls_var != nullptr){
  1075. // bound method is non-data descriptor
  1076. if(!is_tagged(cls_var)){
  1077. switch(cls_var.type.index){
  1078. case tp_function.index:
  1079. return VAR(BoundMethod(obj, cls_var));
  1080. case tp_native_func.index:
  1081. return VAR(BoundMethod(obj, cls_var));
  1082. case tp_staticmethod.index:
  1083. return PK_OBJ_GET(StaticMethod, cls_var).func;
  1084. case tp_classmethod.index:
  1085. return VAR(BoundMethod(_t(objtype), PK_OBJ_GET(ClassMethod, cls_var).func));
  1086. }
  1087. }
  1088. return cls_var;
  1089. }
  1090. const PyTypeInfo* ti = &_all_types[objtype];
  1091. if(ti->m__getattr__){
  1092. PyVar ret = ti->m__getattr__(this, obj, name);
  1093. if(ret) return ret;
  1094. }
  1095. if(throw_err) AttributeError(obj, name);
  1096. return nullptr;
  1097. }
  1098. // used by OP_LOAD_METHOD
  1099. // try to load a unbound method (fallback to `getattr` if not found)
  1100. PyVar VM::get_unbound_method(PyVar obj, StrName name, PyVar* self, bool throw_err, bool fallback){
  1101. *self = PY_NULL;
  1102. Type objtype(0);
  1103. // handle super() proxy
  1104. if(is_type(obj, tp_super)){
  1105. const Super& super = PK_OBJ_GET(Super, obj);
  1106. obj = super.first;
  1107. objtype = super.second;
  1108. }else{
  1109. objtype = _tp(obj);
  1110. }
  1111. PyVar cls_var = find_name_in_mro(objtype, name);
  1112. if(fallback){
  1113. if(cls_var != nullptr){
  1114. // handle descriptor
  1115. if(is_type(cls_var, tp_property)){
  1116. const Property& prop = PK_OBJ_GET(Property, cls_var);
  1117. return call(prop.getter, obj);
  1118. }
  1119. }
  1120. // handle instance __dict__
  1121. if(!is_tagged(obj) && obj->is_attr_valid()){
  1122. PyVar val;
  1123. if(obj.type == tp_type){
  1124. val = find_name_in_mro(PK_OBJ_GET(Type, obj), name);
  1125. if(val != nullptr){
  1126. if(is_tagged(val)) return val;
  1127. if(val.type == tp_staticmethod) return PK_OBJ_GET(StaticMethod, val).func;
  1128. if(val.type == tp_classmethod) return VAR(BoundMethod(obj, PK_OBJ_GET(ClassMethod, val).func));
  1129. return val;
  1130. }
  1131. }else{
  1132. val = obj->attr().try_get_likely_found(name);
  1133. if(val != nullptr) return val;
  1134. }
  1135. }
  1136. }
  1137. if(cls_var != nullptr){
  1138. if(!is_tagged(cls_var)){
  1139. switch(cls_var.type.index){
  1140. case tp_function.index:
  1141. *self = obj;
  1142. break;
  1143. case tp_native_func.index:
  1144. *self = obj;
  1145. break;
  1146. case tp_staticmethod.index:
  1147. *self = PY_NULL;
  1148. return PK_OBJ_GET(StaticMethod, cls_var).func;
  1149. case tp_classmethod.index:
  1150. *self = _t(objtype);
  1151. return PK_OBJ_GET(ClassMethod, cls_var).func;
  1152. }
  1153. }
  1154. return cls_var;
  1155. }
  1156. const PyTypeInfo* ti = &_all_types[objtype];
  1157. if(fallback && ti->m__getattr__){
  1158. PyVar ret = ti->m__getattr__(this, obj, name);
  1159. if(ret) return ret;
  1160. }
  1161. if(throw_err) AttributeError(obj, name);
  1162. return nullptr;
  1163. }
  1164. void VM::setattr(PyVar obj, StrName name, PyVar value){
  1165. Type objtype(0);
  1166. // handle super() proxy
  1167. if(is_type(obj, tp_super)){
  1168. Super& super = PK_OBJ_GET(Super, obj);
  1169. obj = super.first;
  1170. objtype = super.second;
  1171. }else{
  1172. objtype = _tp(obj);
  1173. }
  1174. PyVar cls_var = find_name_in_mro(objtype, name);
  1175. if(cls_var != nullptr){
  1176. // handle descriptor
  1177. if(is_type(cls_var, tp_property)){
  1178. const Property& prop = _CAST(Property&, cls_var);
  1179. if(prop.setter != vm->None){
  1180. call(prop.setter, obj, value);
  1181. }else{
  1182. TypeError(_S("readonly attribute: ", name.escape()));
  1183. }
  1184. return;
  1185. }
  1186. }
  1187. const PyTypeInfo* ti = &_all_types[objtype];
  1188. if(ti->m__setattr__){
  1189. ti->m__setattr__(this, obj, name, value);
  1190. return;
  1191. }
  1192. // handle instance __dict__
  1193. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  1194. obj->attr().set(name, value);
  1195. }
  1196. PyVar VM::bind_func(PyVar obj, StrName name, int argc, NativeFuncC fn, any userdata, BindType bt) {
  1197. PyVar nf = VAR(NativeFunc(fn, argc, std::move(userdata)));
  1198. switch(bt){
  1199. case BindType::DEFAULT: break;
  1200. case BindType::STATICMETHOD: nf = VAR(StaticMethod(nf)); break;
  1201. case BindType::CLASSMETHOD: nf = VAR(ClassMethod(nf)); break;
  1202. }
  1203. if(obj != nullptr) obj->attr().set(name, nf);
  1204. return nf;
  1205. }
  1206. PyVar VM::bind(PyVar obj, const char* sig, NativeFuncC fn, any userdata, BindType bt){
  1207. return bind(obj, sig, nullptr, fn, std::move(userdata), bt);
  1208. }
  1209. PyVar VM::bind(PyVar obj, const char* sig, const char* docstring, NativeFuncC fn, any userdata, BindType bt){
  1210. CodeObject_ co;
  1211. try{
  1212. // fn(a, b, *c, d=1) -> None
  1213. co = compile(_S("def ", sig, " : pass"), "<bind>", EXEC_MODE);
  1214. }catch(const Exception&){
  1215. throw std::runtime_error("invalid signature: " + std::string(sig));
  1216. }
  1217. if(co->func_decls.size() != 1){
  1218. throw std::runtime_error("expected 1 function declaration");
  1219. }
  1220. FuncDecl_ decl = co->func_decls[0];
  1221. decl->docstring = docstring;
  1222. PyVar f_obj = VAR(NativeFunc(fn, decl, std::move(userdata)));
  1223. switch(bt){
  1224. case BindType::STATICMETHOD:
  1225. f_obj = VAR(StaticMethod(f_obj));
  1226. break;
  1227. case BindType::CLASSMETHOD:
  1228. f_obj = VAR(ClassMethod(f_obj));
  1229. break;
  1230. case BindType::DEFAULT:
  1231. break;
  1232. }
  1233. if(obj != nullptr) obj->attr().set(decl->code->name, f_obj);
  1234. return f_obj;
  1235. }
  1236. PyVar VM::bind_property(PyVar obj, const char* name, NativeFuncC fget, NativeFuncC fset){
  1237. PK_ASSERT(is_type(obj, tp_type));
  1238. std::string_view name_sv(name); int pos = name_sv.find(':');
  1239. if(pos > 0) name_sv = name_sv.substr(0, pos);
  1240. PyVar _0 = new_object<NativeFunc>(tp_native_func, fget, 1);
  1241. PyVar _1 = vm->None;
  1242. if(fset != nullptr) _1 = new_object<NativeFunc>(tp_native_func, fset, 2);
  1243. PyVar prop = VAR(Property(_0, _1));
  1244. obj->attr().set(StrName(name_sv), prop);
  1245. return prop;
  1246. }
  1247. void VM::__builtin_error(StrName type){ _error(call(builtins->attr(type))); }
  1248. void VM::__builtin_error(StrName type, PyVar arg){ _error(call(builtins->attr(type), arg)); }
  1249. void VM::__builtin_error(StrName type, const Str& msg){ __builtin_error(type, VAR(msg)); }
  1250. void VM::BinaryOptError(const char* op, PyVar _0, PyVar _1) {
  1251. StrName name_0 = _type_name(vm, _tp(_0));
  1252. StrName name_1 = _type_name(vm, _tp(_1));
  1253. TypeError(_S("unsupported operand type(s) for ", op, ": ", name_0.escape(), " and ", name_1.escape()));
  1254. }
  1255. void VM::AttributeError(PyVar obj, StrName name){
  1256. if(isinstance(obj, vm->tp_type)){
  1257. __builtin_error("AttributeError", _S("type object ", _type_name(vm, PK_OBJ_GET(Type, obj)).escape(), " has no attribute ", name.escape()));
  1258. }else{
  1259. __builtin_error("AttributeError", _S(_type_name(vm, _tp(obj)).escape(), " object has no attribute ", name.escape()));
  1260. }
  1261. }
  1262. void VM::_error(PyVar e_obj){
  1263. PK_ASSERT(isinstance(e_obj, tp_exception))
  1264. Exception& e = PK_OBJ_GET(Exception, e_obj);
  1265. if(callstack.empty()){
  1266. e.is_re = false;
  1267. throw e;
  1268. }
  1269. PUSH(e_obj);
  1270. __raise_exc();
  1271. }
  1272. void VM::__raise_exc(bool re_raise){
  1273. Frame* frame = &callstack.top();
  1274. Exception& e = PK_OBJ_GET(Exception, s_data.top());
  1275. if(!re_raise){
  1276. e._ip_on_error = frame->ip();
  1277. e._code_on_error = (void*)frame->co;
  1278. }
  1279. int next_ip = frame->prepare_jump_exception_handler(&s_data);
  1280. int actual_ip = frame->ip();
  1281. if(e._ip_on_error >= 0 && e._code_on_error == (void*)frame->co) actual_ip = e._ip_on_error;
  1282. int current_line = frame->co->lines[actual_ip].lineno; // current line
  1283. auto current_f_name = frame->co->name.sv(); // current function name
  1284. if(frame->_callable == nullptr) current_f_name = ""; // not in a function
  1285. e.st_push(frame->co->src, current_line, nullptr, current_f_name);
  1286. if(next_ip >= 0){
  1287. throw InternalException(InternalExceptionType::Handled, next_ip);
  1288. }else{
  1289. throw InternalException(InternalExceptionType::Unhandled);
  1290. }
  1291. }
  1292. StrName _type_name(VM *vm, Type type){
  1293. return vm->_all_types[type].name;
  1294. }
  1295. void VM::bind__getitem__(Type type, PyVar (*f)(VM*, PyVar, PyVar)){
  1296. _all_types[type].m__getitem__ = f;
  1297. bind_func(type, __getitem__, 2, [](VM* vm, ArgsView args){
  1298. return lambda_get_userdata<PyVar(*)(VM*, PyVar, PyVar)>(args.begin())(vm, args[0], args[1]);
  1299. }, f);
  1300. }
  1301. void VM::bind__setitem__(Type type, void (*f)(VM*, PyVar, PyVar, PyVar)){
  1302. _all_types[type].m__setitem__ = f;
  1303. bind_func(type, __setitem__, 3, [](VM* vm, ArgsView args){
  1304. lambda_get_userdata<void(*)(VM* vm, PyVar, PyVar, PyVar)>(args.begin())(vm, args[0], args[1], args[2]);
  1305. return vm->None;
  1306. }, f);
  1307. }
  1308. void VM::bind__delitem__(Type type, void (*f)(VM*, PyVar, PyVar)){
  1309. _all_types[type].m__delitem__ = f;
  1310. bind_func(type, __delitem__, 2, [](VM* vm, ArgsView args){
  1311. lambda_get_userdata<void(*)(VM*, PyVar, PyVar)>(args.begin())(vm, args[0], args[1]);
  1312. return vm->None;
  1313. }, f);
  1314. }
  1315. PyVar VM::__pack_next_retval(unsigned n){
  1316. if(n == 0) return StopIteration;
  1317. if(n == 1) return s_data.popx();
  1318. PyVar retval = VAR(s_data.view(n).to_tuple());
  1319. s_data._sp -= n;
  1320. return retval;
  1321. }
  1322. void VM::bind__next__(Type type, unsigned (*f)(VM*, PyVar)){
  1323. _all_types[type].m__next__ = f;
  1324. bind_func(type, __next__, 1, [](VM* vm, ArgsView args){
  1325. int n = lambda_get_userdata<unsigned(*)(VM*, PyVar)>(args.begin())(vm, args[0]);
  1326. return vm->__pack_next_retval(n);
  1327. }, f);
  1328. }
  1329. void VM::bind__next__(Type type, PyVar (*f)(VM*, PyVar)){
  1330. bind_func(type, __next__, 1, [](VM* vm, ArgsView args){
  1331. auto f = lambda_get_userdata<PyVar(*)(VM*, PyVar)>(args.begin());
  1332. return f(vm, args[0]);
  1333. }, f);
  1334. }
  1335. #define BIND_UNARY_SPECIAL(name) \
  1336. void VM::bind##name(Type type, PyVar (*f)(VM*, PyVar)){ \
  1337. _all_types[type].m##name = f; \
  1338. bind_func(type, name, 1, [](VM* vm, ArgsView args){ \
  1339. return lambda_get_userdata<PyVar(*)(VM*, PyVar)>(args.begin())(vm, args[0]);\
  1340. }, f); \
  1341. }
  1342. BIND_UNARY_SPECIAL(__iter__)
  1343. BIND_UNARY_SPECIAL(__neg__)
  1344. BIND_UNARY_SPECIAL(__invert__)
  1345. #undef BIND_UNARY_SPECIAL
  1346. void VM::bind__str__(Type type, Str (*f)(VM*, PyVar)){
  1347. _all_types[type].m__str__ = f;
  1348. bind_func(type, __str__, 1, [](VM* vm, ArgsView args){
  1349. Str s = lambda_get_userdata<decltype(f)>(args.begin())(vm, args[0]);
  1350. return VAR(s);
  1351. }, f);
  1352. }
  1353. void VM::bind__repr__(Type type, Str (*f)(VM*, PyVar)){
  1354. _all_types[type].m__repr__ = f;
  1355. bind_func(type, __repr__, 1, [](VM* vm, ArgsView args){
  1356. Str s = lambda_get_userdata<decltype(f)>(args.begin())(vm, args[0]);
  1357. return VAR(s);
  1358. }, f);
  1359. }
  1360. void VM::bind__hash__(Type type, i64 (*f)(VM*, PyVar)){
  1361. _all_types[type].m__hash__ = f;
  1362. bind_func(type, __hash__, 1, [](VM* vm, ArgsView args){
  1363. i64 ret = lambda_get_userdata<decltype(f)>(args.begin())(vm, args[0]);
  1364. return VAR(ret);
  1365. }, f);
  1366. }
  1367. void VM::bind__len__(Type type, i64 (*f)(VM*, PyVar)){
  1368. _all_types[type].m__len__ = f;
  1369. bind_func(type, __len__, 1, [](VM* vm, ArgsView args){
  1370. i64 ret = lambda_get_userdata<decltype(f)>(args.begin())(vm, args[0]);
  1371. return VAR(ret);
  1372. }, f);
  1373. }
  1374. #define BIND_BINARY_SPECIAL(name) \
  1375. void VM::bind##name(Type type, BinaryFuncC f){ \
  1376. _all_types[type].m##name = f; \
  1377. bind_func(type, name, 2, [](VM* vm, ArgsView args){ \
  1378. return lambda_get_userdata<BinaryFuncC>(args.begin())(vm, args[0], args[1]);\
  1379. }, f); \
  1380. }
  1381. BIND_BINARY_SPECIAL(__eq__)
  1382. BIND_BINARY_SPECIAL(__lt__)
  1383. BIND_BINARY_SPECIAL(__le__)
  1384. BIND_BINARY_SPECIAL(__gt__)
  1385. BIND_BINARY_SPECIAL(__ge__)
  1386. BIND_BINARY_SPECIAL(__contains__)
  1387. BIND_BINARY_SPECIAL(__add__)
  1388. BIND_BINARY_SPECIAL(__sub__)
  1389. BIND_BINARY_SPECIAL(__mul__)
  1390. BIND_BINARY_SPECIAL(__truediv__)
  1391. BIND_BINARY_SPECIAL(__floordiv__)
  1392. BIND_BINARY_SPECIAL(__mod__)
  1393. BIND_BINARY_SPECIAL(__pow__)
  1394. BIND_BINARY_SPECIAL(__matmul__)
  1395. BIND_BINARY_SPECIAL(__lshift__)
  1396. BIND_BINARY_SPECIAL(__rshift__)
  1397. BIND_BINARY_SPECIAL(__and__)
  1398. BIND_BINARY_SPECIAL(__or__)
  1399. BIND_BINARY_SPECIAL(__xor__)
  1400. #undef BIND_BINARY_SPECIAL
  1401. void Dict::_probe_0(VM* vm, PyVar key, bool &ok, int &i) const{
  1402. ok = false;
  1403. i64 hash = vm->py_hash(key);
  1404. i = hash & _mask;
  1405. for(int j=0; j<_capacity; j++) {
  1406. if(_items[i].first != nullptr){
  1407. if(vm->py_eq(_items[i].first, key)) { ok = true; break; }
  1408. }else{
  1409. if(_items[i].second == nullptr) break;
  1410. }
  1411. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1412. i = ((5*i) + 1) & _mask;
  1413. }
  1414. }
  1415. void Dict::_probe_1(VM* vm, PyVar key, bool &ok, int &i) const{
  1416. ok = false;
  1417. i = vm->py_hash(key) & _mask;
  1418. while(_items[i].first != nullptr) {
  1419. if(vm->py_eq(_items[i].first, key)) { ok = true; break; }
  1420. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1421. i = ((5*i) + 1) & _mask;
  1422. }
  1423. }
  1424. void NativeFunc::check_size(VM* vm, ArgsView args) const{
  1425. if(args.size() != argc && argc != -1) {
  1426. vm->TypeError(_S("expected ", argc, " arguments, got ", args.size()));
  1427. }
  1428. }
  1429. #if PK_ENABLE_PROFILER
  1430. void NextBreakpoint::_step(VM* vm){
  1431. int curr_callstack_size = vm->callstack.size();
  1432. int curr_lineno = vm->callstack.top().curr_lineno();
  1433. if(should_step_into){
  1434. if(curr_callstack_size != callstack_size || curr_lineno != lineno){
  1435. vm->__breakpoint();
  1436. }
  1437. }else{
  1438. if(curr_callstack_size == callstack_size) {
  1439. if(curr_lineno != lineno) vm->__breakpoint();
  1440. }else if(curr_callstack_size < callstack_size){
  1441. // returning
  1442. vm->__breakpoint();
  1443. }
  1444. }
  1445. }
  1446. #endif
  1447. void VM::__pop_frame(){
  1448. s_data.reset(callstack.top()._sp_base);
  1449. callstack.pop();
  1450. #if PK_ENABLE_PROFILER
  1451. if(!_next_breakpoint.empty() && callstack.size()<_next_breakpoint.callstack_size){
  1452. _next_breakpoint = NextBreakpoint();
  1453. }
  1454. #endif
  1455. }
  1456. void VM::__breakpoint(){
  1457. #if PK_ENABLE_PROFILER
  1458. _next_breakpoint = NextBreakpoint();
  1459. bool show_where = false;
  1460. bool show_headers = true;
  1461. while(true){
  1462. std::vector<LinkedFrame*> frames;
  1463. LinkedFrame* lf = callstack._tail;
  1464. while(lf != nullptr){
  1465. frames.push_back(lf);
  1466. lf = lf->f_back;
  1467. if(frames.size() >= 4) break;
  1468. }
  1469. if(show_headers){
  1470. for(int i=frames.size()-1; i>=0; i--){
  1471. if(!show_where && i!=0) continue;
  1472. SStream ss;
  1473. Frame* frame = &frames[i]->frame;
  1474. int lineno = frame->curr_lineno();
  1475. ss << "File \"" << frame->co->src->filename << "\", line " << lineno;
  1476. if(frame->_callable){
  1477. ss << ", in ";
  1478. ss << PK_OBJ_GET(Function, frame->_callable).decl->code->name;
  1479. }
  1480. ss << '\n';
  1481. ss << "-> " << frame->co->src->get_line(lineno) << '\n';
  1482. stdout_write(ss.str());
  1483. }
  1484. show_headers = false;
  1485. }
  1486. vm->stdout_write("(Pdb) ");
  1487. Frame* frame_0 = &frames[0]->frame;
  1488. std::string line;
  1489. if(!std::getline(std::cin, line)){
  1490. stdout_write("--KeyboardInterrupt--\n");
  1491. continue;
  1492. }
  1493. if(line == "h" || line == "help"){
  1494. stdout_write("h, help: show this help message\n");
  1495. stdout_write("q, quit: exit the debugger\n");
  1496. stdout_write("n, next: execute next line\n");
  1497. stdout_write("s, step: step into\n");
  1498. stdout_write("w, where: show current stack frame\n");
  1499. stdout_write("c, continue: continue execution\n");
  1500. stdout_write("a, args: show local variables\n");
  1501. stdout_write("p, print <expr>: evaluate expression\n");
  1502. stdout_write("l, list: show lines around current line\n");
  1503. stderr_write("ll, longlist: show all lines\n");
  1504. stdout_write("!: execute statement\n");
  1505. continue;
  1506. }
  1507. if(line == "q" || line == "quit") {
  1508. vm->RuntimeError("pdb quit");
  1509. PK_UNREACHABLE()
  1510. }
  1511. if(line == "n" || line == "next"){
  1512. vm->_next_breakpoint = NextBreakpoint(vm->callstack.size(), frame_0->curr_lineno(), false);
  1513. break;
  1514. }
  1515. if(line == "s" || line == "step"){
  1516. vm->_next_breakpoint = NextBreakpoint(vm->callstack.size(), frame_0->curr_lineno(), true);
  1517. break;
  1518. }
  1519. if(line == "w" || line == "where"){
  1520. show_where = !show_where;
  1521. show_headers = true;
  1522. continue;
  1523. }
  1524. if(line == "c" || line == "continue") break;
  1525. if(line == "a" || line == "args"){
  1526. int i = 0;
  1527. for(PyVar obj: frame_0->_locals){
  1528. if(obj == PY_NULL) continue;
  1529. StrName name = frame_0->co->varnames[i++];
  1530. stdout_write(_S(name.sv(), " = ", vm->py_repr(obj), '\n'));
  1531. }
  1532. continue;
  1533. }
  1534. bool is_list = line == "l" || line == "list";
  1535. bool is_longlist = line == "ll" || line == "longlist";
  1536. if(is_list || is_longlist){
  1537. if(frame_0->co->src->is_precompiled) continue;
  1538. int lineno = frame_0->curr_lineno();
  1539. int start, end;
  1540. if(is_list){
  1541. int max_line = frame_0->co->src->line_starts.size() + 1;
  1542. start = std::max(1, lineno-5);
  1543. end = std::min(max_line, lineno+5);
  1544. }else{
  1545. start = frame_0->co->start_line;
  1546. end = frame_0->co->end_line;
  1547. if(start == -1 || end == -1) continue;
  1548. }
  1549. SStream ss;
  1550. int max_width = std::to_string(end).size();
  1551. for(int i=start; i<=end; i++){
  1552. int spaces = max_width - std::to_string(i).size();
  1553. ss << std::string(spaces, ' ') << std::to_string(i);
  1554. if(i == lineno) ss << " -> ";
  1555. else ss << " ";
  1556. ss << frame_0->co->src->get_line(i) << '\n';
  1557. }
  1558. stdout_write(ss.str());
  1559. continue;
  1560. }
  1561. int space = line.find_first_of(' ');
  1562. if(space != -1){
  1563. std::string cmd = line.substr(0, space);
  1564. std::string arg = line.substr(space+1);
  1565. if(arg.empty()) continue; // ignore empty command
  1566. if(cmd == "p" || cmd == "print"){
  1567. CodeObject_ code = compile(arg, "<stdin>", EVAL_MODE, true);
  1568. PyVar retval = vm->_exec(code.get(), frame_0->_module, frame_0->_callable, frame_0->_locals);
  1569. stdout_write(vm->py_repr(retval));
  1570. stdout_write("\n");
  1571. }else if(cmd == "!"){
  1572. CodeObject_ code = compile(arg, "<stdin>", EXEC_MODE, true);
  1573. vm->_exec(code.get(), frame_0->_module, frame_0->_callable, frame_0->_locals);
  1574. }
  1575. continue;
  1576. }
  1577. }
  1578. #endif
  1579. }
  1580. /**************************************************************************/
  1581. void Function::_gc_mark(VM* vm) const{
  1582. decl->_gc_mark(vm);
  1583. if(_closure){
  1584. _closure->apply([=](StrName _, PyVar obj){
  1585. PK_OBJ_MARK(obj);
  1586. });
  1587. }
  1588. }
  1589. void NativeFunc::_gc_mark(VM* vm) const{
  1590. if(decl) decl->_gc_mark(vm);
  1591. }
  1592. void FuncDecl::_gc_mark(VM* vm) const{
  1593. code->_gc_mark(vm);
  1594. for(int i=0; i<kwargs.size(); i++) PK_OBJ_MARK(kwargs[i].value);
  1595. }
  1596. void List::_gc_mark(VM* vm) const{
  1597. for(PyVar obj: *this) PK_OBJ_MARK(obj);
  1598. }
  1599. void Tuple::_gc_mark(VM* vm) const{
  1600. for(PyVar obj: *this) PK_OBJ_MARK(obj);
  1601. }
  1602. void MappingProxy::_gc_mark(VM* vm) const{
  1603. PK_OBJ_MARK(obj);
  1604. }
  1605. void BoundMethod::_gc_mark(VM* vm) const{
  1606. PK_OBJ_MARK(func);
  1607. PK_OBJ_MARK(self);
  1608. }
  1609. void StarWrapper::_gc_mark(VM* vm) const{
  1610. PK_OBJ_MARK(obj);
  1611. }
  1612. void StaticMethod::_gc_mark(VM* vm) const{
  1613. PK_OBJ_MARK(func);
  1614. }
  1615. void ClassMethod::_gc_mark(VM* vm) const{
  1616. PK_OBJ_MARK(func);
  1617. }
  1618. void Property::_gc_mark(VM* vm) const{
  1619. PK_OBJ_MARK(getter);
  1620. PK_OBJ_MARK(setter);
  1621. }
  1622. void Slice::_gc_mark(VM* vm) const{
  1623. PK_OBJ_MARK(start);
  1624. PK_OBJ_MARK(stop);
  1625. PK_OBJ_MARK(step);
  1626. }
  1627. void Super::_gc_mark(VM* vm) const{
  1628. PK_OBJ_MARK(first);
  1629. }
  1630. void Frame::_gc_mark(VM* vm) const {
  1631. PK_OBJ_MARK(_module);
  1632. co->_gc_mark(vm);
  1633. // Frame could be stored in a generator, so mark _callable for safety
  1634. if(_callable != nullptr) PK_OBJ_MARK(_callable);
  1635. }
  1636. void ManagedHeap::mark() {
  1637. for(PyObject* obj: _no_gc){
  1638. if(!obj->gc_marked) vm->__obj_gc_mark(obj);
  1639. }
  1640. vm->callstack.apply([this](Frame& frame){ frame._gc_mark(vm); });
  1641. for(PyVar obj: vm->s_data) PK_OBJ_MARK(obj);
  1642. for(auto [_, co]: vm->__cached_codes) co->_gc_mark(vm);
  1643. if(vm->__last_exception) PK_OBJ_MARK(vm->__last_exception);
  1644. if(vm->__curr_class) PK_OBJ_MARK(vm->__curr_class);
  1645. if(vm->__c.error != nullptr) PK_OBJ_MARK(vm->__c.error);
  1646. if(_gc_marker_ex) _gc_marker_ex(vm);
  1647. }
  1648. void ManagedHeap::_delete(PyObject* obj){
  1649. const PyTypeInfo* ti = vm->_tp_info(obj->type);
  1650. if(ti->vt._dtor) ti->vt._dtor(obj->_value_ptr());
  1651. if(obj->_attr){
  1652. obj->_attr->~NameDict();
  1653. pool128_dealloc(obj->_attr);
  1654. }
  1655. pool128_dealloc(obj);
  1656. }
  1657. void Dict::_gc_mark(VM* vm) const{
  1658. apply([vm](PyVar k, PyVar v){
  1659. PK_OBJ_MARK(k);
  1660. PK_OBJ_MARK(v);
  1661. });
  1662. }
  1663. void CodeObject::_gc_mark(VM* vm) const {
  1664. for(PyVar v : consts) PK_OBJ_MARK(v);
  1665. for(auto& decl: func_decls) decl->_gc_mark(vm);
  1666. }
  1667. } // namespace pkpy