vm.cpp 62 KB

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