vm.cpp 56 KB

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