vm.h 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. #pragma once
  2. #include "codeobject.h"
  3. #include "common.h"
  4. #include "frame.h"
  5. #include "error.h"
  6. #include "gc.h"
  7. #include "memory.h"
  8. #include "obj.h"
  9. #include "str.h"
  10. #include "tuplelist.h"
  11. namespace pkpy{
  12. /* Stack manipulation macros */
  13. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  14. #define TOP() (s_data.top())
  15. #define SECOND() (s_data.second())
  16. #define THIRD() (s_data.third())
  17. #define PEEK(n) (s_data.peek(n))
  18. #define STACK_SHRINK(n) (s_data.shrink(n))
  19. #define PUSH(v) (s_data.push(v))
  20. #define POP() (s_data.pop())
  21. #define POPX() (s_data.popx())
  22. #define STACK_VIEW(n) (s_data.view(n))
  23. typedef Bytes (*ReadFileCwdFunc)(const Str& name);
  24. inline ReadFileCwdFunc _read_file_cwd = [](const Str& name) { return Bytes(); };
  25. inline int set_read_file_cwd(ReadFileCwdFunc func) { _read_file_cwd = func; return 0; }
  26. #define DEF_NATIVE_2(ctype, ptype) \
  27. template<> inline ctype py_cast<ctype>(VM* vm, PyObject* obj) { \
  28. vm->check_non_tagged_type(obj, vm->ptype); \
  29. return OBJ_GET(ctype, obj); \
  30. } \
  31. template<> inline ctype _py_cast<ctype>(VM* vm, PyObject* obj) { \
  32. return OBJ_GET(ctype, obj); \
  33. } \
  34. template<> inline ctype& py_cast<ctype&>(VM* vm, PyObject* obj) { \
  35. vm->check_non_tagged_type(obj, vm->ptype); \
  36. return OBJ_GET(ctype, obj); \
  37. } \
  38. template<> inline ctype& _py_cast<ctype&>(VM* vm, PyObject* obj) { \
  39. return OBJ_GET(ctype, obj); \
  40. } \
  41. inline PyObject* py_var(VM* vm, const ctype& value) { return vm->heap.gcnew(vm->ptype, value);} \
  42. inline PyObject* py_var(VM* vm, ctype&& value) { return vm->heap.gcnew(vm->ptype, std::move(value));}
  43. class Generator final: public BaseIter {
  44. Frame frame;
  45. int state; // 0,1,2
  46. List s_backup;
  47. public:
  48. Generator(VM* vm, Frame&& frame, ArgsView buffer): BaseIter(vm), frame(std::move(frame)), state(0) {
  49. for(PyObject* obj: buffer) s_backup.push_back(obj);
  50. }
  51. PyObject* next() override;
  52. void _gc_mark() const;
  53. };
  54. struct PyTypeInfo{
  55. PyObject* obj;
  56. Type base;
  57. Str name;
  58. bool subclass_enabled;
  59. };
  60. struct FrameId{
  61. std::vector<pkpy::Frame>* data;
  62. int index;
  63. FrameId(std::vector<pkpy::Frame>* data, int index) : data(data), index(index) {}
  64. Frame* operator->() const { return &data->operator[](index); }
  65. };
  66. typedef void(*PrintFunc)(VM*, const Str&);
  67. class VM {
  68. VM* vm; // self reference for simplify code
  69. public:
  70. ManagedHeap heap;
  71. ValueStack s_data;
  72. stack< Frame > callstack;
  73. std::vector<PyTypeInfo> _all_types;
  74. void (*_gc_marker_ex)(VM*) = nullptr;
  75. NameDict _modules; // loaded modules
  76. std::map<StrName, Str> _lazy_modules; // lazy loaded modules
  77. PyObject* None;
  78. PyObject* True;
  79. PyObject* False;
  80. PyObject* Ellipsis;
  81. PyObject* builtins; // builtins module
  82. PyObject* StopIteration;
  83. PyObject* _main; // __main__ module
  84. PrintFunc _stdout;
  85. PrintFunc _stderr;
  86. bool _initialized;
  87. // for quick access
  88. Type tp_object, tp_type, tp_int, tp_float, tp_bool, tp_str;
  89. Type tp_list, tp_tuple;
  90. Type tp_function, tp_native_func, tp_iterator, tp_bound_method;
  91. Type tp_slice, tp_range, tp_module;
  92. Type tp_super, tp_exception, tp_bytes, tp_mappingproxy;
  93. const bool enable_os;
  94. VM(bool enable_os=true) : heap(this), enable_os(enable_os) {
  95. this->vm = this;
  96. _stdout = [](VM* vm, const Str& s) { std::cout << s; };
  97. _stderr = [](VM* vm, const Str& s) { std::cerr << s; };
  98. callstack.reserve(8);
  99. _initialized = false;
  100. init_builtin_types();
  101. _initialized = true;
  102. }
  103. FrameId top_frame() {
  104. #if DEBUG_EXTRA_CHECK
  105. if(callstack.empty()) FATAL_ERROR();
  106. #endif
  107. return FrameId(&callstack.data(), callstack.size()-1);
  108. }
  109. PyObject* asStr(PyObject* obj){
  110. PyObject* self;
  111. PyObject* f = get_unbound_method(obj, __str__, &self, false);
  112. if(self != PY_NULL) return call_method(self, f);
  113. return asRepr(obj);
  114. }
  115. PyObject* asIter(PyObject* obj){
  116. if(is_type(obj, tp_iterator)) return obj;
  117. PyObject* self;
  118. PyObject* iter_f = get_unbound_method(obj, __iter__, &self, false);
  119. if(self != PY_NULL) return call_method(self, iter_f);
  120. TypeError(OBJ_NAME(_t(obj)).escape() + " object is not iterable");
  121. return nullptr;
  122. }
  123. PyObject* find_name_in_mro(PyObject* cls, StrName name){
  124. PyObject* val;
  125. do{
  126. val = cls->attr().try_get(name);
  127. if(val != nullptr) return val;
  128. Type base = _all_types[OBJ_GET(Type, cls)].base;
  129. if(base.index == -1) break;
  130. cls = _all_types[base].obj;
  131. }while(true);
  132. return nullptr;
  133. }
  134. bool isinstance(PyObject* obj, Type cls_t){
  135. Type obj_t = OBJ_GET(Type, _t(obj));
  136. do{
  137. if(obj_t == cls_t) return true;
  138. Type base = _all_types[obj_t].base;
  139. if(base.index == -1) break;
  140. obj_t = base;
  141. }while(true);
  142. return false;
  143. }
  144. PyObject* exec(Str source, Str filename, CompileMode mode, PyObject* _module=nullptr){
  145. if(_module == nullptr) _module = _main;
  146. try {
  147. CodeObject_ code = compile(source, filename, mode);
  148. #if DEBUG_DIS_EXEC
  149. if(_module == _main) std::cout << disassemble(code) << '\n';
  150. #endif
  151. return _exec(code, _module);
  152. }catch (const Exception& e){
  153. _stderr(this, e.summary() + "\n");
  154. }
  155. #if !DEBUG_FULL_EXCEPTION
  156. catch (const std::exception& e) {
  157. _stderr(this, "An std::exception occurred! It could be a bug.\n");
  158. _stderr(this, e.what());
  159. _stderr(this, "\n");
  160. }
  161. #endif
  162. callstack.clear();
  163. s_data.clear();
  164. return nullptr;
  165. }
  166. template<typename ...Args>
  167. PyObject* _exec(Args&&... args){
  168. callstack.emplace(&s_data, s_data._sp, std::forward<Args>(args)...);
  169. return _run_top_frame();
  170. }
  171. void _pop_frame(){
  172. Frame* frame = &callstack.top();
  173. s_data.reset(frame->_sp_base);
  174. callstack.pop();
  175. }
  176. void _push_varargs(){ }
  177. void _push_varargs(PyObject* _0){ PUSH(_0); }
  178. void _push_varargs(PyObject* _0, PyObject* _1){ PUSH(_0); PUSH(_1); }
  179. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2){ PUSH(_0); PUSH(_1); PUSH(_2); }
  180. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2, PyObject* _3){ PUSH(_0); PUSH(_1); PUSH(_2); PUSH(_3); }
  181. template<typename... Args>
  182. PyObject* call(PyObject* callable, Args&&... args){
  183. PUSH(callable);
  184. PUSH(PY_NULL);
  185. _push_varargs(args...);
  186. return vectorcall(sizeof...(args));
  187. }
  188. template<typename... Args>
  189. PyObject* call_method(PyObject* self, PyObject* callable, Args&&... args){
  190. PUSH(callable);
  191. PUSH(self);
  192. _push_varargs(args...);
  193. return vectorcall(sizeof...(args));
  194. }
  195. template<typename... Args>
  196. PyObject* call_method(PyObject* self, StrName name, Args&&... args){
  197. PyObject* callable = get_unbound_method(self, name, &self);
  198. return call_method(self, callable, args...);
  199. }
  200. PyObject* property(NativeFuncC fget, NativeFuncC fset=nullptr){
  201. PyObject* p = builtins->attr("property");
  202. PyObject* _0 = heap.gcnew(tp_native_func, NativeFunc(fget, 1, false));
  203. PyObject* _1 = vm->None;
  204. if(fset != nullptr) _1 = heap.gcnew(tp_native_func, NativeFunc(fset, 2, false));
  205. return call(p, _0, _1);
  206. }
  207. PyObject* new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled=true){
  208. PyObject* obj = heap._new<Type>(tp_type, _all_types.size());
  209. const PyTypeInfo& base_info = _all_types[base];
  210. if(!base_info.subclass_enabled){
  211. TypeError(fmt("type ", base_info.name.escape(), " is not `subclass_enabled`"));
  212. }
  213. PyTypeInfo info{
  214. obj,
  215. base,
  216. (mod!=nullptr && mod!=builtins) ? Str(OBJ_NAME(mod)+"."+name.sv()): name.sv(),
  217. subclass_enabled,
  218. };
  219. if(mod != nullptr) mod->attr().set(name, obj);
  220. _all_types.push_back(info);
  221. return obj;
  222. }
  223. Type _new_type_object(StrName name, Type base=0) {
  224. PyObject* obj = new_type_object(nullptr, name, base, false);
  225. return OBJ_GET(Type, obj);
  226. }
  227. PyObject* _find_type(const Str& type){
  228. PyObject* obj = builtins->attr().try_get(type);
  229. if(obj == nullptr){
  230. for(auto& t: _all_types) if(t.name == type) return t.obj;
  231. throw std::runtime_error(fmt("type not found: ", type));
  232. }
  233. return obj;
  234. }
  235. template<int ARGC>
  236. void bind_func(Str type, Str name, NativeFuncC fn) {
  237. bind_func<ARGC>(_find_type(type), name, fn);
  238. }
  239. template<int ARGC>
  240. void bind_method(Str type, Str name, NativeFuncC fn) {
  241. bind_method<ARGC>(_find_type(type), name, fn);
  242. }
  243. template<int ARGC, typename __T>
  244. void bind_constructor(__T&& type, NativeFuncC fn) {
  245. static_assert(ARGC==-1 || ARGC>=1);
  246. bind_func<ARGC>(std::forward<__T>(type), "__new__", fn);
  247. }
  248. template<typename T, typename __T>
  249. void bind_default_constructor(__T&& type) {
  250. bind_constructor<-1>(std::forward<__T>(type), [](VM* vm, ArgsView args){
  251. Type t = OBJ_GET(Type, args[0]);
  252. return vm->heap.gcnew<T>(t, T());
  253. });
  254. }
  255. template<int ARGC>
  256. void bind_builtin_func(Str name, NativeFuncC fn) {
  257. bind_func<ARGC>(builtins, name, fn);
  258. }
  259. int normalized_index(int index, int size){
  260. if(index < 0) index += size;
  261. if(index < 0 || index >= size){
  262. IndexError(std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  263. }
  264. return index;
  265. }
  266. template<typename P>
  267. PyObject* PyIter(P&& value) {
  268. static_assert(std::is_base_of_v<BaseIter, std::decay_t<P>>);
  269. return heap.gcnew<P>(tp_iterator, std::forward<P>(value));
  270. }
  271. PyObject* PyIterNext(PyObject* obj){
  272. if(is_non_tagged_type(obj, tp_iterator)){
  273. BaseIter* iter = static_cast<BaseIter*>(obj->value());
  274. return iter->next();
  275. }
  276. return call_method(obj, __next__);
  277. }
  278. /***** Error Reporter *****/
  279. void _error(StrName name, const Str& msg){
  280. _error(Exception(name, msg));
  281. }
  282. void _raise(){
  283. bool ok = top_frame()->jump_to_exception_handler();
  284. if(ok) throw HandledException();
  285. else throw UnhandledException();
  286. }
  287. void StackOverflowError() { _error("StackOverflowError", ""); }
  288. void IOError(const Str& msg) { _error("IOError", msg); }
  289. void NotImplementedError(){ _error("NotImplementedError", ""); }
  290. void TypeError(const Str& msg){ _error("TypeError", msg); }
  291. void ZeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  292. void IndexError(const Str& msg){ _error("IndexError", msg); }
  293. void ValueError(const Str& msg){ _error("ValueError", msg); }
  294. void NameError(StrName name){ _error("NameError", fmt("name ", name.escape() + " is not defined")); }
  295. void AttributeError(PyObject* obj, StrName name){
  296. // OBJ_NAME calls getattr, which may lead to a infinite recursion
  297. _error("AttributeError", fmt("type ", OBJ_NAME(_t(obj)).escape(), " has no attribute ", name.escape()));
  298. }
  299. void AttributeError(Str msg){ _error("AttributeError", msg); }
  300. void check_type(PyObject* obj, Type type){
  301. if(is_type(obj, type)) return;
  302. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", but got " + OBJ_NAME(_t(obj)).escape());
  303. }
  304. void check_non_tagged_type(PyObject* obj, Type type){
  305. if(is_non_tagged_type(obj, type)) return;
  306. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", but got " + OBJ_NAME(_t(obj)).escape());
  307. }
  308. void check_int(PyObject* obj){
  309. if(is_int(obj)) return;
  310. check_type(obj, tp_int);
  311. }
  312. void check_float(PyObject* obj){
  313. if(is_float(obj)) return;
  314. check_type(obj, tp_float);
  315. }
  316. PyObject* _t(Type t){
  317. return _all_types[t.index].obj;
  318. }
  319. PyObject* _t(PyObject* obj){
  320. if(is_int(obj)) return _t(tp_int);
  321. if(is_float(obj)) return _t(tp_float);
  322. return _all_types[OBJ_GET(Type, _t(obj->type)).index].obj;
  323. }
  324. ~VM() {
  325. callstack.clear();
  326. s_data.clear();
  327. _all_types.clear();
  328. _modules.clear();
  329. _lazy_modules.clear();
  330. }
  331. void _log_s_data(const char* title = nullptr);
  332. PyObject* vectorcall(int ARGC, int KWARGC=0, bool op_call=false);
  333. CodeObject_ compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope=false);
  334. PyObject* num_negated(PyObject* obj);
  335. f64 num_to_float(PyObject* obj);
  336. bool asBool(PyObject* obj);
  337. i64 hash(PyObject* obj);
  338. PyObject* asRepr(PyObject*);
  339. PyObject* asList(PyObject*);
  340. PyObject* new_module(StrName name);
  341. Str disassemble(CodeObject_ co);
  342. void init_builtin_types();
  343. PyObject* _py_call(PyObject** sp_base, PyObject* callable, ArgsView args, ArgsView kwargs);
  344. PyObject* getattr(PyObject* obj, StrName name, bool throw_err=true);
  345. PyObject* get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err=true, bool fallback=false);
  346. void parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step);
  347. PyObject* format(Str, PyObject*);
  348. void setattr(PyObject* obj, StrName name, PyObject* value);
  349. template<int ARGC>
  350. void bind_method(PyObject*, Str, NativeFuncC);
  351. template<int ARGC>
  352. void bind_func(PyObject*, Str, NativeFuncC);
  353. void _error(Exception);
  354. PyObject* _run_top_frame();
  355. void post_init();
  356. };
  357. inline PyObject* NativeFunc::operator()(VM* vm, ArgsView args) const{
  358. int args_size = args.size() - (int)method; // remove self
  359. if(argc != -1 && args_size != argc) {
  360. vm->TypeError(fmt("expected ", argc, " arguments, but got ", args_size));
  361. }
  362. return f(vm, args);
  363. }
  364. inline void CodeObject::optimize(VM* vm){
  365. // uint32_t base_n = (uint32_t)(names.size() / kLocalsLoadFactor + 0.5);
  366. // perfect_locals_capacity = std::max(find_next_capacity(base_n), NameDict::__Capacity);
  367. // perfect_hash_seed = find_perfect_hash_seed(perfect_locals_capacity, names);
  368. }
  369. DEF_NATIVE_2(Str, tp_str)
  370. DEF_NATIVE_2(List, tp_list)
  371. DEF_NATIVE_2(Tuple, tp_tuple)
  372. DEF_NATIVE_2(Function, tp_function)
  373. DEF_NATIVE_2(NativeFunc, tp_native_func)
  374. DEF_NATIVE_2(BoundMethod, tp_bound_method)
  375. DEF_NATIVE_2(Range, tp_range)
  376. DEF_NATIVE_2(Slice, tp_slice)
  377. DEF_NATIVE_2(Exception, tp_exception)
  378. DEF_NATIVE_2(Bytes, tp_bytes)
  379. DEF_NATIVE_2(MappingProxy, tp_mappingproxy)
  380. #define PY_CAST_INT(T) \
  381. template<> inline T py_cast<T>(VM* vm, PyObject* obj){ \
  382. vm->check_int(obj); \
  383. return (T)(BITS(obj) >> 2); \
  384. } \
  385. template<> inline T _py_cast<T>(VM* vm, PyObject* obj){ \
  386. return (T)(BITS(obj) >> 2); \
  387. }
  388. PY_CAST_INT(char)
  389. PY_CAST_INT(short)
  390. PY_CAST_INT(int)
  391. PY_CAST_INT(long)
  392. PY_CAST_INT(long long)
  393. PY_CAST_INT(unsigned char)
  394. PY_CAST_INT(unsigned short)
  395. PY_CAST_INT(unsigned int)
  396. PY_CAST_INT(unsigned long)
  397. PY_CAST_INT(unsigned long long)
  398. template<> inline float py_cast<float>(VM* vm, PyObject* obj){
  399. vm->check_float(obj);
  400. i64 bits = BITS(obj);
  401. bits = (bits >> 2) << 2;
  402. return BitsCvt(bits)._float;
  403. }
  404. template<> inline float _py_cast<float>(VM* vm, PyObject* obj){
  405. i64 bits = BITS(obj);
  406. bits = (bits >> 2) << 2;
  407. return BitsCvt(bits)._float;
  408. }
  409. template<> inline double py_cast<double>(VM* vm, PyObject* obj){
  410. vm->check_float(obj);
  411. i64 bits = BITS(obj);
  412. bits = (bits >> 2) << 2;
  413. return BitsCvt(bits)._float;
  414. }
  415. template<> inline double _py_cast<double>(VM* vm, PyObject* obj){
  416. i64 bits = BITS(obj);
  417. bits = (bits >> 2) << 2;
  418. return BitsCvt(bits)._float;
  419. }
  420. #define PY_VAR_INT(T) \
  421. inline PyObject* py_var(VM* vm, T _val){ \
  422. i64 val = static_cast<i64>(_val); \
  423. if(((val << 2) >> 2) != val){ \
  424. vm->_error("OverflowError", std::to_string(val) + " is out of range"); \
  425. } \
  426. val = (val << 2) | 0b01; \
  427. return reinterpret_cast<PyObject*>(val); \
  428. }
  429. PY_VAR_INT(char)
  430. PY_VAR_INT(short)
  431. PY_VAR_INT(int)
  432. PY_VAR_INT(long)
  433. PY_VAR_INT(long long)
  434. PY_VAR_INT(unsigned char)
  435. PY_VAR_INT(unsigned short)
  436. PY_VAR_INT(unsigned int)
  437. PY_VAR_INT(unsigned long)
  438. PY_VAR_INT(unsigned long long)
  439. #define PY_VAR_FLOAT(T) \
  440. inline PyObject* py_var(VM* vm, T _val){ \
  441. f64 val = static_cast<f64>(_val); \
  442. i64 bits = BitsCvt(val)._int; \
  443. bits = (bits >> 2) << 2; \
  444. bits |= 0b10; \
  445. return reinterpret_cast<PyObject*>(bits); \
  446. }
  447. PY_VAR_FLOAT(float)
  448. PY_VAR_FLOAT(double)
  449. inline PyObject* py_var(VM* vm, bool val){
  450. return val ? vm->True : vm->False;
  451. }
  452. template<> inline bool py_cast<bool>(VM* vm, PyObject* obj){
  453. vm->check_non_tagged_type(obj, vm->tp_bool);
  454. return obj == vm->True;
  455. }
  456. template<> inline bool _py_cast<bool>(VM* vm, PyObject* obj){
  457. return obj == vm->True;
  458. }
  459. inline PyObject* py_var(VM* vm, const char val[]){
  460. return VAR(Str(val));
  461. }
  462. inline PyObject* py_var(VM* vm, std::string val){
  463. return VAR(Str(std::move(val)));
  464. }
  465. inline PyObject* py_var(VM* vm, std::string_view val){
  466. return VAR(Str(val));
  467. }
  468. template<typename T>
  469. void _check_py_class(VM* vm, PyObject* obj){
  470. vm->check_non_tagged_type(obj, T::_type(vm));
  471. }
  472. inline PyObject* VM::num_negated(PyObject* obj){
  473. if (is_int(obj)){
  474. return VAR(-CAST(i64, obj));
  475. }else if(is_float(obj)){
  476. return VAR(-CAST(f64, obj));
  477. }
  478. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape());
  479. return nullptr;
  480. }
  481. inline f64 VM::num_to_float(PyObject* obj){
  482. if(is_float(obj)){
  483. return CAST(f64, obj);
  484. } else if (is_int(obj)){
  485. return (f64)CAST(i64, obj);
  486. }
  487. TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape());
  488. return 0;
  489. }
  490. inline bool VM::asBool(PyObject* obj){
  491. if(is_non_tagged_type(obj, tp_bool)) return obj == True;
  492. if(obj == None) return false;
  493. if(is_int(obj)) return CAST(i64, obj) != 0;
  494. if(is_float(obj)) return CAST(f64, obj) != 0.0;
  495. PyObject* self;
  496. PyObject* len_f = get_unbound_method(obj, __len__, &self, false);
  497. if(self != PY_NULL){
  498. PyObject* ret = call_method(self, len_f);
  499. return CAST(i64, ret) > 0;
  500. }
  501. return true;
  502. }
  503. inline PyObject* VM::asList(PyObject* it){
  504. it = asIter(it);
  505. List list;
  506. PyObject* obj = PyIterNext(it);
  507. while(obj != StopIteration){
  508. list.push_back(obj);
  509. obj = PyIterNext(it);
  510. }
  511. return VAR(std::move(list));
  512. }
  513. inline void VM::parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step){
  514. auto clip = [](int value, int min, int max){
  515. if(value < min) return min;
  516. if(value > max) return max;
  517. return value;
  518. };
  519. if(s.step == None) step = 1;
  520. else step = CAST(int, s.step);
  521. if(step == 0) ValueError("slice step cannot be zero");
  522. if(step > 0){
  523. if(s.start == None){
  524. start = 0;
  525. }else{
  526. start = CAST(int, s.start);
  527. if(start < 0) start += length;
  528. start = clip(start, 0, length);
  529. }
  530. if(s.stop == None){
  531. stop = length;
  532. }else{
  533. stop = CAST(int, s.stop);
  534. if(stop < 0) stop += length;
  535. stop = clip(stop, 0, length);
  536. }
  537. }else{
  538. if(s.start == None){
  539. start = length - 1;
  540. }else{
  541. start = CAST(int, s.start);
  542. if(start < 0) start += length;
  543. start = clip(start, -1, length - 1);
  544. }
  545. if(s.stop == None){
  546. stop = -1;
  547. }else{
  548. stop = CAST(int, s.stop);
  549. if(stop < 0) stop += length;
  550. stop = clip(stop, -1, length - 1);
  551. }
  552. }
  553. }
  554. inline i64 VM::hash(PyObject* obj){
  555. if (is_non_tagged_type(obj, tp_str)) return CAST(Str&, obj).hash();
  556. if (is_int(obj)) return CAST(i64, obj);
  557. if (is_non_tagged_type(obj, tp_tuple)) {
  558. i64 x = 1000003;
  559. const Tuple& items = CAST(Tuple&, obj);
  560. for (int i=0; i<items.size(); i++) {
  561. i64 y = hash(items[i]);
  562. // recommended by Github Copilot
  563. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2));
  564. }
  565. return x;
  566. }
  567. if (is_non_tagged_type(obj, tp_type)) return BITS(obj);
  568. if (is_non_tagged_type(obj, tp_iterator)) return BITS(obj);
  569. if (is_non_tagged_type(obj, tp_bool)) return _CAST(bool, obj) ? 1 : 0;
  570. if (is_float(obj)){
  571. f64 val = CAST(f64, obj);
  572. return (i64)std::hash<f64>()(val);
  573. }
  574. TypeError("unhashable type: " + OBJ_NAME(_t(obj)).escape());
  575. return 0;
  576. }
  577. inline PyObject* VM::asRepr(PyObject* obj){
  578. return call_method(obj, __repr__);
  579. }
  580. inline PyObject* VM::format(Str spec, PyObject* obj){
  581. if(spec.empty()) return asStr(obj);
  582. char type;
  583. switch(spec.end()[-1]){
  584. case 'f': case 'd': case 's':
  585. type = spec.end()[-1];
  586. spec = spec.substr(0, spec.length() - 1);
  587. break;
  588. default: type = ' '; break;
  589. }
  590. char pad_c = ' ';
  591. if(spec[0] == '0'){
  592. pad_c = '0';
  593. spec = spec.substr(1);
  594. }
  595. char align;
  596. if(spec[0] == '>'){
  597. align = '>';
  598. spec = spec.substr(1);
  599. }else if(spec[0] == '<'){
  600. align = '<';
  601. spec = spec.substr(1);
  602. }else{
  603. if(is_int(obj) || is_float(obj)) align = '>';
  604. else align = '<';
  605. }
  606. int dot = spec.index(".");
  607. int width, precision;
  608. try{
  609. if(dot >= 0){
  610. width = Number::stoi(spec.substr(0, dot).str());
  611. precision = Number::stoi(spec.substr(dot+1).str());
  612. }else{
  613. width = Number::stoi(spec.str());
  614. precision = -1;
  615. }
  616. }catch(...){
  617. ValueError("invalid format specifer");
  618. }
  619. if(type != 'f' && dot >= 0) ValueError("precision not allowed in the format specifier");
  620. Str ret;
  621. if(type == 'f'){
  622. f64 val = num_to_float(obj);
  623. if(precision < 0) precision = 6;
  624. std::stringstream ss;
  625. ss << std::fixed << std::setprecision(precision) << val;
  626. ret = ss.str();
  627. }else if(type == 'd'){
  628. ret = std::to_string(CAST(i64, obj));
  629. }else if(type == 's'){
  630. ret = CAST(Str&, obj);
  631. }else{
  632. ret = CAST(Str&, asStr(obj));
  633. }
  634. if(width > ret.length()){
  635. int pad = width - ret.length();
  636. std::string padding(pad, pad_c);
  637. if(align == '>') ret = padding.c_str() + ret;
  638. else ret = ret + padding.c_str();
  639. }
  640. return VAR(ret);
  641. }
  642. inline PyObject* VM::new_module(StrName name) {
  643. PyObject* obj = heap._new<DummyModule>(tp_module, DummyModule());
  644. obj->attr().set(__name__, VAR(name.sv()));
  645. // we do not allow override in order to avoid memory leak
  646. // it is because Module objects are not garbage collected
  647. if(_modules.contains(name)) FATAL_ERROR();
  648. _modules.set(name, obj);
  649. return obj;
  650. }
  651. inline std::string _opcode_argstr(VM* vm, Bytecode byte, const CodeObject* co){
  652. std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
  653. switch(byte.op){
  654. case OP_LOAD_CONST:
  655. if(vm != nullptr){
  656. argStr += fmt(" (", CAST(Str, vm->asRepr(co->consts[byte.arg])), ")");
  657. }
  658. break;
  659. case OP_LOAD_NAME: case OP_LOAD_GLOBAL: case OP_LOAD_NONLOCAL: case OP_STORE_GLOBAL:
  660. case OP_LOAD_ATTR: case OP_LOAD_METHOD: case OP_STORE_ATTR: case OP_DELETE_ATTR:
  661. case OP_IMPORT_NAME: case OP_BEGIN_CLASS:
  662. case OP_DELETE_GLOBAL:
  663. argStr += fmt(" (", StrName(byte.arg).sv(), ")");
  664. break;
  665. case OP_LOAD_FAST: case OP_STORE_FAST: case OP_DELETE_FAST:
  666. argStr += fmt(" (", co->varnames[byte.arg].sv(), ")");
  667. break;
  668. case OP_BINARY_OP:
  669. argStr += fmt(" (", BINARY_SPECIAL_METHODS[byte.arg], ")");
  670. break;
  671. case OP_LOAD_FUNCTION:
  672. argStr += fmt(" (", co->func_decls[byte.arg]->code->name, ")");
  673. break;
  674. }
  675. return argStr;
  676. }
  677. inline Str VM::disassemble(CodeObject_ co){
  678. auto pad = [](const Str& s, const int n){
  679. if(s.length() >= n) return s.substr(0, n);
  680. return s + std::string(n - s.length(), ' ');
  681. };
  682. std::vector<int> jumpTargets;
  683. for(auto byte : co->codes){
  684. if(byte.op == OP_JUMP_ABSOLUTE || byte.op == OP_POP_JUMP_IF_FALSE){
  685. jumpTargets.push_back(byte.arg);
  686. }
  687. }
  688. std::stringstream ss;
  689. int prev_line = -1;
  690. for(int i=0; i<co->codes.size(); i++){
  691. const Bytecode& byte = co->codes[i];
  692. Str line = std::to_string(co->lines[i]);
  693. if(co->lines[i] == prev_line) line = "";
  694. else{
  695. if(prev_line != -1) ss << "\n";
  696. prev_line = co->lines[i];
  697. }
  698. std::string pointer;
  699. if(std::find(jumpTargets.begin(), jumpTargets.end(), i) != jumpTargets.end()){
  700. pointer = "-> ";
  701. }else{
  702. pointer = " ";
  703. }
  704. ss << pad(line, 8) << pointer << pad(std::to_string(i), 3);
  705. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  706. // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
  707. std::string argStr = _opcode_argstr(this, byte, co.get());
  708. ss << pad(argStr, 40); // may overflow
  709. ss << co->blocks[byte.block].type;
  710. if(i != co->codes.size() - 1) ss << '\n';
  711. }
  712. for(auto& decl: co->func_decls){
  713. ss << "\n\n" << "Disassembly of " << decl->code->name << ":\n";
  714. ss << disassemble(decl->code);
  715. }
  716. ss << "\n";
  717. return Str(ss.str());
  718. }
  719. inline void VM::_log_s_data(const char* title) {
  720. if(!_initialized) return;
  721. if(callstack.empty()) return;
  722. std::stringstream ss;
  723. if(title) ss << title << " | ";
  724. std::map<PyObject**, int> sp_bases;
  725. for(Frame& f: callstack.data()){
  726. if(f._sp_base == nullptr) FATAL_ERROR();
  727. sp_bases[f._sp_base] += 1;
  728. }
  729. FrameId frame = top_frame();
  730. int line = frame->co->lines[frame->_ip];
  731. ss << frame->co->name << ":" << line << " [";
  732. for(PyObject** p=s_data.begin(); p!=s_data.end(); p++){
  733. ss << std::string(sp_bases[p], '|');
  734. if(sp_bases[p] > 0) ss << " ";
  735. PyObject* obj = *p;
  736. if(obj == nullptr) ss << "(nil)";
  737. else if(obj == PY_BEGIN_CALL) ss << "BEGIN_CALL";
  738. else if(obj == PY_NULL) ss << "NULL";
  739. else if(is_int(obj)) ss << CAST(i64, obj);
  740. else if(is_float(obj)) ss << CAST(f64, obj);
  741. else if(is_type(obj, tp_str)) ss << CAST(Str, obj).escape();
  742. else if(obj == None) ss << "None";
  743. else if(obj == True) ss << "True";
  744. else if(obj == False) ss << "False";
  745. else if(is_type(obj, tp_function)){
  746. auto& f = CAST(Function&, obj);
  747. ss << f.decl->code->name << "(...)";
  748. } else if(is_type(obj, tp_type)){
  749. Type t = OBJ_GET(Type, obj);
  750. ss << "<class " + _all_types[t].name.escape() + ">";
  751. } else if(is_type(obj, tp_list)){
  752. auto& t = CAST(List&, obj);
  753. ss << "list(size=" << t.size() << ")";
  754. } else if(is_type(obj, tp_tuple)){
  755. auto& t = CAST(Tuple&, obj);
  756. ss << "tuple(size=" << t.size() << ")";
  757. } else ss << "(" << obj_type_name(this, obj->type) << ")";
  758. ss << ", ";
  759. }
  760. std::string output = ss.str();
  761. if(!s_data.empty()) {
  762. output.pop_back(); output.pop_back();
  763. }
  764. output.push_back(']');
  765. Bytecode byte = frame->co->codes[frame->_ip];
  766. std::cout << output << " " << OP_NAMES[byte.op] << " " << _opcode_argstr(nullptr, byte, frame->co) << std::endl;
  767. }
  768. inline void VM::init_builtin_types(){
  769. _all_types.push_back({heap._new<Type>(Type(1), Type(0)), -1, "object", true});
  770. _all_types.push_back({heap._new<Type>(Type(1), Type(1)), 0, "type", false});
  771. tp_object = 0; tp_type = 1;
  772. tp_int = _new_type_object("int");
  773. tp_float = _new_type_object("float");
  774. if(tp_int.index != kTpIntIndex || tp_float.index != kTpFloatIndex) FATAL_ERROR();
  775. tp_bool = _new_type_object("bool");
  776. tp_str = _new_type_object("str");
  777. tp_list = _new_type_object("list");
  778. tp_tuple = _new_type_object("tuple");
  779. tp_slice = _new_type_object("slice");
  780. tp_range = _new_type_object("range");
  781. tp_module = _new_type_object("module");
  782. tp_function = _new_type_object("function");
  783. tp_native_func = _new_type_object("native_func");
  784. tp_iterator = _new_type_object("iterator");
  785. tp_bound_method = _new_type_object("bound_method");
  786. tp_super = _new_type_object("super");
  787. tp_exception = _new_type_object("Exception");
  788. tp_bytes = _new_type_object("bytes");
  789. tp_mappingproxy = _new_type_object("mappingproxy");
  790. this->None = heap._new<Dummy>(_new_type_object("NoneType"), {});
  791. this->Ellipsis = heap._new<Dummy>(_new_type_object("ellipsis"), {});
  792. this->True = heap._new<Dummy>(tp_bool, {});
  793. this->False = heap._new<Dummy>(tp_bool, {});
  794. this->StopIteration = heap._new<Dummy>(_new_type_object("StopIterationType"), {});
  795. this->builtins = new_module("builtins");
  796. this->_main = new_module("__main__");
  797. // setup public types
  798. builtins->attr().set("type", _t(tp_type));
  799. builtins->attr().set("object", _t(tp_object));
  800. builtins->attr().set("bool", _t(tp_bool));
  801. builtins->attr().set("int", _t(tp_int));
  802. builtins->attr().set("float", _t(tp_float));
  803. builtins->attr().set("str", _t(tp_str));
  804. builtins->attr().set("list", _t(tp_list));
  805. builtins->attr().set("tuple", _t(tp_tuple));
  806. builtins->attr().set("range", _t(tp_range));
  807. builtins->attr().set("bytes", _t(tp_bytes));
  808. builtins->attr().set("StopIteration", StopIteration);
  809. builtins->attr().set("slice", _t(tp_slice));
  810. post_init();
  811. for(int i=0; i<_all_types.size(); i++){
  812. _all_types[i].obj->attr()._try_perfect_rehash();
  813. }
  814. for(auto [k, v]: _modules.items()) v->attr()._try_perfect_rehash();
  815. }
  816. inline PyObject* VM::vectorcall(int ARGC, int KWARGC, bool op_call){
  817. bool is_varargs = ARGC == 0xFFFF;
  818. PyObject** p0;
  819. PyObject** p1 = s_data._sp - KWARGC*2;
  820. if(is_varargs){
  821. p0 = p1 - 1;
  822. while(*p0 != PY_BEGIN_CALL) p0--;
  823. // [BEGIN_CALL, callable, <self>, args..., kwargs...]
  824. // ^p0 ^p1 ^_sp
  825. ARGC = p1 - (p0 + 3);
  826. }else{
  827. p0 = p1 - ARGC - 2 - (int)is_varargs;
  828. // [callable, <self>, args..., kwargs...]
  829. // ^p0 ^p1 ^_sp
  830. }
  831. PyObject* callable = p1[-(ARGC + 2)];
  832. bool method_call = p1[-(ARGC + 1)] != PY_NULL;
  833. // handle boundmethod, do a patch
  834. if(is_non_tagged_type(callable, tp_bound_method)){
  835. if(method_call) FATAL_ERROR();
  836. auto& bm = CAST(BoundMethod&, callable);
  837. callable = bm.func; // get unbound method
  838. p1[-(ARGC + 2)] = bm.func;
  839. p1[-(ARGC + 1)] = bm.self;
  840. method_call = true;
  841. // [unbound, self, args..., kwargs...]
  842. }
  843. ArgsView args(p1 - ARGC - int(method_call), p1);
  844. if(is_non_tagged_type(callable, tp_native_func)){
  845. const auto& f = OBJ_GET(NativeFunc, callable);
  846. if(KWARGC != 0) TypeError("native_func does not accept keyword arguments");
  847. PyObject* ret = f(this, args);
  848. s_data.reset(p0);
  849. return ret;
  850. }
  851. ArgsView kwargs(p1, s_data._sp);
  852. if(is_non_tagged_type(callable, tp_function)){
  853. // ret is nullptr or a generator
  854. PyObject* ret = _py_call(p0, callable, args, kwargs);
  855. // stack resetting is handled by _py_call
  856. if(ret != nullptr) return ret;
  857. if(op_call) return PY_OP_CALL;
  858. return _run_top_frame();
  859. }
  860. if(is_non_tagged_type(callable, tp_type)){
  861. if(method_call) FATAL_ERROR();
  862. // [type, NULL, args..., kwargs...]
  863. // __new__
  864. const static StrName m_new("__new__");
  865. PyObject* new_f = find_name_in_mro(callable, m_new);
  866. PyObject* obj;
  867. if(new_f != nullptr){
  868. PUSH(new_f);
  869. PUSH(PY_NULL);
  870. PUSH(callable); // cls
  871. for(PyObject* obj: args) PUSH(obj);
  872. for(PyObject* obj: kwargs) PUSH(obj);
  873. // if obj is not an instance of callable, the behavior is undefined
  874. obj = vectorcall(ARGC+1, KWARGC);
  875. }else{
  876. // fast path for object.__new__
  877. Type t = OBJ_GET(Type, callable);
  878. obj= vm->heap.gcnew<DummyInstance>(t, {});
  879. }
  880. // __init__
  881. PyObject* self;
  882. callable = get_unbound_method(obj, __init__, &self, false);
  883. if (self != PY_NULL) {
  884. // replace `NULL` with `self`
  885. p1[-(ARGC + 2)] = callable;
  886. p1[-(ARGC + 1)] = self;
  887. // [init_f, self, args..., kwargs...]
  888. vectorcall(ARGC, KWARGC);
  889. // We just discard the return value of `__init__`
  890. // in cpython it raises a TypeError if the return value is not None
  891. }else{
  892. // manually reset the stack
  893. s_data.reset(p0);
  894. }
  895. return obj;
  896. }
  897. // handle `__call__` overload
  898. PyObject* self;
  899. PyObject* call_f = get_unbound_method(callable, __call__, &self, false);
  900. if(self != PY_NULL){
  901. p1[-(ARGC + 2)] = call_f;
  902. p1[-(ARGC + 1)] = self;
  903. // [call_f, self, args..., kwargs...]
  904. return vectorcall(ARGC, KWARGC, false);
  905. }
  906. TypeError(OBJ_NAME(_t(callable)).escape() + " object is not callable");
  907. return nullptr;
  908. }
  909. inline PyObject* VM::_py_call(PyObject** p0, PyObject* callable, ArgsView args, ArgsView kwargs){
  910. // callable must be a `function` object
  911. if(s_data.is_overflow()) StackOverflowError();
  912. const Function& fn = CAST(Function&, callable);
  913. const CodeObject* co = fn.decl->code.get();
  914. if(args.size() < fn.argc){
  915. vm->TypeError(fmt(
  916. "expected ",
  917. fn.argc,
  918. " positional arguments, but got ",
  919. args.size(),
  920. " (", fn.decl->code->name, ')'
  921. ));
  922. }
  923. // if this function is simple, a.k.a, no kwargs and no *args and not a generator
  924. // we can use a fast path to avoid using buffer copy
  925. if(fn.is_simple){
  926. if(args.size() > fn.argc) TypeError("too many positional arguments");
  927. int spaces = co->varnames.size() - fn.argc;
  928. for(int j=0; j<spaces; j++) PUSH(nullptr);
  929. callstack.emplace(&s_data, p0, co, fn._module, callable, FastLocals(co, args.begin()));
  930. return nullptr;
  931. }
  932. int i = 0;
  933. static THREAD_LOCAL PyObject* buffer[PK_MAX_CO_VARNAMES];
  934. // prepare args
  935. for(int index: fn.decl->args) buffer[index] = args[i++];
  936. // set extra varnames to nullptr
  937. for(int j=i; j<co->varnames.size(); j++) buffer[j] = nullptr;
  938. // prepare kwdefaults
  939. for(auto& kv: fn.decl->kwargs) buffer[kv.key] = kv.value;
  940. // handle *args
  941. if(fn.decl->starred_arg != -1){
  942. List vargs; // handle *args
  943. while(i < args.size()) vargs.push_back(args[i++]);
  944. buffer[fn.decl->starred_arg] = VAR(Tuple(std::move(vargs)));
  945. }else{
  946. // kwdefaults override
  947. for(auto& kv: fn.decl->kwargs){
  948. if(i < args.size()){
  949. buffer[kv.key] = args[i++];
  950. }else{
  951. break;
  952. }
  953. }
  954. if(i < args.size()) TypeError(fmt("too many arguments", " (", fn.decl->code->name, ')'));
  955. }
  956. for(int i=0; i<kwargs.size(); i+=2){
  957. StrName key = CAST(int, kwargs[i]);
  958. int index = co->varnames_inv.try_get(key);
  959. if(index<0) TypeError(fmt(key.escape(), " is an invalid keyword argument for ", co->name, "()"));
  960. buffer[index] = kwargs[i+1];
  961. }
  962. s_data.reset(p0);
  963. if(co->is_generator){
  964. PyObject* ret = PyIter(Generator(
  965. this,
  966. Frame(&s_data, nullptr, co, fn._module, callable),
  967. ArgsView(buffer, buffer + co->varnames.size())
  968. ));
  969. return ret;
  970. }
  971. // copy buffer to stack
  972. for(int i=0; i<co->varnames.size(); i++) PUSH(buffer[i]);
  973. callstack.emplace(&s_data, p0, co, fn._module, callable);
  974. return nullptr;
  975. }
  976. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  977. inline PyObject* VM::getattr(PyObject* obj, StrName name, bool throw_err){
  978. PyObject* objtype = _t(obj);
  979. // handle super() proxy
  980. if(is_non_tagged_type(obj, tp_super)){
  981. const Super& super = OBJ_GET(Super, obj);
  982. obj = super.first;
  983. objtype = _t(super.second);
  984. }
  985. PyObject* cls_var = find_name_in_mro(objtype, name);
  986. if(cls_var != nullptr){
  987. // handle descriptor
  988. PyObject* descr_get = _t(cls_var)->attr().try_get(__get__);
  989. if(descr_get != nullptr) return call_method(cls_var, descr_get, obj);
  990. }
  991. // handle instance __dict__
  992. if(!is_tagged(obj) && obj->is_attr_valid()){
  993. PyObject* val = obj->attr().try_get(name);
  994. if(val != nullptr) return val;
  995. }
  996. if(cls_var != nullptr){
  997. // bound method is non-data descriptor
  998. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  999. return VAR(BoundMethod(obj, cls_var));
  1000. }
  1001. return cls_var;
  1002. }
  1003. if(throw_err) AttributeError(obj, name);
  1004. return nullptr;
  1005. }
  1006. // used by OP_LOAD_METHOD
  1007. // try to load a unbound method (fallback to `getattr` if not found)
  1008. inline PyObject* VM::get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err, bool fallback){
  1009. *self = PY_NULL;
  1010. PyObject* objtype = _t(obj);
  1011. // handle super() proxy
  1012. if(is_non_tagged_type(obj, tp_super)){
  1013. const Super& super = OBJ_GET(Super, obj);
  1014. obj = super.first;
  1015. objtype = _t(super.second);
  1016. }
  1017. PyObject* cls_var = find_name_in_mro(objtype, name);
  1018. if(fallback){
  1019. if(cls_var != nullptr){
  1020. // handle descriptor
  1021. PyObject* descr_get = _t(cls_var)->attr().try_get(__get__);
  1022. if(descr_get != nullptr) return call_method(cls_var, descr_get, obj);
  1023. }
  1024. // handle instance __dict__
  1025. if(!is_tagged(obj) && obj->is_attr_valid()){
  1026. PyObject* val = obj->attr().try_get(name);
  1027. if(val != nullptr) return val;
  1028. }
  1029. }
  1030. if(cls_var != nullptr){
  1031. if(is_non_tagged_type(cls_var, tp_function) || is_non_tagged_type(cls_var, tp_native_func)){
  1032. *self = obj;
  1033. }
  1034. return cls_var;
  1035. }
  1036. if(throw_err) AttributeError(obj, name);
  1037. return nullptr;
  1038. }
  1039. inline void VM::setattr(PyObject* obj, StrName name, PyObject* value){
  1040. PyObject* objtype = _t(obj);
  1041. // handle super() proxy
  1042. if(is_non_tagged_type(obj, tp_super)){
  1043. Super& super = OBJ_GET(Super, obj);
  1044. obj = super.first;
  1045. objtype = _t(super.second);
  1046. }
  1047. PyObject* cls_var = find_name_in_mro(objtype, name);
  1048. if(cls_var != nullptr){
  1049. // handle descriptor
  1050. PyObject* cls_var_t = _t(cls_var);
  1051. if(cls_var_t->attr().contains(__get__)){
  1052. PyObject* descr_set = cls_var_t->attr().try_get(__set__);
  1053. if(descr_set != nullptr){
  1054. call_method(cls_var, descr_set, obj, value);
  1055. }else{
  1056. TypeError(fmt("readonly attribute: ", name.escape()));
  1057. }
  1058. return;
  1059. }
  1060. }
  1061. // handle instance __dict__
  1062. if(is_tagged(obj) || !obj->is_attr_valid()) TypeError("cannot set attribute");
  1063. obj->attr().set(name, value);
  1064. }
  1065. template<int ARGC>
  1066. void VM::bind_method(PyObject* obj, Str name, NativeFuncC fn) {
  1067. check_non_tagged_type(obj, tp_type);
  1068. obj->attr().set(name, VAR(NativeFunc(fn, ARGC, true)));
  1069. }
  1070. template<int ARGC>
  1071. void VM::bind_func(PyObject* obj, Str name, NativeFuncC fn) {
  1072. obj->attr().set(name, VAR(NativeFunc(fn, ARGC, false)));
  1073. }
  1074. inline void VM::_error(Exception e){
  1075. if(callstack.empty()){
  1076. e.is_re = false;
  1077. throw e;
  1078. }
  1079. PUSH(VAR(e));
  1080. _raise();
  1081. }
  1082. inline void ManagedHeap::mark() {
  1083. for(PyObject* obj: _no_gc) OBJ_MARK(obj);
  1084. for(auto& frame : vm->callstack.data()) frame._gc_mark();
  1085. for(PyObject* obj: vm->s_data) if(obj!=nullptr) OBJ_MARK(obj);
  1086. if(vm->_gc_marker_ex != nullptr) vm->_gc_marker_ex(vm);
  1087. }
  1088. inline Str obj_type_name(VM *vm, Type type){
  1089. return vm->_all_types[type].name;
  1090. }
  1091. #undef PY_VAR_INT
  1092. #undef PY_VAR_FLOAT
  1093. } // namespace pkpy