vm.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. #include "pocketpy/vm.h"
  2. namespace pkpy{
  3. struct JsonSerializer{
  4. VM* vm;
  5. PyObject* root;
  6. SStream ss;
  7. JsonSerializer(VM* vm, PyObject* root) : vm(vm), root(root) {}
  8. template<typename T>
  9. void write_array(T& arr){
  10. ss << '[';
  11. for(int i=0; i<arr.size(); i++){
  12. if(i != 0) ss << ", ";
  13. write_object(arr[i]);
  14. }
  15. ss << ']';
  16. }
  17. void write_dict(Dict& dict){
  18. ss << '{';
  19. bool first = true;
  20. dict.apply([&](PyObject* k, PyObject* v){
  21. if(!first) ss << ", ";
  22. first = false;
  23. if(!is_non_tagged_type(k, vm->tp_str)){
  24. vm->TypeError(_S("json keys must be string, got ", _type_name(vm, vm->_tp(k))));
  25. }
  26. ss << _CAST(Str&, k).escape(false) << ": ";
  27. write_object(v);
  28. });
  29. ss << '}';
  30. }
  31. void write_object(PyObject* obj){
  32. Type obj_t = vm->_tp(obj);
  33. if(obj == vm->None){
  34. ss << "null";
  35. }else if(obj_t == vm->tp_int){
  36. ss << _CAST(i64, obj);
  37. }else if(obj_t == vm->tp_float){
  38. f64 val = _CAST(f64, obj);
  39. if(std::isinf(val) || std::isnan(val)) vm->ValueError("cannot jsonify 'nan' or 'inf'");
  40. ss << val;
  41. }else if(obj_t == vm->tp_bool){
  42. ss << (obj == vm->True ? "true" : "false");
  43. }else if(obj_t == vm->tp_str){
  44. _CAST(Str&, obj).escape_(ss, false);
  45. }else if(obj_t == vm->tp_list){
  46. write_array<List>(_CAST(List&, obj));
  47. }else if(obj_t == vm->tp_tuple){
  48. write_array<Tuple>(_CAST(Tuple&, obj));
  49. }else if(obj_t == vm->tp_dict){
  50. write_dict(_CAST(Dict&, obj));
  51. }else{
  52. vm->TypeError(_S("unrecognized type ", _type_name(vm, obj_t).escape()));
  53. }
  54. }
  55. Str serialize(){
  56. auto _lock = vm->heap.gc_scope_lock();
  57. write_object(root);
  58. return ss.str();
  59. }
  60. };
  61. VM::VM(bool enable_os) : heap(this), enable_os(enable_os) {
  62. this->vm = this;
  63. this->_c.error = nullptr;
  64. _stdout = [](const char* buf, int size) {
  65. std::cout.write(buf, size);
  66. };
  67. _stderr = [](const char* buf, int size) {
  68. std::cerr.write(buf, size);
  69. };
  70. callstack.reserve(8);
  71. _main = nullptr;
  72. _last_exception = nullptr;
  73. _import_handler = [](const char* name_p, int name_size, int* out_size) -> unsigned char*{
  74. PK_UNUSED(name_p);
  75. PK_UNUSED(name_size);
  76. PK_UNUSED(out_size);
  77. return nullptr;
  78. };
  79. init_builtin_types();
  80. }
  81. PyObject* VM::py_str(PyObject* obj){
  82. const PyTypeInfo* ti = _inst_type_info(obj);
  83. if(ti->m__str__) return ti->m__str__(this, obj);
  84. PyObject* self;
  85. PyObject* f = get_unbound_method(obj, __str__, &self, false);
  86. if(self != PY_NULL) return call_method(self, f);
  87. return py_repr(obj);
  88. }
  89. PyObject* VM::py_repr(PyObject* obj){
  90. const PyTypeInfo* ti = _inst_type_info(obj);
  91. if(ti->m__repr__) return ti->m__repr__(this, obj);
  92. return call_method(obj, __repr__);
  93. }
  94. PyObject* VM::py_json(PyObject* obj){
  95. auto j = JsonSerializer(this, obj);
  96. return VAR(j.serialize());
  97. }
  98. PyObject* VM::py_iter(PyObject* obj){
  99. const PyTypeInfo* ti = _inst_type_info(obj);
  100. if(ti->m__iter__) return ti->m__iter__(this, obj);
  101. PyObject* self;
  102. PyObject* iter_f = get_unbound_method(obj, __iter__, &self, false);
  103. if(self != PY_NULL) return call_method(self, iter_f);
  104. TypeError(_type_name(vm, _tp(obj)).escape() + " object is not iterable");
  105. return nullptr;
  106. }
  107. std::pair<PyObject**, int> VM::_cast_array(PyObject* obj){
  108. if(is_non_tagged_type(obj, VM::tp_list)){
  109. List& list = PK_OBJ_GET(List, obj);
  110. return {list.data(), list.size()};
  111. }else if(is_non_tagged_type(obj, VM::tp_tuple)){
  112. Tuple& tuple = PK_OBJ_GET(Tuple, obj);
  113. return {tuple.data(), tuple.size()};
  114. }
  115. TypeError(_S("expected list or tuple, got ", _type_name(this, _tp(obj)).escape()));
  116. PK_UNREACHABLE();
  117. }
  118. FrameId VM::top_frame(){
  119. #if PK_DEBUG_EXTRA_CHECK
  120. if(callstack.empty()) PK_FATAL_ERROR();
  121. #endif
  122. return FrameId(&callstack.data(), callstack.size()-1);
  123. }
  124. void VM::_pop_frame(){
  125. Frame* frame = &callstack.top();
  126. s_data.reset(frame->_sp_base);
  127. callstack.pop();
  128. }
  129. PyObject* VM::find_name_in_mro(Type cls, StrName name){
  130. PyObject* val;
  131. do{
  132. val = _t(cls)->attr().try_get(name);
  133. if(val != nullptr) return val;
  134. cls = _all_types[cls].base;
  135. if(cls.index == -1) break;
  136. }while(true);
  137. return nullptr;
  138. }
  139. bool VM::isinstance(PyObject* obj, Type base){
  140. return issubclass(_tp(obj), base);
  141. }
  142. bool VM::issubclass(Type cls, Type base){
  143. do{
  144. if(cls == base) return true;
  145. Type next = _all_types[cls].base;
  146. if(next.index == -1) break;
  147. cls = next;
  148. }while(true);
  149. return false;
  150. }
  151. PyObject* VM::exec(std::string_view source, Str filename, CompileMode mode, PyObject* _module){
  152. if(_module == nullptr) _module = _main;
  153. try {
  154. CodeObject_ code = compile(source, filename, mode);
  155. #if PK_DEBUG_DIS_EXEC
  156. if(_module == _main) std::cout << disassemble(code) << '\n';
  157. #endif
  158. return _exec(code, _module);
  159. }catch (const Exception& e){
  160. stderr_write(e.summary() + "\n");
  161. }
  162. #if !PK_DEBUG_FULL_EXCEPTION
  163. catch(const std::exception& e) {
  164. Str msg = "An std::exception occurred! It could be a bug.\n";
  165. msg = msg + e.what() + "\n";
  166. stderr_write(msg);
  167. }
  168. catch(NeedMoreLines){
  169. throw;
  170. }
  171. catch(...) {
  172. Str msg = "An unknown exception occurred! It could be a bug. Please report it to @blueloveTH on GitHub.\n";
  173. stderr_write(msg);
  174. }
  175. #endif
  176. callstack.clear();
  177. s_data.clear();
  178. return nullptr;
  179. }
  180. PyObject* VM::exec(std::string_view source){
  181. return exec(source, "main.py", EXEC_MODE);
  182. }
  183. PyObject* VM::eval(std::string_view source){
  184. return exec(source, "<eval>", EVAL_MODE);
  185. }
  186. PyObject* VM::new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled){
  187. PyObject* obj = heap._new<Type>(tp_type, _all_types.size());
  188. const PyTypeInfo& base_info = _all_types[base];
  189. if(!base_info.subclass_enabled){
  190. TypeError(_S("type ", base_info.name.escape(), " is not `subclass_enabled`"));
  191. }
  192. PyTypeInfo info{
  193. obj,
  194. base,
  195. mod,
  196. name,
  197. subclass_enabled,
  198. };
  199. _all_types.push_back(info);
  200. return obj;
  201. }
  202. Type VM::_new_type_object(StrName name, Type base, bool subclass_enabled) {
  203. PyObject* obj = new_type_object(nullptr, name, base, subclass_enabled);
  204. return PK_OBJ_GET(Type, obj);
  205. }
  206. const PyTypeInfo* VM::_inst_type_info(PyObject* obj){
  207. if(is_int(obj)) return &_all_types[tp_int];
  208. if(is_float(obj)) return &_all_types[tp_float];
  209. return &_all_types[obj->type];
  210. }
  211. bool VM::py_eq(PyObject* lhs, PyObject* rhs){
  212. if(lhs == rhs) return true;
  213. const PyTypeInfo* ti = _inst_type_info(lhs);
  214. PyObject* res;
  215. if(ti->m__eq__){
  216. res = ti->m__eq__(this, lhs, rhs);
  217. if(res != vm->NotImplemented) return res == vm->True;
  218. }
  219. res = call_method(lhs, __eq__, rhs);
  220. if(res != vm->NotImplemented) return res == vm->True;
  221. ti = _inst_type_info(rhs);
  222. if(ti->m__eq__){
  223. res = ti->m__eq__(this, rhs, lhs);
  224. if(res != vm->NotImplemented) return res == vm->True;
  225. }
  226. res = call_method(rhs, __eq__, lhs);
  227. if(res != vm->NotImplemented) return res == vm->True;
  228. return false;
  229. }
  230. i64 VM::normalized_index(i64 index, int size){
  231. if(index < 0) index += size;
  232. if(index < 0 || index >= size){
  233. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  234. }
  235. return index;
  236. }
  237. PyObject* VM::py_next(PyObject* obj){
  238. const PyTypeInfo* ti = _inst_type_info(obj);
  239. if(ti->m__next__) return ti->m__next__(this, obj);
  240. return call_method(obj, __next__);
  241. }
  242. bool VM::py_callable(PyObject* obj){
  243. Type cls = vm->_tp(obj);
  244. switch(cls.index){
  245. case VM::tp_function.index: return vm->True;
  246. case VM::tp_native_func.index: return vm->True;
  247. case VM::tp_bound_method.index: return vm->True;
  248. case VM::tp_type.index: return vm->True;
  249. }
  250. return vm->find_name_in_mro(cls, __call__) != nullptr;
  251. }
  252. PyObject* VM::py_import(Str path, bool throw_err){
  253. if(path.empty()) vm->ValueError("empty module name");
  254. static auto f_join = [](const std::vector<std::string_view>& cpnts){
  255. SStream ss;
  256. for(int i=0; i<cpnts.size(); i++){
  257. if(i != 0) ss << ".";
  258. ss << cpnts[i];
  259. }
  260. return Str(ss.str());
  261. };
  262. if(path[0] == '.'){
  263. if(_import_context.pending.empty()){
  264. ImportError("relative import outside of package");
  265. }
  266. Str curr_path = _import_context.pending.back();
  267. bool curr_is_init = _import_context.pending_is_init.back();
  268. // convert relative path to absolute path
  269. std::vector<std::string_view> cpnts = curr_path.split('.');
  270. int prefix = 0; // how many dots in the prefix
  271. for(int i=0; i<path.length(); i++){
  272. if(path[i] == '.') prefix++;
  273. else break;
  274. }
  275. if(prefix > cpnts.size()) ImportError("attempted relative import beyond top-level package");
  276. path = path.substr(prefix); // remove prefix
  277. for(int i=(int)curr_is_init; i<prefix; i++) cpnts.pop_back();
  278. if(!path.empty()) cpnts.push_back(path.sv());
  279. path = f_join(cpnts);
  280. }
  281. PK_ASSERT(path.begin()[0] != '.' && path.end()[-1] != '.');
  282. // check existing module
  283. StrName name(path);
  284. PyObject* ext_mod = _modules.try_get(name);
  285. if(ext_mod != nullptr) return ext_mod;
  286. std::vector<std::string_view> path_cpnts = path.split('.');
  287. // check circular import
  288. if(_import_context.pending.size() > 128){
  289. ImportError("maximum recursion depth exceeded while importing");
  290. }
  291. // try import
  292. Str filename = path.replace('.', PK_PLATFORM_SEP) + ".py";
  293. Str source;
  294. bool is_init = false;
  295. auto it = _lazy_modules.find(name);
  296. if(it == _lazy_modules.end()){
  297. int out_size;
  298. unsigned char* out = _import_handler(filename.data, filename.size, &out_size);
  299. if(out == nullptr){
  300. filename = path.replace('.', PK_PLATFORM_SEP).str() + PK_PLATFORM_SEP + "__init__.py";
  301. is_init = true;
  302. out = _import_handler(filename.data, filename.size, &out_size);
  303. }
  304. if(out == nullptr){
  305. if(throw_err) ImportError(_S("module ", path.escape(), " not found"));
  306. else return nullptr;
  307. }
  308. PK_ASSERT(out_size >= 0)
  309. source = Str(std::string_view((char*)out, out_size));
  310. free(out);
  311. }else{
  312. source = it->second;
  313. _lazy_modules.erase(it);
  314. }
  315. auto _ = _import_context.scope(path, is_init);
  316. CodeObject_ code = compile(source, filename, EXEC_MODE);
  317. Str name_cpnt = path_cpnts.back();
  318. path_cpnts.pop_back();
  319. PyObject* new_mod = new_module(name_cpnt, f_join(path_cpnts));
  320. _exec(code, new_mod);
  321. return new_mod;
  322. }
  323. VM::~VM() {
  324. callstack.clear();
  325. s_data.clear();
  326. _all_types.clear();
  327. _modules.clear();
  328. _lazy_modules.clear();
  329. }
  330. PyObject* VM::py_negate(PyObject* obj){
  331. const PyTypeInfo* ti = _inst_type_info(obj);
  332. if(ti->m__neg__) return ti->m__neg__(this, obj);
  333. return call_method(obj, __neg__);
  334. }
  335. bool VM::py_bool(PyObject* obj){
  336. if(obj == vm->True) return true;
  337. if(obj == vm->False) return false;
  338. if(obj == None) return false;
  339. if(is_int(obj)) return _CAST(i64, obj) != 0;
  340. if(is_float(obj)) return _CAST(f64, obj) != 0.0;
  341. PyObject* self;
  342. PyObject* len_f = get_unbound_method(obj, __len__, &self, false);
  343. if(self != PY_NULL){
  344. PyObject* ret = call_method(self, len_f);
  345. return CAST(i64, ret) > 0;
  346. }
  347. return true;
  348. }
  349. PyObject* VM::py_list(PyObject* it){
  350. auto _lock = heap.gc_scope_lock();
  351. it = py_iter(it);
  352. List list;
  353. PyObject* obj = py_next(it);
  354. while(obj != StopIteration){
  355. list.push_back(obj);
  356. obj = py_next(it);
  357. }
  358. return VAR(std::move(list));
  359. }
  360. void VM::parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step){
  361. auto clip = [](int value, int min, int max){
  362. if(value < min) return min;
  363. if(value > max) return max;
  364. return value;
  365. };
  366. if(s.step == None) step = 1;
  367. else step = CAST(int, s.step);
  368. if(step == 0) ValueError("slice step cannot be zero");
  369. if(step > 0){
  370. if(s.start == None){
  371. start = 0;
  372. }else{
  373. start = CAST(int, s.start);
  374. if(start < 0) start += length;
  375. start = clip(start, 0, length);
  376. }
  377. if(s.stop == None){
  378. stop = length;
  379. }else{
  380. stop = CAST(int, s.stop);
  381. if(stop < 0) stop += length;
  382. stop = clip(stop, 0, length);
  383. }
  384. }else{
  385. if(s.start == None){
  386. start = length - 1;
  387. }else{
  388. start = CAST(int, s.start);
  389. if(start < 0) start += length;
  390. start = clip(start, -1, length - 1);
  391. }
  392. if(s.stop == None){
  393. stop = -1;
  394. }else{
  395. stop = CAST(int, s.stop);
  396. if(stop < 0) stop += length;
  397. stop = clip(stop, -1, length - 1);
  398. }
  399. }
  400. }
  401. i64 VM::py_hash(PyObject* obj){
  402. // https://docs.python.org/3.10/reference/datamodel.html#object.__hash__
  403. const PyTypeInfo* ti = _inst_type_info(obj);
  404. if(ti->m__hash__) return ti->m__hash__(this, obj);
  405. PyObject* self;
  406. PyObject* f = get_unbound_method(obj, __hash__, &self, false);
  407. if(f != nullptr){
  408. PyObject* ret = call_method(self, f);
  409. return CAST(i64, ret);
  410. }
  411. // if it is trivial `object`, return PK_BITS
  412. if(ti == &_all_types[tp_object]) return PK_BITS(obj);
  413. // otherwise, we check if it has a custom __eq__ other than object.__eq__
  414. bool has_custom_eq = false;
  415. if(ti->m__eq__) has_custom_eq = true;
  416. else{
  417. f = get_unbound_method(obj, __eq__, &self, false);
  418. has_custom_eq = f != _t(tp_object)->attr(__eq__);
  419. }
  420. if(has_custom_eq){
  421. TypeError(_S("unhashable type: ", ti->name.escape()));
  422. PK_UNREACHABLE()
  423. }else{
  424. return PK_BITS(obj);
  425. }
  426. }
  427. PyObject* VM::_format_string(Str spec, PyObject* obj){
  428. if(spec.empty()) return py_str(obj);
  429. char type;
  430. switch(spec.end()[-1]){
  431. case 'f': case 'd': case 's':
  432. type = spec.end()[-1];
  433. spec = spec.substr(0, spec.length() - 1);
  434. break;
  435. default: type = ' '; break;
  436. }
  437. char pad_c = ' ';
  438. for(char c: std::string_view("0-=*#@!~")){
  439. if(spec[0] == c){
  440. pad_c = c;
  441. spec = spec.substr(1);
  442. break;
  443. }
  444. }
  445. char align;
  446. if(spec[0] == '^'){
  447. align = '^';
  448. spec = spec.substr(1);
  449. }else if(spec[0] == '>'){
  450. align = '>';
  451. spec = spec.substr(1);
  452. }else if(spec[0] == '<'){
  453. align = '<';
  454. spec = spec.substr(1);
  455. }else{
  456. if(is_int(obj) || is_float(obj)) align = '>';
  457. else align = '<';
  458. }
  459. int dot = spec.index(".");
  460. int width, precision;
  461. try{
  462. if(dot >= 0){
  463. if(dot == 0){
  464. width = -1;
  465. }else{
  466. width = std::stoi(spec.substr(0, dot).str());
  467. }
  468. precision = std::stoi(spec.substr(dot+1).str());
  469. }else{
  470. width = std::stoi(spec.str());
  471. precision = -1;
  472. }
  473. }catch(...){
  474. ValueError("invalid format specifer");
  475. }
  476. if(type != 'f' && dot >= 0) ValueError("precision not allowed in the format specifier");
  477. Str ret;
  478. if(type == 'f'){
  479. f64 val = CAST(f64, obj);
  480. if(precision < 0) precision = 6;
  481. SStream ss;
  482. ss.setprecision(precision);
  483. ss << val;
  484. ret = ss.str();
  485. }else if(type == 'd'){
  486. ret = std::to_string(CAST(i64, obj));
  487. }else if(type == 's'){
  488. ret = CAST(Str&, obj);
  489. }else{
  490. ret = CAST(Str&, py_str(obj));
  491. }
  492. if(width != -1 && width > ret.length()){
  493. int pad = width - ret.length();
  494. if(align == '>' || align == '<'){
  495. std::string padding(pad, pad_c);
  496. if(align == '>') ret = padding.c_str() + ret;
  497. else ret = ret + padding.c_str();
  498. }else{ // ^
  499. int pad_left = pad / 2;
  500. int pad_right = pad - pad_left;
  501. std::string padding_left(pad_left, pad_c);
  502. std::string padding_right(pad_right, pad_c);
  503. ret = padding_left.c_str() + ret + padding_right.c_str();
  504. }
  505. }
  506. return VAR(ret);
  507. }
  508. PyObject* VM::new_module(Str name, Str package) {
  509. PyObject* obj = heap._new<DummyModule>(tp_module);
  510. obj->attr().set(__name__, VAR(name));
  511. obj->attr().set(__package__, VAR(package));
  512. // convert to fullname
  513. if(!package.empty()) name = package + "." + name;
  514. obj->attr().set(__path__, VAR(name));
  515. // we do not allow override in order to avoid memory leak
  516. // it is because Module objects are not garbage collected
  517. if(_modules.contains(name)){
  518. throw std::runtime_error(_S("module ", name.escape(), " already exists").str());
  519. }
  520. // set it into _modules
  521. _modules.set(name, obj);
  522. return obj;
  523. }
  524. static std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  525. std::string argStr = std::to_string(byte.arg);
  526. switch(byte.op){
  527. case OP_LOAD_CONST: case OP_FORMAT_STRING: case OP_IMPORT_PATH:
  528. if(vm != nullptr){
  529. argStr += _S(" (", CAST(Str, vm->py_repr(co->consts[byte.arg])), ")").sv();
  530. }
  531. break;
  532. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  533. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  534. case OP_BEGIN_CLASS: case OP_GOTO:
  535. case OP_DELETE_GLOBAL: case OP_INC_GLOBAL: case OP_DEC_GLOBAL: case OP_STORE_CLASS_ATTR:
  536. argStr += _S(" (", StrName(byte.arg).sv(), ")").sv();
  537. break;
  538. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST: case OP_INC_FAST: case OP_DEC_FAST:
  539. argStr += _S(" (", co->varnames[byte.arg].sv(), ")").sv();
  540. break;
  541. case OP_LOAD_FUNCTION:
  542. argStr += _S(" (", co->func_decls[byte.arg]->code->name, ")").sv();
  543. break;
  544. }
  545. return argStr;
  546. }
  547. Str VM::disassemble(CodeObject_ co){
  548. auto pad = [](const Str& s, const int n){
  549. if(s.length() >= n) return s.substr(0, n);
  550. return s + std::string(n - s.length(), ' ');
  551. };
  552. std::vector<int> jumpTargets;
  553. for(auto byte : co->codes){
  554. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE || byte.op == OP_SHORTCUT_IF_FALSE_OR_POP || byte.op == OP_FOR_ITER){
  555. jumpTargets.push_back(byte.arg);
  556. }
  557. if(byte.op == OP_GOTO){
  558. // TODO: pre-compute jump targets for OP_GOTO
  559. int* target = co->labels.try_get_2_likely_found(StrName(byte.arg));
  560. if(target != nullptr) jumpTargets.push_back(*target);
  561. }
  562. }
  563. SStream ss;
  564. int prev_line = -1;
  565. for(int i=0; i<co->codes.size(); i++){
  566. const Bytecode& byte = co->codes[i];
  567. Str line = std::to_string(co->lines[i]);
  568. if(co->lines[i] == prev_line) line = "";
  569. else{
  570. if(prev_line != -1) ss << "\n";
  571. prev_line = co->lines[i];
  572. }
  573. std::string pointer;
  574. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  575. pointer = "-> ";
  576. }else{
  577. pointer = " ";
  578. }
  579. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  580. std::string bc_name(OP_NAMES[byte.op]);
  581. if(co->is_virtual[i]) bc_name += '*';
  582. ss << " " << pad(bc_name, 25) << " ";
  583. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  584. std::string argStr = _opcode_argstr(this, byte, co.get());
  585. ss << argStr;
  586. // ss << pad(argStr, 40); // may overflow
  587. // ss << co->blocks[byte.block].type;
  588. if(i != co->codes.size() - 1) ss << '\n';
  589. }
  590. for(auto& decl: co->func_decls){
  591. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  592. ss << disassemble(decl->code);
  593. }
  594. ss << "\n";
  595. return Str(ss.str());
  596. }
  597. #if PK_DEBUG_CEVAL_STEP
  598. void VM::_log_s_data(const char* title) {
  599. if(_main == nullptr) return;
  600. if(callstack.empty()) return;
  601. SStream ss;
  602. if(title) ss << title << " | ";
  603. std::map<PyObject**, int> sp_bases;
  604. for(Frame& f: callstack.data()){
  605. if(f._sp_base == nullptr) PK_FATAL_ERROR();
  606. sp_bases[f._sp_base] += 1;
  607. }
  608. FrameId frame = top_frame();
  609. int line = frame->co->lines[frame->_ip];
  610. ss << frame->co->name << ":" << line << " [";
  611. for(PyObject** p=s_data.begin(); p!=s_data.end(); p++){
  612. ss << std::string(sp_bases[p], '|');
  613. if(sp_bases[p] > 0) ss << " ";
  614. PyObject* obj = *p;
  615. if(obj == nullptr) ss << "(nil)";
  616. else if(obj == PY_NULL) ss << "NULL";
  617. else if(is_int(obj)) ss << CAST(i64, obj);
  618. else if(is_float(obj)) ss << CAST(f64, obj);
  619. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  620. else if(obj == None) ss << "None";
  621. else if(obj == True) ss << "True";
  622. else if(obj == False) ss << "False";
  623. else if(is_type(obj, tp_function)){
  624. auto& f = CAST(Function&, obj);
  625. ss << f.decl->code->name << "(...)";
  626. } else if(is_type(obj, tp_type)){
  627. Type t = PK_OBJ_GET(Type, obj);
  628. ss << "<class " + _all_types[t].name.escape() + ">";
  629. } else if(is_type(obj, tp_list)){
  630. auto& t = CAST(List&, obj);
  631. ss << "list(size=" << t.size() << ")";
  632. } else if(is_type(obj, tp_tuple)){
  633. auto& t = CAST(Tuple&, obj);
  634. ss << "tuple(size=" << t.size() << ")";
  635. } else ss << "(" << _type_name(this, obj->type) << ")";
  636. ss << ", ";
  637. }
  638. std::string output = ss.str();
  639. if(!s_data.empty()) {
  640. output.pop_back(); output.pop_back();
  641. }
  642. output.push_back(']');
  643. Bytecode byte = frame->co->codes[frame->_ip];
  644. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  645. }
  646. #endif
  647. void VM::init_builtin_types(){
  648. _all_types.push_back({heap._new<Type>(Type(1), Type(0)), -1, nullptr, "object", true});
  649. _all_types.push_back({heap._new<Type>(Type(1), Type(1)), 0, nullptr, "type", false});
  650. if(tp_int != _new_type_object("int")) exit(-3);
  651. if((tp_float != _new_type_object("float"))) exit(-3);
  652. if(tp_bool != _new_type_object("bool")) exit(-3);
  653. if(tp_str != _new_type_object("str")) exit(-3);
  654. if(tp_list != _new_type_object("list")) exit(-3);
  655. if(tp_tuple != _new_type_object("tuple")) exit(-3);
  656. if(tp_slice != _new_type_object("slice")) exit(-3);
  657. if(tp_range != _new_type_object("range")) exit(-3);
  658. if(tp_module != _new_type_object("module")) exit(-3);
  659. if(tp_function != _new_type_object("function")) exit(-3);
  660. if(tp_native_func != _new_type_object("native_func")) exit(-3);
  661. if(tp_bound_method != _new_type_object("bound_method")) exit(-3);
  662. if(tp_super != _new_type_object("super")) exit(-3);
  663. if(tp_exception != _new_type_object("Exception", 0, true)) exit(-3);
  664. if(tp_bytes != _new_type_object("bytes")) exit(-3);
  665. if(tp_mappingproxy != _new_type_object("mappingproxy")) exit(-3);
  666. if(tp_dict != _new_type_object("dict")) exit(-3);
  667. if(tp_property != _new_type_object("property")) exit(-3);
  668. if(tp_star_wrapper != _new_type_object("_star_wrapper")) exit(-3);
  669. if(tp_staticmethod != _new_type_object("staticmethod")) exit(-3);
  670. if(tp_classmethod != _new_type_object("classmethod")) exit(-3);
  671. // SyntaxError and IndentationError must be created here
  672. Type tp_syntax_error = _new_type_object("SyntaxError", tp_exception, true);
  673. Type tp_indentation_error = _new_type_object("IndentationError", tp_syntax_error, true);
  674. this->None = heap._new<Dummy>(_new_type_object("NoneType"));
  675. this->NotImplemented = heap._new<Dummy>(_new_type_object("NotImplementedType"));
  676. this->Ellipsis = heap._new<Dummy>(_new_type_object("ellipsis"));
  677. this->True = heap._new<Dummy>(tp_bool);
  678. this->False = heap._new<Dummy>(tp_bool);
  679. this->StopIteration = heap._new<Dummy>(_new_type_object("StopIterationType"));
  680. this->builtins = new_module("builtins");
  681. // setup public types
  682. builtins->attr().set("type", _t(tp_type));
  683. builtins->attr().set("object", _t(tp_object));
  684. builtins->attr().set("bool", _t(tp_bool));
  685. builtins->attr().set("int", _t(tp_int));
  686. builtins->attr().set("float", _t(tp_float));
  687. builtins->attr().set("str", _t(tp_str));
  688. builtins->attr().set("list", _t(tp_list));
  689. builtins->attr().set("tuple", _t(tp_tuple));
  690. builtins->attr().set("range", _t(tp_range));
  691. builtins->attr().set("bytes", _t(tp_bytes));
  692. builtins->attr().set("dict", _t(tp_dict));
  693. builtins->attr().set("property", _t(tp_property));
  694. builtins->attr().set("StopIteration", StopIteration);
  695. builtins->attr().set("NotImplemented", NotImplemented);
  696. builtins->attr().set("slice", _t(tp_slice));
  697. builtins->attr().set("Exception", _t(tp_exception));
  698. builtins->attr().set("SyntaxError", _t(tp_syntax_error));
  699. builtins->attr().set("IndentationError", _t(tp_indentation_error));
  700. post_init();
  701. this->_main = new_module("__main__");
  702. }
  703. // `heap.gc_scope_lock();` needed before calling this function
  704. void VM::_unpack_as_list(ArgsView args, List& list){
  705. for(PyObject* obj: args){
  706. if(is_non_tagged_type(obj, tp_star_wrapper)){
  707. const StarWrapper& w = _CAST(StarWrapper&, obj);
  708. // maybe this check should be done in the compile time
  709. if(w.level != 1) TypeError("expected level 1 star wrapper");
  710. PyObject* _0 = py_iter(w.obj);
  711. PyObject* _1 = py_next(_0);
  712. while(_1 != StopIteration){
  713. list.push_back(_1);
  714. _1 = py_next(_0);
  715. }
  716. }else{
  717. list.push_back(obj);
  718. }
  719. }
  720. }
  721. // `heap.gc_scope_lock();` needed before calling this function
  722. void VM::_unpack_as_dict(ArgsView args, Dict& dict){
  723. for(PyObject* obj: args){
  724. if(is_non_tagged_type(obj, tp_star_wrapper)){
  725. const StarWrapper& w = _CAST(StarWrapper&, obj);
  726. // maybe this check should be done in the compile time
  727. if(w.level != 2) TypeError("expected level 2 star wrapper");
  728. const Dict& other = CAST(Dict&, w.obj);
  729. dict.update(other);
  730. }else{
  731. const Tuple& t = CAST(Tuple&, obj);
  732. if(t.size() != 2) TypeError("expected tuple of length 2");
  733. dict.set(t[0], t[1]);
  734. }
  735. }
  736. }
  737. void VM::_prepare_py_call(PyObject** buffer, ArgsView args, ArgsView kwargs, const FuncDecl_& decl){
  738. const CodeObject* co = decl->code.get();
  739. int co_nlocals = co->varnames.size();
  740. int decl_argc = decl->args.size();
  741. if(args.size() < decl_argc){
  742. vm->TypeError(_S(
  743. co->name, "() takes ", decl_argc, " positional arguments but ", args.size(), " were given"
  744. ));
  745. }
  746. int i = 0;
  747. // prepare args
  748. for(int index: decl->args) buffer[index] = args[i++];
  749. // set extra varnames to PY_NULL
  750. for(int j=i; j<co_nlocals; j++) buffer[j] = PY_NULL;
  751. // prepare kwdefaults
  752. for(auto& kv: decl->kwargs) buffer[kv.index] = kv.value;
  753. // handle *args
  754. if(decl->starred_arg != -1){
  755. ArgsView vargs(args.begin() + i, args.end());
  756. buffer[decl->starred_arg] = VAR(vargs.to_tuple());
  757. i += vargs.size();
  758. }else{
  759. // kwdefaults override
  760. for(auto& kv: decl->kwargs){
  761. if(i >= args.size()) break;
  762. buffer[kv.index] = args[i++];
  763. }
  764. if(i < args.size()) TypeError(_S("too many arguments", " (", decl->code->name, ')'));
  765. }
  766. PyObject* vkwargs;
  767. if(decl->starred_kwarg != -1){
  768. vkwargs = VAR(Dict(this));
  769. buffer[decl->starred_kwarg] = vkwargs;
  770. }else{
  771. vkwargs = nullptr;
  772. }
  773. for(int j=0; j<kwargs.size(); j+=2){
  774. StrName key(CAST(int, kwargs[j]));
  775. int index = decl->kw_to_index.try_get_likely_found(key);
  776. // if key is an explicit key, set as local variable
  777. if(index >= 0){
  778. buffer[index] = kwargs[j+1];
  779. }else{
  780. // otherwise, set as **kwargs if possible
  781. if(vkwargs == nullptr){
  782. TypeError(_S(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  783. }else{
  784. Dict& dict = _CAST(Dict&, vkwargs);
  785. dict.set(VAR(key.sv()), kwargs[j+1]);
  786. }
  787. }
  788. }
  789. }
  790. PyObject* VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  791. PyObject** p1 = s_data._sp - KWARGC*2;
  792. PyObject** p0 = p1 - ARGC - 2;
  793. // [callable, <self>, args..., kwargs...]
  794. // ^p0 ^p1 ^_sp
  795. PyObject* callable = p1[-(ARGC + 2)];
  796. bool method_call = p1[-(ARGC + 1)] != PY_NULL;
  797. // handle boundmethod, do a patch
  798. if(is_non_tagged_type(callable, tp_bound_method)){
  799. if(method_call) PK_FATAL_ERROR();
  800. BoundMethod& bm = PK_OBJ_GET(BoundMethod, callable);
  801. callable = bm.func; // get unbound method
  802. p1[-(ARGC + 2)] = bm.func;
  803. p1[-(ARGC + 1)] = bm.self;
  804. method_call = true;
  805. // [unbound, self, args..., kwargs...]
  806. }
  807. ArgsView args(p1 - ARGC - int(method_call), p1);
  808. ArgsView kwargs(p1, s_data._sp);
  809. PyObject** _base = args.begin();
  810. PyObject* buffer[PK_MAX_CO_VARNAMES];
  811. if(is_non_tagged_type(callable, tp_native_func)){
  812. const auto& f = PK_OBJ_GET(NativeFunc, callable);
  813. PyObject* ret;
  814. if(f.decl != nullptr){
  815. int co_nlocals = f.decl->code->varnames.size();
  816. _prepare_py_call(buffer, args, kwargs, f.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. ret = f.call(vm, ArgsView(s_data._sp - co_nlocals, s_data._sp));
  821. }else{
  822. if(KWARGC != 0) TypeError("old-style native_func does not accept keyword arguments");
  823. f.check_size(this, args);
  824. ret = f.call(this, args);
  825. }
  826. s_data.reset(p0);
  827. return ret;
  828. }
  829. if(is_non_tagged_type(callable, tp_function)){
  830. /*****************_py_call*****************/
  831. // callable must be a `function` object
  832. if(s_data.is_overflow()) StackOverflowError();
  833. const Function& fn = PK_OBJ_GET(Function, callable);
  834. const FuncDecl_& decl = fn.decl;
  835. const CodeObject* co = decl->code.get();
  836. int co_nlocals = co->varnames.size();
  837. if(decl->is_simple){
  838. if(args.size() != decl->args.size()){
  839. TypeError(_S(
  840. co->name, "() takes ", decl->args.size(), " positional arguments but ", args.size(), " were given"
  841. ));
  842. }
  843. if(!kwargs.empty()){
  844. TypeError(_S(co->name, "() takes no keyword arguments"));
  845. }
  846. s_data.reset(_base + co_nlocals);
  847. int i = 0;
  848. // prepare args
  849. for(int index: decl->args) _base[index] = args[i++];
  850. // set extra varnames to PY_NULL
  851. for(int j=i; j<co_nlocals; j++) _base[j] = PY_NULL;
  852. goto __FAST_CALL;
  853. }
  854. _prepare_py_call(buffer, args, kwargs, decl);
  855. if(co->is_generator){
  856. s_data.reset(p0);
  857. return _py_generator(
  858. Frame(&s_data, nullptr, co, fn._module, callable),
  859. ArgsView(buffer, buffer + co_nlocals)
  860. );
  861. }
  862. // copy buffer back to stack
  863. s_data.reset(_base + co_nlocals);
  864. for(int j=0; j<co_nlocals; j++) _base[j] = buffer[j];
  865. __FAST_CALL:
  866. callstack.emplace(&s_data, p0, co, fn._module, callable, FastLocals(co, args.begin()));
  867. if(op_call) return PY_OP_CALL;
  868. return _run_top_frame();
  869. /*****************_py_call*****************/
  870. }
  871. if(is_non_tagged_type(callable, tp_type)){
  872. if(method_call) PK_FATAL_ERROR();
  873. // [type, NULL, args..., kwargs...]
  874. PyObject* new_f = find_name_in_mro(PK_OBJ_GET(Type, callable), __new__);
  875. PyObject* obj;
  876. #if PK_DEBUG_EXTRA_CHECK
  877. PK_ASSERT(new_f != nullptr);
  878. #endif
  879. if(new_f == cached_object__new__) {
  880. // fast path for object.__new__
  881. Type t = PK_OBJ_GET(Type, callable);
  882. obj = vm->heap.gcnew<DummyInstance>(t);
  883. }else{
  884. PUSH(new_f);
  885. PUSH(PY_NULL);
  886. PUSH(callable); // cls
  887. for(PyObject* o: args) PUSH(o);
  888. for(PyObject* o: kwargs) PUSH(o);
  889. // if obj is not an instance of callable, the behavior is undefined
  890. obj = vectorcall(ARGC+1, KWARGC);
  891. }
  892. // __init__
  893. PyObject* self;
  894. callable = get_unbound_method(obj, __init__, &self, false);
  895. if (self != PY_NULL) {
  896. // replace `NULL` with `self`
  897. p1[-(ARGC + 2)] = callable;
  898. p1[-(ARGC + 1)] = self;
  899. // [init_f, self, args..., kwargs...]
  900. vectorcall(ARGC, KWARGC);
  901. // We just discard the return value of `__init__`
  902. // in cpython it raises a TypeError if the return value is not None
  903. }else{
  904. // manually reset the stack
  905. s_data.reset(p0);
  906. }
  907. return obj;
  908. }
  909. // handle `__call__` overload
  910. PyObject* self;
  911. PyObject* call_f = get_unbound_method(callable, __call__, &self, false);
  912. if(self != PY_NULL){
  913. p1[-(ARGC + 2)] = call_f;
  914. p1[-(ARGC + 1)] = self;
  915. // [call_f, self, args..., kwargs...]
  916. return vectorcall(ARGC, KWARGC, false);
  917. }
  918. TypeError(_type_name(vm, _tp(callable)).escape() + " object is not callable");
  919. PK_UNREACHABLE()
  920. }
  921. void VM::delattr(PyObject *_0, StrName _name){
  922. const PyTypeInfo* ti = _inst_type_info(_0);
  923. if(ti->m__delattr__ && ti->m__delattr__(this, _0, _name)) return;
  924. if(is_tagged(_0) || !_0->is_attr_valid()) TypeError("cannot delete attribute");
  925. if(!_0->attr().del(_name)) AttributeError(_0, _name);
  926. }
  927. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  928. PyObject* VM::getattr(PyObject* obj, StrName name, bool throw_err){
  929. Type objtype(0);
  930. // handle super() proxy
  931. if(is_non_tagged_type(obj, tp_super)){
  932. const Super& super = PK_OBJ_GET(Super, obj);
  933. obj = super.first;
  934. objtype = super.second;
  935. }else{
  936. objtype = _tp(obj);
  937. }
  938. PyObject* cls_var = find_name_in_mro(objtype, name);
  939. if(cls_var != nullptr){
  940. // handle descriptor
  941. if(is_non_tagged_type(cls_var, tp_property)){
  942. const Property& prop = PK_OBJ_GET(Property, cls_var);
  943. return call(prop.getter, obj);
  944. }
  945. }
  946. // handle instance __dict__
  947. if(!is_tagged(obj) && obj->is_attr_valid()){
  948. PyObject* val;
  949. if(obj->type == tp_type){
  950. val = find_name_in_mro(PK_OBJ_GET(Type, obj), name);
  951. if(val != nullptr){
  952. if(is_tagged(val)) return val;
  953. if(val->type == tp_staticmethod) return PK_OBJ_GET(StaticMethod, val).func;
  954. if(val->type == tp_classmethod) return VAR(BoundMethod(obj, PK_OBJ_GET(ClassMethod, val).func));
  955. return val;
  956. }
  957. }else{
  958. val = obj->attr().try_get_likely_found(name);
  959. if(val != nullptr) return val;
  960. }
  961. }
  962. if(cls_var != nullptr){
  963. // bound method is non-data descriptor
  964. if(!is_tagged(cls_var)){
  965. switch(cls_var->type){
  966. case tp_function.index:
  967. return VAR(BoundMethod(obj, cls_var));
  968. case tp_native_func.index:
  969. return VAR(BoundMethod(obj, cls_var));
  970. case tp_staticmethod.index:
  971. return PK_OBJ_GET(StaticMethod, cls_var).func;
  972. case tp_classmethod.index:
  973. return VAR(BoundMethod(_t(objtype), PK_OBJ_GET(ClassMethod, cls_var).func));
  974. }
  975. }
  976. return cls_var;
  977. }
  978. const PyTypeInfo* ti = &_all_types[objtype];
  979. if(ti->m__getattr__){
  980. PyObject* ret = ti->m__getattr__(this, obj, name);
  981. if(ret) return ret;
  982. }
  983. if(throw_err) AttributeError(obj, name);
  984. return nullptr;
  985. }
  986. // used by OP_LOAD_METHOD
  987. // try to load a unbound method (fallback to `getattr` if not found)
  988. PyObject* VM::get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err, bool fallback){
  989. *self = PY_NULL;
  990. Type objtype(0);
  991. // handle super() proxy
  992. if(is_non_tagged_type(obj, tp_super)){
  993. const Super& super = PK_OBJ_GET(Super, obj);
  994. obj = super.first;
  995. objtype = super.second;
  996. }else{
  997. objtype = _tp(obj);
  998. }
  999. PyObject* cls_var = find_name_in_mro(objtype, name);
  1000. if(fallback){
  1001. if(cls_var != nullptr){
  1002. // handle descriptor
  1003. if(is_non_tagged_type(cls_var, tp_property)){
  1004. const Property& prop = PK_OBJ_GET(Property, cls_var);
  1005. return call(prop.getter, obj);
  1006. }
  1007. }
  1008. // handle instance __dict__
  1009. if(!is_tagged(obj) && obj->is_attr_valid()){
  1010. PyObject* val;
  1011. if(obj->type == tp_type){
  1012. val = find_name_in_mro(PK_OBJ_GET(Type, obj), name);
  1013. if(val != nullptr){
  1014. if(is_tagged(val)) return val;
  1015. if(val->type == tp_staticmethod) return PK_OBJ_GET(StaticMethod, val).func;
  1016. if(val->type == tp_classmethod) return VAR(BoundMethod(obj, PK_OBJ_GET(ClassMethod, val).func));
  1017. return val;
  1018. }
  1019. }else{
  1020. val = obj->attr().try_get_likely_found(name);
  1021. if(val != nullptr) return val;
  1022. }
  1023. }
  1024. }
  1025. if(cls_var != nullptr){
  1026. if(!is_tagged(cls_var)){
  1027. switch(cls_var->type){
  1028. case tp_function.index:
  1029. *self = obj;
  1030. break;
  1031. case tp_native_func.index:
  1032. *self = obj;
  1033. break;
  1034. case tp_staticmethod.index:
  1035. *self = PY_NULL;
  1036. return PK_OBJ_GET(StaticMethod, cls_var).func;
  1037. case tp_classmethod.index:
  1038. *self = _t(objtype);
  1039. return PK_OBJ_GET(ClassMethod, cls_var).func;
  1040. }
  1041. }
  1042. return cls_var;
  1043. }
  1044. const PyTypeInfo* ti = &_all_types[objtype];
  1045. if(fallback && ti->m__getattr__){
  1046. PyObject* ret = ti->m__getattr__(this, obj, name);
  1047. if(ret) return ret;
  1048. }
  1049. if(throw_err) AttributeError(obj, name);
  1050. return nullptr;
  1051. }
  1052. void VM::setattr(PyObject* obj, StrName name, PyObject* value){
  1053. Type objtype(0);
  1054. // handle super() proxy
  1055. if(is_non_tagged_type(obj, tp_super)){
  1056. Super& super = PK_OBJ_GET(Super, obj);
  1057. obj = super.first;
  1058. objtype = super.second;
  1059. }else{
  1060. objtype = _tp(obj);
  1061. }
  1062. PyObject* cls_var = find_name_in_mro(objtype, name);
  1063. if(cls_var != nullptr){
  1064. // handle descriptor
  1065. if(is_non_tagged_type(cls_var, tp_property)){
  1066. const Property& prop = _CAST(Property&, cls_var);
  1067. if(prop.setter != vm->None){
  1068. call(prop.setter, obj, value);
  1069. }else{
  1070. TypeError(_S("readonly attribute: ", name.escape()));
  1071. }
  1072. return;
  1073. }
  1074. }
  1075. const PyTypeInfo* ti = &_all_types[objtype];
  1076. if(ti->m__setattr__){
  1077. ti->m__setattr__(this, obj, name, value);
  1078. return;
  1079. }
  1080. // handle instance __dict__
  1081. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  1082. obj->attr().set(name, value);
  1083. }
  1084. PyObject* VM::bind(PyObject* obj, const char* sig, NativeFuncC fn, UserData userdata, BindType bt){
  1085. return bind(obj, sig, nullptr, fn, userdata, bt);
  1086. }
  1087. PyObject* VM::bind(PyObject* obj, const char* sig, const char* docstring, NativeFuncC fn, UserData userdata, BindType bt){
  1088. CodeObject_ co;
  1089. try{
  1090. // fn(a, b, *c, d=1) -> None
  1091. co = compile(_S("def ", sig, " : pass"), "<bind>", EXEC_MODE);
  1092. }catch(const Exception&){
  1093. throw std::runtime_error("invalid signature: " + std::string(sig));
  1094. }
  1095. if(co->func_decls.size() != 1){
  1096. throw std::runtime_error("expected 1 function declaration");
  1097. }
  1098. FuncDecl_ decl = co->func_decls[0];
  1099. decl->signature = Str(sig);
  1100. if(docstring != nullptr){
  1101. decl->docstring = Str(docstring).strip();
  1102. }
  1103. PyObject* f_obj = VAR(NativeFunc(fn, decl));
  1104. PK_OBJ_GET(NativeFunc, f_obj).set_userdata(userdata);
  1105. switch(bt){
  1106. case BindType::STATICMETHOD:
  1107. f_obj = VAR(StaticMethod(f_obj));
  1108. break;
  1109. case BindType::CLASSMETHOD:
  1110. f_obj = VAR(ClassMethod(f_obj));
  1111. break;
  1112. case BindType::DEFAULT:
  1113. break;
  1114. }
  1115. if(obj != nullptr) obj->attr().set(decl->code->name, f_obj);
  1116. return f_obj;
  1117. }
  1118. PyObject* VM::bind_property(PyObject* obj, Str name, NativeFuncC fget, NativeFuncC fset){
  1119. PyObject* _0 = heap.gcnew<NativeFunc>(tp_native_func, fget, 1, false);
  1120. PyObject* _1 = vm->None;
  1121. if(fset != nullptr) _1 = heap.gcnew<NativeFunc>(tp_native_func, fset, 2, false);
  1122. Str signature = name;
  1123. int pos = name.index(":");
  1124. if(pos > 0) name = name.substr(0, pos).strip();
  1125. PyObject* prop = VAR(Property(_0, _1, signature));
  1126. obj->attr().set(name, prop);
  1127. return prop;
  1128. }
  1129. void VM::_builtin_error(StrName type){ _error(call(builtins->attr(type))); }
  1130. void VM::_builtin_error(StrName type, PyObject* arg){ _error(call(builtins->attr(type), arg)); }
  1131. void VM::_builtin_error(StrName type, const Str& msg){ _builtin_error(type, VAR(msg)); }
  1132. void VM::_error(PyObject* e_obj){
  1133. PK_ASSERT(isinstance(e_obj, tp_exception))
  1134. Exception& e = PK_OBJ_GET(Exception, e_obj);
  1135. if(callstack.empty()){
  1136. e.is_re = false;
  1137. throw e;
  1138. }
  1139. PUSH(e_obj);
  1140. _raise();
  1141. }
  1142. void VM::_raise(bool re_raise){
  1143. Frame* frame = top_frame().get();
  1144. Exception& e = PK_OBJ_GET(Exception, s_data.top());
  1145. if(!re_raise){
  1146. e._ip_on_error = frame->_ip;
  1147. e._code_on_error = (void*)frame->co;
  1148. }
  1149. bool ok = frame->jump_to_exception_handler();
  1150. int actual_ip = frame->_ip;
  1151. if(e._ip_on_error >= 0 && e._code_on_error == (void*)frame->co) actual_ip = e._ip_on_error;
  1152. int current_line = frame->co->lines[actual_ip]; // current line
  1153. auto current_f_name = frame->co->name.sv(); // current function name
  1154. if(frame->_callable == nullptr) current_f_name = ""; // not in a function
  1155. e.st_push(frame->co->src, current_line, nullptr, current_f_name);
  1156. if(ok) throw HandledException();
  1157. else throw UnhandledException();
  1158. }
  1159. void ManagedHeap::mark() {
  1160. for(PyObject* obj: _no_gc) PK_OBJ_MARK(obj);
  1161. for(auto& frame : vm->callstack.data()) frame._gc_mark();
  1162. for(PyObject* obj: vm->s_data) PK_OBJ_MARK(obj);
  1163. for(auto [_, co]: vm->_cached_codes) co->_gc_mark();
  1164. if(vm->_last_exception) PK_OBJ_MARK(vm->_last_exception);
  1165. if(vm->_curr_class) PK_OBJ_MARK(vm->_curr_class);
  1166. if(vm->_c.error != nullptr) PK_OBJ_MARK(vm->_c.error);
  1167. if(_gc_marker_ex) _gc_marker_ex(vm);
  1168. }
  1169. StrName _type_name(VM *vm, Type type){
  1170. return vm->_all_types[type].name;
  1171. }
  1172. void VM::bind__getitem__(Type type, PyObject* (*f)(VM*, PyObject*, PyObject*)){
  1173. _all_types[type].m__getitem__ = f;
  1174. PyObject* nf = bind_method<1>(type, "__getitem__", [](VM* vm, ArgsView args){
  1175. return lambda_get_userdata<PyObject*(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  1176. });
  1177. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1178. }
  1179. void VM::bind__setitem__(Type type, void (*f)(VM*, PyObject*, PyObject*, PyObject*)){
  1180. _all_types[type].m__setitem__ = f;
  1181. PyObject* nf = bind_method<2>(type, "__setitem__", [](VM* vm, ArgsView args){
  1182. lambda_get_userdata<void(*)(VM* vm, PyObject*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1], args[2]);
  1183. return vm->None;
  1184. });
  1185. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1186. }
  1187. void VM::bind__delitem__(Type type, void (*f)(VM*, PyObject*, PyObject*)){
  1188. _all_types[type].m__delitem__ = f;
  1189. PyObject* nf = bind_method<1>(type, "__delitem__", [](VM* vm, ArgsView args){
  1190. lambda_get_userdata<void(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  1191. return vm->None;
  1192. });
  1193. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1194. }
  1195. void VM::bind__hash__(Type type, i64 (*f)(VM*, PyObject*)){
  1196. PyObject* obj = _t(type);
  1197. _all_types[type].m__hash__ = f;
  1198. PyObject* nf = bind_method<0>(obj, "__hash__", [](VM* vm, ArgsView args){
  1199. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1200. return VAR(ret);
  1201. });
  1202. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1203. }
  1204. void VM::bind__len__(Type type, i64 (*f)(VM*, PyObject*)){
  1205. PyObject* obj = _t(type);
  1206. _all_types[type].m__len__ = f;
  1207. PyObject* nf = bind_method<0>(obj, "__len__", [](VM* vm, ArgsView args){
  1208. i64 ret = lambda_get_userdata<i64(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);
  1209. return VAR(ret);
  1210. });
  1211. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  1212. }
  1213. void Dict::_probe_0(PyObject *key, bool &ok, int &i) const{
  1214. ok = false;
  1215. i64 hash = vm->py_hash(key);
  1216. i = hash & _mask;
  1217. // std::cout << CAST(Str, vm->py_repr(key)) << " " << hash << " " << i << std::endl;
  1218. for(int j=0; j<_capacity; j++) {
  1219. if(_items[i].first != nullptr){
  1220. if(vm->py_eq(_items[i].first, key)) { ok = true; break; }
  1221. }else{
  1222. if(_items[i].second == nullptr) break;
  1223. }
  1224. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1225. i = ((5*i) + 1) & _mask;
  1226. // std::cout << CAST(Str, vm->py_repr(key)) << " next: " << i << std::endl;
  1227. }
  1228. }
  1229. void Dict::_probe_1(PyObject *key, bool &ok, int &i) const{
  1230. ok = false;
  1231. i = vm->py_hash(key) & _mask;
  1232. while(_items[i].first != nullptr) {
  1233. if(vm->py_eq(_items[i].first, key)) { ok = true; break; }
  1234. // https://github.com/python/cpython/blob/3.8/Objects/dictobject.c#L166
  1235. i = ((5*i) + 1) & _mask;
  1236. }
  1237. }
  1238. void NativeFunc::check_size(VM* vm, ArgsView args) const{
  1239. if(args.size() != argc && argc != -1) {
  1240. vm->TypeError(_S("expected ", argc, " arguments, got ", args.size()));
  1241. }
  1242. }
  1243. PyObject* NativeFunc::call(VM *vm, ArgsView args) const {
  1244. return f(vm, args);
  1245. }
  1246. } // namespace pkpy