vm.cpp 61 KB

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