vm.cpp 43 KB

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