vm.cpp 59 KB

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