vm.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. #include "dict.h"
  12. #include "profiler.h"
  13. namespace pkpy{
  14. /* Stack manipulation macros */
  15. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  16. #define TOP() (s_data.top())
  17. #define SECOND() (s_data.second())
  18. #define THIRD() (s_data.third())
  19. #define STACK_SHRINK(n) (s_data.shrink(n))
  20. #define PUSH(v) (s_data.push(v))
  21. #define POP() (s_data.pop())
  22. #define POPX() (s_data.popx())
  23. #define STACK_VIEW(n) (s_data.view(n))
  24. typedef PyObject* (*BinaryFuncC)(VM*, PyObject*, PyObject*);
  25. typedef void (*RegisterFunc)(VM*, PyObject*, PyObject*);
  26. #if PK_ENABLE_PROFILER
  27. struct NextBreakpoint{
  28. int callstack_size;
  29. int lineno;
  30. bool should_step_into;
  31. NextBreakpoint(): callstack_size(0) {}
  32. NextBreakpoint(int callstack_size, int lineno, bool should_step_into): callstack_size(callstack_size), lineno(lineno), should_step_into(should_step_into) {}
  33. void _step(VM* vm);
  34. bool empty() const { return callstack_size == 0; }
  35. };
  36. #endif
  37. struct PyTypeInfo{
  38. PyObject* obj; // never be garbage collected
  39. Type base;
  40. PyObject* mod; // never be garbage collected
  41. StrName name;
  42. bool subclass_enabled;
  43. std::vector<StrName> annotated_fields = {};
  44. // cached special methods
  45. // unary operators
  46. PyObject* (*m__repr__)(VM* vm, PyObject*) = nullptr;
  47. PyObject* (*m__str__)(VM* vm, PyObject*) = nullptr;
  48. i64 (*m__hash__)(VM* vm, PyObject*) = nullptr;
  49. i64 (*m__len__)(VM* vm, PyObject*) = nullptr;
  50. PyObject* (*m__iter__)(VM* vm, PyObject*) = nullptr;
  51. unsigned (*m__next__)(VM* vm, PyObject*) = nullptr;
  52. PyObject* (*m__neg__)(VM* vm, PyObject*) = nullptr;
  53. PyObject* (*m__invert__)(VM* vm, PyObject*) = nullptr;
  54. BinaryFuncC m__eq__ = nullptr;
  55. BinaryFuncC m__lt__ = nullptr;
  56. BinaryFuncC m__le__ = nullptr;
  57. BinaryFuncC m__gt__ = nullptr;
  58. BinaryFuncC m__ge__ = nullptr;
  59. BinaryFuncC m__contains__ = nullptr;
  60. // binary operators
  61. BinaryFuncC m__add__ = nullptr;
  62. BinaryFuncC m__sub__ = nullptr;
  63. BinaryFuncC m__mul__ = nullptr;
  64. BinaryFuncC m__truediv__ = nullptr;
  65. BinaryFuncC m__floordiv__ = nullptr;
  66. BinaryFuncC m__mod__ = nullptr;
  67. BinaryFuncC m__pow__ = nullptr;
  68. BinaryFuncC m__matmul__ = nullptr;
  69. BinaryFuncC m__lshift__ = nullptr;
  70. BinaryFuncC m__rshift__ = nullptr;
  71. BinaryFuncC m__and__ = nullptr;
  72. BinaryFuncC m__or__ = nullptr;
  73. BinaryFuncC m__xor__ = nullptr;
  74. // indexer
  75. PyObject* (*m__getitem__)(VM* vm, PyObject*, PyObject*) = nullptr;
  76. void (*m__setitem__)(VM* vm, PyObject*, PyObject*, PyObject*) = nullptr;
  77. void (*m__delitem__)(VM* vm, PyObject*, PyObject*) = nullptr;
  78. // attributes
  79. void (*m__setattr__)(VM* vm, PyObject*, StrName, PyObject*) = nullptr;
  80. PyObject* (*m__getattr__)(VM* vm, PyObject*, StrName) = nullptr;
  81. bool (*m__delattr__)(VM* vm, PyObject*, StrName) = nullptr;
  82. // backdoors
  83. void (*on_end_subclass)(VM* vm, PyTypeInfo*) = nullptr;
  84. };
  85. struct ImportContext{
  86. PK_ALWAYS_PASS_BY_POINTER(ImportContext)
  87. std::vector<Str> pending;
  88. std::vector<bool> pending_is_init; // a.k.a __init__.py
  89. ImportContext() {}
  90. struct Temp{
  91. PK_ALWAYS_PASS_BY_POINTER(Temp)
  92. ImportContext* ctx;
  93. Temp(ImportContext* ctx, Str name, bool is_init) : ctx(ctx){
  94. ctx->pending.push_back(name);
  95. ctx->pending_is_init.push_back(is_init);
  96. }
  97. ~Temp(){
  98. ctx->pending.pop_back();
  99. ctx->pending_is_init.pop_back();
  100. }
  101. };
  102. Temp scope(Str name, bool is_init){
  103. return {this, name, is_init};
  104. }
  105. };
  106. class VM {
  107. PK_ALWAYS_PASS_BY_POINTER(VM)
  108. VM* vm; // self reference for simplify code
  109. public:
  110. ManagedHeap heap;
  111. ValueStack s_data;
  112. CallStack callstack;
  113. std::vector<PyTypeInfo> _all_types;
  114. NameDict _modules; // loaded modules
  115. std::map<StrName, Str> _lazy_modules; // lazy loaded modules
  116. struct{
  117. PyObject* error;
  118. stack_no_copy<ArgsView> s_view;
  119. } _c;
  120. PyObject *None, *True, *False, *NotImplemented;
  121. PyObject *StopIteration, *Ellipsis;
  122. PyObject *builtins, *_main;
  123. // typeid -> Type
  124. std::map<const std::type_index, Type> _cxx_typeid_map;
  125. // this is for repr() recursion detection (no need to mark)
  126. std::set<PyObject*> _repr_recursion_set;
  127. ImportContext __import_context; // for import
  128. PyObject* __last_exception; // last exception
  129. PyObject* __curr_class; // current class being defined
  130. PyObject* __cached_object_new;
  131. std::map<std::string_view, CodeObject_> __cached_codes;
  132. void (*_ceval_on_step)(VM*, Frame*, Bytecode bc) = nullptr;
  133. #if PK_ENABLE_PROFILER
  134. LineProfiler* _profiler = nullptr;
  135. NextBreakpoint _next_breakpoint;
  136. #endif
  137. void(*_stdout)(const char*, int);
  138. void(*_stderr)(const char*, int);
  139. unsigned char* (*_import_handler)(const char*, int*);
  140. // for quick access
  141. static constexpr Type tp_object=Type(0), tp_type=Type(1);
  142. static constexpr Type tp_int=Type(kTpIntIndex), tp_float=Type(kTpFloatIndex), tp_bool=Type(4), tp_str=Type(5);
  143. static constexpr Type tp_list=Type(6), tp_tuple=Type(7);
  144. static constexpr Type tp_slice=Type(8), tp_range=Type(9), tp_module=Type(10);
  145. static constexpr Type tp_function=Type(11), tp_native_func=Type(12), tp_bound_method=Type(13);
  146. static constexpr Type tp_super=Type(14), tp_exception=Type(15), tp_bytes=Type(16), tp_mappingproxy=Type(17);
  147. static constexpr Type tp_dict=Type(18), tp_property=Type(19), tp_star_wrapper=Type(20);
  148. static constexpr Type tp_staticmethod=Type(21), tp_classmethod=Type(22);
  149. const bool enable_os;
  150. VM(bool enable_os=true);
  151. /********** py_xxx **********/
  152. PyObject* py_str(PyObject* obj);
  153. PyObject* py_repr(PyObject* obj);
  154. PyObject* py_json(PyObject* obj);
  155. PyObject* py_iter(PyObject* obj);
  156. PyObject* py_next(PyObject*);
  157. PyObject* _py_next(const PyTypeInfo*, PyObject*);
  158. PyObject* py_import(Str path, bool throw_err=true);
  159. PyObject* py_negate(PyObject* obj);
  160. PyObject* py_list(PyObject*);
  161. bool py_callable(PyObject* obj);
  162. bool py_bool(PyObject* obj);
  163. i64 py_hash(PyObject* obj);
  164. bool py_eq(PyObject* lhs, PyObject* rhs);
  165. // new in v1.2.9
  166. bool py_lt(PyObject* lhs, PyObject* rhs);
  167. bool py_le(PyObject* lhs, PyObject* rhs);
  168. bool py_gt(PyObject* lhs, PyObject* rhs);
  169. bool py_ge(PyObject* lhs, PyObject* rhs);
  170. bool py_ne(PyObject* lhs, PyObject* rhs) { return !py_eq(lhs, rhs); }
  171. /********** utils **********/
  172. PyObject* new_module(Str name, Str package="");
  173. ArgsView cast_array_view(PyObject* obj);
  174. void set_main_argv(int argc, char** argv);
  175. i64 normalized_index(i64 index, int size);
  176. Str disassemble(CodeObject_ co);
  177. void parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step);
  178. /********** name lookup **********/
  179. PyObject* find_name_in_mro(Type cls, StrName name);
  180. PyObject* getattr(PyObject* obj, StrName name, bool throw_err=true);
  181. void delattr(PyObject* obj, StrName name);
  182. PyObject* get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err=true, bool fallback=false);
  183. void setattr(PyObject* obj, StrName name, PyObject* value);
  184. /********** execution **********/
  185. CodeObject_ compile(std::string_view source, const Str& filename, CompileMode mode, bool unknown_global_scope=false);
  186. Str precompile(std::string_view source, const Str& filename, CompileMode mode);
  187. PyObject* exec(std::string_view source, Str filename, CompileMode mode, PyObject* _module=nullptr);
  188. PyObject* exec(std::string_view source);
  189. PyObject* eval(std::string_view source);
  190. template<typename ...Args>
  191. PyObject* _exec(Args&&... args){
  192. callstack.emplace(s_data._sp, std::forward<Args>(args)...);
  193. return __run_top_frame();
  194. }
  195. /********** invocation **********/
  196. PyObject* vectorcall(int ARGC, int KWARGC=0, bool op_call=false);
  197. template<typename... Args>
  198. PyObject* call(PyObject* callable, Args&&... args){
  199. PUSH(callable); PUSH(PY_NULL);
  200. __push_varargs(args...);
  201. return vectorcall(sizeof...(args));
  202. }
  203. template<typename... Args>
  204. PyObject* call_method(PyObject* self, PyObject* callable, Args&&... args){
  205. PUSH(callable); PUSH(self);
  206. __push_varargs(args...);
  207. return vectorcall(sizeof...(args));
  208. }
  209. template<typename... Args>
  210. PyObject* call_method(PyObject* self, StrName name, Args&&... args){
  211. PyObject* callable = get_unbound_method(self, name, &self);
  212. return call_method(self, callable, args...);
  213. }
  214. /********** io **********/
  215. virtual void stdout_write(const Str& s){ _stdout(s.data, s.size); }
  216. virtual void stderr_write(const Str& s){ _stderr(s.data, s.size); }
  217. /********** bindings **********/
  218. void bind__repr__(Type type, PyObject* (*f)(VM*, PyObject*));
  219. void bind__str__(Type type, PyObject* (*f)(VM*, PyObject*));
  220. void bind__iter__(Type type, PyObject* (*f)(VM*, PyObject*));
  221. void bind__next__(Type type, unsigned (*f)(VM*, PyObject*));
  222. [[deprecated]] void bind__next__(Type type, PyObject* (*f)(VM*, PyObject*));
  223. void bind__neg__(Type type, PyObject* (*f)(VM*, PyObject*));
  224. void bind__invert__(Type type, PyObject* (*f)(VM*, PyObject*));
  225. void bind__hash__(Type type, i64 (*f)(VM* vm, PyObject*));
  226. void bind__len__(Type type, i64 (*f)(VM* vm, PyObject*));
  227. void bind__eq__(Type type, BinaryFuncC f);
  228. void bind__lt__(Type type, BinaryFuncC f);
  229. void bind__le__(Type type, BinaryFuncC f);
  230. void bind__gt__(Type type, BinaryFuncC f);
  231. void bind__ge__(Type type, BinaryFuncC f);
  232. void bind__contains__(Type type, BinaryFuncC f);
  233. void bind__add__(Type type, BinaryFuncC f);
  234. void bind__sub__(Type type, BinaryFuncC f);
  235. void bind__mul__(Type type, BinaryFuncC f);
  236. void bind__truediv__(Type type, BinaryFuncC f);
  237. void bind__floordiv__(Type type, BinaryFuncC f);
  238. void bind__mod__(Type type, BinaryFuncC f);
  239. void bind__pow__(Type type, BinaryFuncC f);
  240. void bind__matmul__(Type type, BinaryFuncC f);
  241. void bind__lshift__(Type type, BinaryFuncC f);
  242. void bind__rshift__(Type type, BinaryFuncC f);
  243. void bind__and__(Type type, BinaryFuncC f);
  244. void bind__or__(Type type, BinaryFuncC f);
  245. void bind__xor__(Type type, BinaryFuncC f);
  246. void bind__getitem__(Type type, PyObject* (*f)(VM*, PyObject*, PyObject*));
  247. void bind__setitem__(Type type, void (*f)(VM*, PyObject*, PyObject*, PyObject*));
  248. void bind__delitem__(Type type, void (*f)(VM*, PyObject*, PyObject*));
  249. // new style binding api
  250. PyObject* bind_func(PyObject* obj, StrName name, int argc, NativeFuncC fn, UserData userdata={}, BindType bt=BindType::DEFAULT);
  251. PyObject* bind_func(Type type, StrName name, int argc, NativeFuncC fn, UserData userdata={}, BindType bt=BindType::DEFAULT){
  252. return bind_func(_t(type), name, argc, fn, userdata, bt);
  253. }
  254. PyObject* bind_property(PyObject*, const char*, NativeFuncC fget, NativeFuncC fset=nullptr);
  255. template<typename T, typename F, bool ReadOnly=false>
  256. PyObject* bind_field(PyObject*, const char*, F T::*);
  257. // without docstring
  258. PyObject* bind(PyObject*, const char*, NativeFuncC, UserData userdata={}, BindType bt=BindType::DEFAULT);
  259. template<typename Ret, typename... Params>
  260. PyObject* bind(PyObject*, const char*, Ret(*)(Params...), BindType bt=BindType::DEFAULT);
  261. template<typename Ret, typename T, typename... Params>
  262. PyObject* bind(PyObject*, const char*, Ret(T::*)(Params...), BindType bt=BindType::DEFAULT);
  263. // with docstring
  264. PyObject* bind(PyObject*, const char*, const char*, NativeFuncC, UserData userdata={}, BindType bt=BindType::DEFAULT);
  265. template<typename Ret, typename... Params>
  266. PyObject* bind(PyObject*, const char*, const char*, Ret(*)(Params...), BindType bt=BindType::DEFAULT);
  267. template<typename Ret, typename T, typename... Params>
  268. PyObject* bind(PyObject*, const char*, const char*, Ret(T::*)(Params...), BindType bt=BindType::DEFAULT);
  269. /********** error **********/
  270. void _error(PyObject*);
  271. void StackOverflowError() { __builtin_error("StackOverflowError"); }
  272. void IOError(const Str& msg) { __builtin_error("IOError", msg); }
  273. void NotImplementedError(){ __builtin_error("NotImplementedError"); }
  274. void TypeError(const Str& msg){ __builtin_error("TypeError", msg); }
  275. void TypeError(Type expected, Type actual) { TypeError("expected " + _type_name(vm, expected).escape() + ", got " + _type_name(vm, actual).escape()); }
  276. void IndexError(const Str& msg){ __builtin_error("IndexError", msg); }
  277. void ValueError(const Str& msg){ __builtin_error("ValueError", msg); }
  278. void RuntimeError(const Str& msg){ __builtin_error("RuntimeError", msg); }
  279. void ZeroDivisionError(const Str& msg){ __builtin_error("ZeroDivisionError", msg); }
  280. void ZeroDivisionError(){ __builtin_error("ZeroDivisionError", "division by zero"); }
  281. void NameError(StrName name){ __builtin_error("NameError", _S("name ", name.escape() + " is not defined")); }
  282. void UnboundLocalError(StrName name){ __builtin_error("UnboundLocalError", _S("local variable ", name.escape() + " referenced before assignment")); }
  283. void KeyError(PyObject* obj){ __builtin_error("KeyError", obj); }
  284. void ImportError(const Str& msg){ __builtin_error("ImportError", msg); }
  285. void AssertionError(const Str& msg){ __builtin_error("AssertionError", msg); }
  286. void AssertionError(){ __builtin_error("AssertionError"); }
  287. void BinaryOptError(const char* op, PyObject* _0, PyObject* _1);
  288. void AttributeError(PyObject* obj, StrName name);
  289. void AttributeError(const Str& msg){ __builtin_error("AttributeError", msg); }
  290. /********** type **********/
  291. PyObject* new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled=true);
  292. const PyTypeInfo* _inst_type_info(PyObject* obj);
  293. bool isinstance(PyObject* obj, Type base);
  294. bool issubclass(Type cls, Type base);
  295. void check_type(PyObject* obj, Type type){ if(!is_type(obj, type)) TypeError(type, _tp(obj)); }
  296. void check_compatible_type(PyObject* obj, Type type){ if(!isinstance(obj, type)) TypeError(type, _tp(obj)); }
  297. PyObject* _t(PyObject* obj){ return _all_types[_tp(obj)].obj; }
  298. PyObject* _t(Type t){ return _all_types[t.index].obj; }
  299. Type _tp(PyObject* obj){ return is_small_int(obj) ? tp_int : obj->type; }
  300. /********** user type **********/
  301. template<typename T>
  302. Type _tp_user(){ return _find_type_in_cxx_typeid_map<T>(); }
  303. template<typename T>
  304. bool is_user_type(PyObject* obj){ return _tp(obj) == _tp_user<T>(); }
  305. template<typename T>
  306. PyObject* register_user_class(PyObject*, StrName, RegisterFunc, Type base=tp_object, bool subclass_enabled=false);
  307. template<typename T>
  308. PyObject* register_user_class(PyObject*, StrName, Type base=tp_object, bool subclass_enabled=false);
  309. template<typename T, typename ...Args>
  310. PyObject* new_user_object(Args&&... args){
  311. return heap.gcnew<T>(_tp_user<T>(), std::forward<Args>(args)...);
  312. }
  313. template<typename T>
  314. Type _find_type_in_cxx_typeid_map(){
  315. auto it = _cxx_typeid_map.find(typeid(T));
  316. if(it == _cxx_typeid_map.end()){
  317. #if __GNUC__ || __clang__
  318. throw std::runtime_error(__PRETTY_FUNCTION__ + std::string(" failed: T not found"));
  319. #elif _MSC_VER
  320. throw std::runtime_error(__FUNCSIG__ + std::string(" failed: T not found"));
  321. #else
  322. throw std::runtime_error("_find_type_in_cxx_typeid_map() failed: T not found");
  323. #endif
  324. }
  325. return it->second;
  326. }
  327. /********** private **********/
  328. virtual ~VM();
  329. #if PK_DEBUG_CEVAL_STEP
  330. void __log_s_data(const char* title = nullptr);
  331. #endif
  332. void __breakpoint();
  333. PyObject* __format_object(PyObject*, Str);
  334. PyObject* __run_top_frame();
  335. void __pop_frame();
  336. PyObject* __py_generator(Frame&& frame, ArgsView buffer);
  337. void __op_unpack_sequence(uint16_t arg);
  338. void __prepare_py_call(PyObject**, ArgsView, ArgsView, const FuncDecl_&);
  339. void __unpack_as_list(ArgsView args, List& list);
  340. void __unpack_as_dict(ArgsView args, Dict& dict);
  341. void __raise_exc(bool re_raise=false);
  342. void __init_builtin_types();
  343. void __post_init_builtin_types();
  344. void __builtin_error(StrName type);
  345. void __builtin_error(StrName type, PyObject* arg);
  346. void __builtin_error(StrName type, const Str& msg);
  347. void __push_varargs(){}
  348. void __push_varargs(PyObject* _0){ PUSH(_0); }
  349. void __push_varargs(PyObject* _0, PyObject* _1){ PUSH(_0); PUSH(_1); }
  350. void __push_varargs(PyObject* _0, PyObject* _1, PyObject* _2){ PUSH(_0); PUSH(_1); PUSH(_2); }
  351. void __push_varargs(PyObject* _0, PyObject* _1, PyObject* _2, PyObject* _3){ PUSH(_0); PUSH(_1); PUSH(_2); PUSH(_3); }
  352. PyObject* __pack_next_retval(unsigned);
  353. PyObject* __minmax_reduce(bool (VM::*op)(PyObject*, PyObject*), PyObject* args, PyObject* key);
  354. };
  355. template<typename T>
  356. inline constexpr bool is_immutable_v = is_integral_v<T> || is_floating_point_v<T>
  357. || std::is_same_v<T, Str> || std::is_same_v<T, Tuple> || std::is_same_v<T, Bytes> || std::is_same_v<T, bool>
  358. || std::is_same_v<T, Range> || std::is_same_v<T, Slice>
  359. || std::is_pointer_v<T> || std::is_enum_v<T>;
  360. template<typename T> constexpr Type _find_type_in_const_cxx_typeid_map(){ return Type(-1); }
  361. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Str>(){ return VM::tp_str; }
  362. template<> constexpr Type _find_type_in_const_cxx_typeid_map<List>(){ return VM::tp_list; }
  363. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Tuple>(){ return VM::tp_tuple; }
  364. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Function>(){ return VM::tp_function; }
  365. template<> constexpr Type _find_type_in_const_cxx_typeid_map<NativeFunc>(){ return VM::tp_native_func; }
  366. template<> constexpr Type _find_type_in_const_cxx_typeid_map<BoundMethod>(){ return VM::tp_bound_method; }
  367. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Range>(){ return VM::tp_range; }
  368. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Slice>(){ return VM::tp_slice; }
  369. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Exception>(){ return VM::tp_exception; }
  370. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Bytes>(){ return VM::tp_bytes; }
  371. template<> constexpr Type _find_type_in_const_cxx_typeid_map<MappingProxy>(){ return VM::tp_mappingproxy; }
  372. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Dict>(){ return VM::tp_dict; }
  373. template<> constexpr Type _find_type_in_const_cxx_typeid_map<Property>(){ return VM::tp_property; }
  374. template<> constexpr Type _find_type_in_const_cxx_typeid_map<StarWrapper>(){ return VM::tp_star_wrapper; }
  375. template<> constexpr Type _find_type_in_const_cxx_typeid_map<StaticMethod>(){ return VM::tp_staticmethod; }
  376. template<> constexpr Type _find_type_in_const_cxx_typeid_map<ClassMethod>(){ return VM::tp_classmethod; }
  377. template<typename __T>
  378. PyObject* py_var(VM* vm, __T&& value){
  379. using T = std::decay_t<__T>;
  380. static_assert(!std::is_same_v<T, PyObject*>, "py_var(VM*, PyObject*) is not allowed");
  381. if constexpr(std::is_same_v<T, const char*> || std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view>){
  382. // str (shortcuts)
  383. return VAR(Str(std::forward<__T>(value)));
  384. }else if constexpr(std::is_same_v<T, NoReturn>){
  385. // NoneType
  386. return vm->None;
  387. }else if constexpr(std::is_same_v<T, bool>){
  388. // bool
  389. return value ? vm->True : vm->False;
  390. }else if constexpr(is_integral_v<T>){
  391. // int
  392. i64 val = static_cast<i64>(std::forward<__T>(value));
  393. if(val >= Number::kMinSmallInt && val <= Number::kMaxSmallInt){
  394. val = (val << 2) | 0b10;
  395. return reinterpret_cast<PyObject*>(val);
  396. }else{
  397. return vm->heap.gcnew<i64>(vm->tp_int, val);
  398. }
  399. }else if constexpr(is_floating_point_v<T>){
  400. // float
  401. f64 val = static_cast<f64>(std::forward<__T>(value));
  402. return vm->heap.gcnew<f64>(vm->tp_float, val);
  403. }else if constexpr(std::is_pointer_v<T>){
  404. return from_void_p(vm, (void*)value);
  405. }else{
  406. constexpr Type const_type = _find_type_in_const_cxx_typeid_map<T>();
  407. if constexpr(const_type.index >= 0){
  408. return vm->heap.gcnew<T>(const_type, std::forward<__T>(value));
  409. }
  410. }
  411. Type type = vm->_find_type_in_cxx_typeid_map<T>();
  412. return vm->heap.gcnew<T>(type, std::forward<__T>(value));
  413. }
  414. template<typename __T, bool with_check>
  415. __T _py_cast__internal(VM* vm, PyObject* obj) {
  416. static_assert(!std::is_rvalue_reference_v<__T>, "rvalue reference is not allowed");
  417. using T = std::decay_t<__T>;
  418. if constexpr(std::is_same_v<T, const char*> || std::is_same_v<T, CString>){
  419. static_assert(!std::is_reference_v<__T>);
  420. // str (shortcuts)
  421. if(obj == vm->None) return nullptr;
  422. if constexpr(with_check) vm->check_type(obj, vm->tp_str);
  423. return PK_OBJ_GET(Str, obj).c_str();
  424. }else if constexpr(std::is_same_v<T, bool>){
  425. static_assert(!std::is_reference_v<__T>);
  426. // bool
  427. if constexpr(with_check){
  428. if(obj == vm->True) return true;
  429. if(obj == vm->False) return false;
  430. vm->TypeError("expected 'bool', got " + _type_name(vm, vm->_tp(obj)).escape());
  431. }else{
  432. return obj == vm->True;
  433. }
  434. }else if constexpr(is_integral_v<T>){
  435. static_assert(!std::is_reference_v<__T>);
  436. // int
  437. if constexpr(with_check){
  438. if(is_small_int(obj)) return (T)(PK_BITS(obj) >> 2);
  439. if(is_heap_int(obj)) return (T)PK_OBJ_GET(i64, obj);
  440. vm->TypeError("expected 'int', got " + _type_name(vm, vm->_tp(obj)).escape());
  441. }else{
  442. if(is_small_int(obj)) return (T)(PK_BITS(obj) >> 2);
  443. return (T)PK_OBJ_GET(i64, obj);
  444. }
  445. }else if constexpr(is_floating_point_v<T>){
  446. static_assert(!std::is_reference_v<__T>);
  447. // float
  448. if(is_float(obj)) return PK_OBJ_GET(f64, obj);
  449. i64 bits;
  450. if(try_cast_int(obj, &bits)) return (float)bits;
  451. vm->TypeError("expected 'int' or 'float', got " + _type_name(vm, vm->_tp(obj)).escape());
  452. }else if constexpr(std::is_enum_v<T>){
  453. static_assert(!std::is_reference_v<__T>);
  454. return (__T)_py_cast__internal<i64, with_check>(vm, obj);
  455. }else if constexpr(std::is_pointer_v<T>){
  456. static_assert(!std::is_reference_v<__T>);
  457. return to_void_p<T>(vm, obj);
  458. }else{
  459. constexpr Type const_type = _find_type_in_const_cxx_typeid_map<T>();
  460. if constexpr(const_type.index >= 0){
  461. if constexpr(with_check){
  462. if constexpr(std::is_same_v<T, Exception>){
  463. // Exception is `subclass_enabled`
  464. vm->check_compatible_type(obj, const_type);
  465. }else{
  466. vm->check_type(obj, const_type);
  467. }
  468. }
  469. return PK_OBJ_GET(T, obj);
  470. }
  471. }
  472. Type type = vm->_find_type_in_cxx_typeid_map<T>();
  473. if constexpr(with_check) vm->check_compatible_type(obj, type);
  474. return PK_OBJ_GET(T, obj);
  475. }
  476. template<typename __T>
  477. __T py_cast(VM* vm, PyObject* obj) { return _py_cast__internal<__T, true>(vm, obj); }
  478. template<typename __T>
  479. __T _py_cast(VM* vm, PyObject* obj) { return _py_cast__internal<__T, false>(vm, obj); }
  480. template<typename T>
  481. PyObject* VM::register_user_class(PyObject* mod, StrName name, RegisterFunc _register, Type base, bool subclass_enabled){
  482. PyObject* type = new_type_object(mod, name, base, subclass_enabled);
  483. mod->attr().set(name, type);
  484. _cxx_typeid_map[typeid(T)] = PK_OBJ_GET(Type, type);
  485. _register(this, mod, type);
  486. if(!type->attr().contains(__new__)){
  487. if constexpr(std::is_default_constructible_v<T>) {
  488. bind_func(type, __new__, -1, [](VM* vm, ArgsView args){
  489. Type cls_t = PK_OBJ_GET(Type, args[0]);
  490. return vm->heap.gcnew<T>(cls_t);
  491. });
  492. }else{
  493. bind_func(type, __new__, -1, PK_ACTION(vm->NotImplementedError()));
  494. }
  495. }
  496. return type;
  497. }
  498. template<typename T>
  499. PyObject* VM::register_user_class(PyObject* mod, StrName name, Type base, bool subclass_enabled){
  500. return register_user_class<T>(mod, name, &T::_register, base, subclass_enabled);
  501. }
  502. } // namespace pkpy