vm.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. namespace pkpy{
  13. /* Stack manipulation macros */
  14. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  15. #define TOP() (s_data.top())
  16. #define SECOND() (s_data.second())
  17. #define THIRD() (s_data.third())
  18. #define PEEK(n) (s_data.peek(n))
  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. #define DEF_NATIVE_2(ctype, ptype) \
  25. template<> inline ctype py_cast<ctype>(VM* vm, PyObject* obj) { \
  26. vm->check_non_tagged_type(obj, vm->ptype); \
  27. return PK_OBJ_GET(ctype, obj); \
  28. } \
  29. template<> inline ctype _py_cast<ctype>(VM* vm, PyObject* obj) { \
  30. PK_UNUSED(vm); \
  31. return PK_OBJ_GET(ctype, obj); \
  32. } \
  33. template<> inline ctype& py_cast<ctype&>(VM* vm, PyObject* obj) { \
  34. vm->check_non_tagged_type(obj, vm->ptype); \
  35. return PK_OBJ_GET(ctype, obj); \
  36. } \
  37. template<> inline ctype& _py_cast<ctype&>(VM* vm, PyObject* obj) { \
  38. PK_UNUSED(vm); \
  39. return PK_OBJ_GET(ctype, obj); \
  40. } \
  41. inline PyObject* py_var(VM* vm, const ctype& value) { return vm->heap.gcnew<ctype>(vm->ptype, value);} \
  42. inline PyObject* py_var(VM* vm, ctype&& value) { return vm->heap.gcnew<ctype>(vm->ptype, std::move(value));}
  43. typedef PyObject* (*BinaryFuncC)(VM*, PyObject*, PyObject*);
  44. struct PyTypeInfo{
  45. PyObject* obj; // never be garbage collected
  46. Type base;
  47. PyObject* mod; // never be garbage collected
  48. Str name;
  49. bool subclass_enabled;
  50. // cached special methods
  51. // unary operators
  52. PyObject* (*m__repr__)(VM* vm, PyObject*) = nullptr;
  53. PyObject* (*m__str__)(VM* vm, PyObject*) = nullptr;
  54. i64 (*m__hash__)(VM* vm, PyObject*) = nullptr;
  55. i64 (*m__len__)(VM* vm, PyObject*) = nullptr;
  56. PyObject* (*m__iter__)(VM* vm, PyObject*) = nullptr;
  57. PyObject* (*m__next__)(VM* vm, PyObject*) = nullptr;
  58. PyObject* (*m__neg__)(VM* vm, PyObject*) = nullptr;
  59. PyObject* (*m__bool__)(VM* vm, PyObject*) = nullptr;
  60. PyObject* (*m__invert__)(VM* vm, PyObject*) = nullptr;
  61. BinaryFuncC m__eq__ = nullptr;
  62. BinaryFuncC m__lt__ = nullptr;
  63. BinaryFuncC m__le__ = nullptr;
  64. BinaryFuncC m__gt__ = nullptr;
  65. BinaryFuncC m__ge__ = nullptr;
  66. BinaryFuncC m__contains__ = nullptr;
  67. // binary operators
  68. BinaryFuncC m__add__ = nullptr;
  69. BinaryFuncC m__sub__ = nullptr;
  70. BinaryFuncC m__mul__ = nullptr;
  71. BinaryFuncC m__truediv__ = nullptr;
  72. BinaryFuncC m__floordiv__ = nullptr;
  73. BinaryFuncC m__mod__ = nullptr;
  74. BinaryFuncC m__pow__ = nullptr;
  75. BinaryFuncC m__matmul__ = nullptr;
  76. BinaryFuncC m__lshift__ = nullptr;
  77. BinaryFuncC m__rshift__ = nullptr;
  78. BinaryFuncC m__and__ = nullptr;
  79. BinaryFuncC m__or__ = nullptr;
  80. BinaryFuncC m__xor__ = nullptr;
  81. // indexer
  82. PyObject* (*m__getitem__)(VM* vm, PyObject*, PyObject*) = nullptr;
  83. void (*m__setitem__)(VM* vm, PyObject*, PyObject*, PyObject*) = nullptr;
  84. void (*m__delitem__)(VM* vm, PyObject*, PyObject*) = nullptr;
  85. };
  86. struct FrameId{
  87. std::vector<pkpy::Frame>* data;
  88. int index;
  89. FrameId(std::vector<pkpy::Frame>* data, int index) : data(data), index(index) {}
  90. Frame* operator->() const { return &data->operator[](index); }
  91. Frame* get() const { return &data->operator[](index); }
  92. };
  93. typedef void(*PrintFunc)(VM*, const char*, int);
  94. class VM {
  95. PK_ALWAYS_PASS_BY_POINTER(VM)
  96. VM* vm; // self reference for simplify code
  97. public:
  98. ManagedHeap heap;
  99. ValueStack s_data;
  100. stack< Frame > callstack;
  101. std::vector<PyTypeInfo> _all_types;
  102. NameDict _modules; // loaded modules
  103. std::map<StrName, Str> _lazy_modules; // lazy loaded modules
  104. struct{
  105. PyObject* error;
  106. stack<ArgsView> s_view;
  107. } _c;
  108. PyObject* None;
  109. PyObject* True;
  110. PyObject* False;
  111. PyObject* NotImplemented; // unused
  112. PyObject* Ellipsis;
  113. PyObject* builtins; // builtins module
  114. PyObject* StopIteration;
  115. PyObject* _main; // __main__ module
  116. PyObject* _last_exception;
  117. #if PK_ENABLE_CEVAL_CALLBACK
  118. void (*_ceval_on_step)(VM*, Frame*, Bytecode bc) = nullptr;
  119. #endif
  120. PrintFunc _stdout;
  121. PrintFunc _stderr;
  122. Bytes (*_import_handler)(const Str& name);
  123. // for quick access
  124. Type tp_object, tp_type, tp_int, tp_float, tp_bool, tp_str;
  125. Type tp_list, tp_tuple;
  126. Type tp_function, tp_native_func, tp_bound_method;
  127. Type tp_slice, tp_range, tp_module;
  128. Type tp_super, tp_exception, tp_bytes, tp_mappingproxy;
  129. Type tp_dict, tp_property, tp_star_wrapper;
  130. PyObject* cached_object__new__;
  131. const bool enable_os;
  132. VM(bool enable_os=true);
  133. FrameId top_frame();
  134. void _pop_frame();
  135. PyObject* py_str(PyObject* obj);
  136. PyObject* py_repr(PyObject* obj);
  137. PyObject* py_json(PyObject* obj);
  138. PyObject* py_iter(PyObject* obj);
  139. PyObject* find_name_in_mro(PyObject* cls, StrName name);
  140. bool isinstance(PyObject* obj, Type base);
  141. bool issubclass(Type cls, Type base);
  142. PyObject* exec(Str source, Str filename, CompileMode mode, PyObject* _module=nullptr);
  143. PyObject* exec(Str source);
  144. PyObject* eval(Str source);
  145. template<typename ...Args>
  146. PyObject* _exec(Args&&... args){
  147. callstack.emplace(&s_data, s_data._sp, std::forward<Args>(args)...);
  148. return _run_top_frame();
  149. }
  150. void _push_varargs(){ }
  151. void _push_varargs(PyObject* _0){ PUSH(_0); }
  152. void _push_varargs(PyObject* _0, PyObject* _1){ PUSH(_0); PUSH(_1); }
  153. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2){ PUSH(_0); PUSH(_1); PUSH(_2); }
  154. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2, PyObject* _3){ PUSH(_0); PUSH(_1); PUSH(_2); PUSH(_3); }
  155. void stdout_write(const Str& s){
  156. _stdout(this, s.data, s.size);
  157. }
  158. template<typename... Args>
  159. PyObject* call(PyObject* callable, Args&&... args){
  160. PUSH(callable);
  161. PUSH(PY_NULL);
  162. _push_varargs(args...);
  163. return vectorcall(sizeof...(args));
  164. }
  165. template<typename... Args>
  166. PyObject* call_method(PyObject* self, PyObject* callable, Args&&... args){
  167. PUSH(callable);
  168. PUSH(self);
  169. _push_varargs(args...);
  170. return vectorcall(sizeof...(args));
  171. }
  172. template<typename... Args>
  173. PyObject* call_method(PyObject* self, StrName name, Args&&... args){
  174. PyObject* callable = get_unbound_method(self, name, &self);
  175. return call_method(self, callable, args...);
  176. }
  177. PyObject* new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled=true);
  178. Type _new_type_object(StrName name, Type base=0);
  179. PyObject* _find_type_object(const Str& type);
  180. Type _type(const Str& type);
  181. PyTypeInfo* _type_info(const Str& type);
  182. PyTypeInfo* _type_info(Type type);
  183. const PyTypeInfo* _inst_type_info(PyObject* obj);
  184. #define BIND_UNARY_SPECIAL(name) \
  185. void bind##name(Type type, PyObject* (*f)(VM*, PyObject*)){ \
  186. _all_types[type].m##name = f; \
  187. PyObject* nf = bind_method<0>(_t(type), #name, [](VM* vm, ArgsView args){ \
  188. return lambda_get_userdata<PyObject*(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);\
  189. }); \
  190. PK_OBJ_GET(NativeFunc, nf).set_userdata(f); \
  191. }
  192. BIND_UNARY_SPECIAL(__repr__)
  193. BIND_UNARY_SPECIAL(__str__)
  194. BIND_UNARY_SPECIAL(__iter__)
  195. BIND_UNARY_SPECIAL(__next__)
  196. BIND_UNARY_SPECIAL(__neg__)
  197. BIND_UNARY_SPECIAL(__bool__)
  198. BIND_UNARY_SPECIAL(__invert__)
  199. void bind__hash__(Type type, i64 (*f)(VM* vm, PyObject*));
  200. void bind__len__(Type type, i64 (*f)(VM* vm, PyObject*));
  201. #undef BIND_UNARY_SPECIAL
  202. #define BIND_BINARY_SPECIAL(name) \
  203. void bind##name(Type type, BinaryFuncC f){ \
  204. PyObject* obj = _t(type); \
  205. _all_types[type].m##name = f; \
  206. PyObject* nf = bind_method<1>(obj, #name, [](VM* vm, ArgsView args){ \
  207. return lambda_get_userdata<BinaryFuncC>(args.begin())(vm, args[0], args[1]); \
  208. }); \
  209. PK_OBJ_GET(NativeFunc, nf).set_userdata(f); \
  210. }
  211. BIND_BINARY_SPECIAL(__eq__)
  212. BIND_BINARY_SPECIAL(__lt__)
  213. BIND_BINARY_SPECIAL(__le__)
  214. BIND_BINARY_SPECIAL(__gt__)
  215. BIND_BINARY_SPECIAL(__ge__)
  216. BIND_BINARY_SPECIAL(__contains__)
  217. BIND_BINARY_SPECIAL(__add__)
  218. BIND_BINARY_SPECIAL(__sub__)
  219. BIND_BINARY_SPECIAL(__mul__)
  220. BIND_BINARY_SPECIAL(__truediv__)
  221. BIND_BINARY_SPECIAL(__floordiv__)
  222. BIND_BINARY_SPECIAL(__mod__)
  223. BIND_BINARY_SPECIAL(__pow__)
  224. BIND_BINARY_SPECIAL(__matmul__)
  225. BIND_BINARY_SPECIAL(__lshift__)
  226. BIND_BINARY_SPECIAL(__rshift__)
  227. BIND_BINARY_SPECIAL(__and__)
  228. BIND_BINARY_SPECIAL(__or__)
  229. BIND_BINARY_SPECIAL(__xor__)
  230. #undef BIND_BINARY_SPECIAL
  231. void bind__getitem__(Type type, PyObject* (*f)(VM*, PyObject*, PyObject*)){
  232. PyObject* obj = _t(type);
  233. _all_types[type].m__getitem__ = f;
  234. PyObject* nf = bind_method<1>(obj, "__getitem__", [](VM* vm, ArgsView args){
  235. return lambda_get_userdata<PyObject*(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  236. });
  237. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  238. }
  239. void bind__setitem__(Type type, void (*f)(VM*, PyObject*, PyObject*, PyObject*)){
  240. PyObject* obj = _t(type);
  241. _all_types[type].m__setitem__ = f;
  242. PyObject* nf = bind_method<2>(obj, "__setitem__", [](VM* vm, ArgsView args){
  243. lambda_get_userdata<void(*)(VM* vm, PyObject*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1], args[2]);
  244. return vm->None;
  245. });
  246. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  247. }
  248. void bind__delitem__(Type type, void (*f)(VM*, PyObject*, PyObject*)){
  249. PyObject* obj = _t(type);
  250. _all_types[type].m__delitem__ = f;
  251. PyObject* nf = bind_method<1>(obj, "__delitem__", [](VM* vm, ArgsView args){
  252. lambda_get_userdata<void(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  253. return vm->None;
  254. });
  255. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  256. }
  257. bool py_equals(PyObject* lhs, PyObject* rhs);
  258. template<int ARGC>
  259. PyObject* bind_func(Str type, Str name, NativeFuncC fn) {
  260. return bind_func<ARGC>(_find_type_object(type), name, fn);
  261. }
  262. template<int ARGC>
  263. PyObject* bind_method(Str type, Str name, NativeFuncC fn) {
  264. return bind_method<ARGC>(_find_type_object(type), name, fn);
  265. }
  266. template<int ARGC, typename __T>
  267. PyObject* bind_constructor(__T&& type, NativeFuncC fn) {
  268. static_assert(ARGC==-1 || ARGC>=1);
  269. return bind_func<ARGC>(std::forward<__T>(type), "__new__", fn);
  270. }
  271. template<typename T, typename __T>
  272. PyObject* bind_default_constructor(__T&& type) {
  273. return bind_constructor<1>(std::forward<__T>(type), [](VM* vm, ArgsView args){
  274. Type t = PK_OBJ_GET(Type, args[0]);
  275. return vm->heap.gcnew<T>(t, T());
  276. });
  277. }
  278. template<typename T, typename __T>
  279. PyObject* bind_notimplemented_constructor(__T&& type) {
  280. return bind_constructor<-1>(std::forward<__T>(type), [](VM* vm, ArgsView args){
  281. PK_UNUSED(args);
  282. vm->NotImplementedError();
  283. return vm->None;
  284. });
  285. }
  286. template<int ARGC>
  287. PyObject* bind_builtin_func(Str name, NativeFuncC fn) {
  288. return bind_func<ARGC>(builtins, name, fn);
  289. }
  290. int normalized_index(int index, int size);
  291. PyObject* py_next(PyObject* obj);
  292. /***** Error Reporter *****/
  293. void _error(StrName name, const Str& msg){
  294. _error(Exception(name, msg));
  295. }
  296. void _raise(bool re_raise=false);
  297. void StackOverflowError() { _error("StackOverflowError", ""); }
  298. void IOError(const Str& msg) { _error("IOError", msg); }
  299. void NotImplementedError(){ _error("NotImplementedError", ""); }
  300. void TypeError(const Str& msg){ _error("TypeError", msg); }
  301. void IndexError(const Str& msg){ _error("IndexError", msg); }
  302. void ValueError(const Str& msg){ _error("ValueError", msg); }
  303. void ZeroDivisionError(const Str& msg){ _error("ZeroDivisionError", msg); }
  304. void ZeroDivisionError(){ _error("ZeroDivisionError", "division by zero"); }
  305. void NameError(StrName name){ _error("NameError", fmt("name ", name.escape() + " is not defined")); }
  306. void UnboundLocalError(StrName name){ _error("UnboundLocalError", fmt("local variable ", name.escape() + " referenced before assignment")); }
  307. void KeyError(PyObject* obj){ _error("KeyError", PK_OBJ_GET(Str, py_repr(obj))); }
  308. void BinaryOptError(const char* op) { TypeError(fmt("unsupported operand type(s) for ", op)); }
  309. void ImportError(const Str& msg){ _error("ImportError", msg); }
  310. void AttributeError(PyObject* obj, StrName name){
  311. // OBJ_NAME calls getattr, which may lead to a infinite recursion
  312. if(isinstance(obj, vm->tp_type)){
  313. _error("AttributeError", fmt("type object ", OBJ_NAME(obj).escape(), " has no attribute ", name.escape()));
  314. }else{
  315. _error("AttributeError", fmt(OBJ_NAME(_t(obj)).escape(), " object has no attribute ", name.escape()));
  316. }
  317. }
  318. void AttributeError(Str msg){ _error("AttributeError", msg); }
  319. void check_type(PyObject* obj, Type type){
  320. if(is_type(obj, type)) return;
  321. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", got " + OBJ_NAME(_t(obj)).escape());
  322. }
  323. void check_args_size(int size, int min_size, int max_size){
  324. if(size >= min_size && size <= max_size) return;
  325. TypeError(fmt("expected ", min_size, "-", max_size, " arguments, got ", size));
  326. }
  327. void check_non_tagged_type(PyObject* obj, Type type){
  328. if(is_non_tagged_type(obj, type)) return;
  329. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", got " + OBJ_NAME(_t(obj)).escape());
  330. }
  331. PyObject* _t(Type t){
  332. return _all_types[t.index].obj;
  333. }
  334. Type _tp(PyObject* obj){
  335. if(is_int(obj)) return tp_int;
  336. if(is_float(obj)) return tp_float;
  337. return obj->type;
  338. }
  339. PyObject* _t(PyObject* obj){
  340. return _all_types[_tp(obj).index].obj;
  341. }
  342. struct ImportContext{
  343. std::vector<Str> pending;
  344. std::vector<bool> pending_is_init; // a.k.a __init__.py
  345. struct Temp{
  346. ImportContext* ctx;
  347. Temp(ImportContext* ctx, Str name, bool is_init) : ctx(ctx){
  348. ctx->pending.push_back(name);
  349. ctx->pending_is_init.push_back(is_init);
  350. }
  351. ~Temp(){
  352. ctx->pending.pop_back();
  353. ctx->pending_is_init.pop_back();
  354. }
  355. };
  356. Temp scope(Str name, bool is_init){
  357. return {this, name, is_init};
  358. }
  359. };
  360. ImportContext _import_context;
  361. PyObject* py_import(Str path, bool throw_err=true);
  362. ~VM();
  363. #if PK_DEBUG_CEVAL_STEP
  364. void _log_s_data(const char* title = nullptr);
  365. #endif
  366. void _unpack_as_list(ArgsView args, List& list);
  367. void _unpack_as_dict(ArgsView args, Dict& dict);
  368. PyObject* vectorcall(int ARGC, int KWARGC=0, bool op_call=false);
  369. CodeObject_ compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope=false);
  370. PyObject* py_negate(PyObject* obj);
  371. bool py_bool(PyObject* obj);
  372. i64 py_hash(PyObject* obj);
  373. PyObject* py_list(PyObject*);
  374. PyObject* new_module(Str name, Str package="");
  375. Str disassemble(CodeObject_ co);
  376. void init_builtin_types();
  377. PyObject* getattr(PyObject* obj, StrName name, bool throw_err=true);
  378. void delattr(PyObject* obj, StrName name);
  379. PyObject* get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err=true, bool fallback=false);
  380. void parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step);
  381. PyObject* format(Str, PyObject*);
  382. void setattr(PyObject* obj, StrName name, PyObject* value);
  383. template<int ARGC>
  384. PyObject* bind_method(PyObject*, Str, NativeFuncC);
  385. template<int ARGC>
  386. PyObject* bind_func(PyObject*, Str, NativeFuncC);
  387. void _error(Exception);
  388. PyObject* _run_top_frame();
  389. void post_init();
  390. PyObject* _py_generator(Frame&& frame, ArgsView buffer);
  391. void _prepare_py_call(PyObject**, ArgsView, ArgsView, const FuncDecl_&);
  392. // new style binding api
  393. PyObject* bind(PyObject*, const char*, const char*, NativeFuncC, UserData userdata={});
  394. PyObject* bind(PyObject*, const char*, NativeFuncC, UserData userdata={});
  395. PyObject* bind_property(PyObject*, Str, NativeFuncC fget, NativeFuncC fset=nullptr);
  396. };
  397. DEF_NATIVE_2(Str, tp_str)
  398. DEF_NATIVE_2(List, tp_list)
  399. DEF_NATIVE_2(Tuple, tp_tuple)
  400. DEF_NATIVE_2(Function, tp_function)
  401. DEF_NATIVE_2(NativeFunc, tp_native_func)
  402. DEF_NATIVE_2(BoundMethod, tp_bound_method)
  403. DEF_NATIVE_2(Range, tp_range)
  404. DEF_NATIVE_2(Slice, tp_slice)
  405. DEF_NATIVE_2(Exception, tp_exception)
  406. DEF_NATIVE_2(Bytes, tp_bytes)
  407. DEF_NATIVE_2(MappingProxy, tp_mappingproxy)
  408. DEF_NATIVE_2(Dict, tp_dict)
  409. DEF_NATIVE_2(Property, tp_property)
  410. DEF_NATIVE_2(StarWrapper, tp_star_wrapper)
  411. #undef DEF_NATIVE_2
  412. #define PY_CAST_INT(T) \
  413. template<> inline T py_cast<T>(VM* vm, PyObject* obj){ \
  414. if(is_small_int(obj)) return (T)(PK_BITS(obj) >> 2); \
  415. if(is_heap_int(obj)) return (T)PK_OBJ_GET(i64, obj); \
  416. vm->check_type(obj, vm->tp_int); \
  417. return 0; \
  418. } \
  419. template<> inline T _py_cast<T>(VM* vm, PyObject* obj){ \
  420. PK_UNUSED(vm); \
  421. if(is_small_int(obj)) return (T)(PK_BITS(obj) >> 2); \
  422. return (T)PK_OBJ_GET(i64, obj); \
  423. }
  424. PY_CAST_INT(char)
  425. PY_CAST_INT(short)
  426. PY_CAST_INT(int)
  427. PY_CAST_INT(long)
  428. PY_CAST_INT(long long)
  429. PY_CAST_INT(unsigned char)
  430. PY_CAST_INT(unsigned short)
  431. PY_CAST_INT(unsigned int)
  432. PY_CAST_INT(unsigned long)
  433. PY_CAST_INT(unsigned long long)
  434. template<> inline float py_cast<float>(VM* vm, PyObject* obj){
  435. if(is_float(obj)) return untag_float(obj);
  436. i64 bits;
  437. if(try_cast_int(obj, &bits)) return (float)bits;
  438. vm->TypeError("expected 'int' or 'float', got " + OBJ_NAME(vm->_t(obj)).escape());
  439. return 0;
  440. }
  441. template<> inline float _py_cast<float>(VM* vm, PyObject* obj){
  442. return py_cast<float>(vm, obj);
  443. }
  444. template<> inline double py_cast<double>(VM* vm, PyObject* obj){
  445. if(is_float(obj)) return untag_float(obj);
  446. i64 bits;
  447. if(try_cast_int(obj, &bits)) return (float)bits;
  448. vm->TypeError("expected 'int' or 'float', got " + OBJ_NAME(vm->_t(obj)).escape());
  449. return 0;
  450. }
  451. template<> inline double _py_cast<double>(VM* vm, PyObject* obj){
  452. return py_cast<double>(vm, obj);
  453. }
  454. #define PY_VAR_INT(T) \
  455. inline PyObject* py_var(VM* vm, T _val){ \
  456. i64 val = static_cast<i64>(_val); \
  457. if(val >= Number::kMinSmallInt && val <= Number::kMaxSmallInt){ \
  458. val = (val << 2) | 0b10; \
  459. return reinterpret_cast<PyObject*>(val); \
  460. }else{ \
  461. return vm->heap.gcnew<i64>(vm->tp_int, val); \
  462. } \
  463. }
  464. PY_VAR_INT(char)
  465. PY_VAR_INT(short)
  466. PY_VAR_INT(int)
  467. PY_VAR_INT(long)
  468. PY_VAR_INT(long long)
  469. PY_VAR_INT(unsigned char)
  470. PY_VAR_INT(unsigned short)
  471. PY_VAR_INT(unsigned int)
  472. PY_VAR_INT(unsigned long)
  473. PY_VAR_INT(unsigned long long)
  474. #define PY_VAR_FLOAT(T) \
  475. inline PyObject* py_var(VM* vm, T _val){ \
  476. PK_UNUSED(vm); \
  477. return tag_float(static_cast<f64>(_val)); \
  478. }
  479. PY_VAR_FLOAT(float)
  480. PY_VAR_FLOAT(double)
  481. #undef PY_VAR_INT
  482. #undef PY_VAR_FLOAT
  483. inline PyObject* py_var(VM* vm, bool val){
  484. return val ? vm->True : vm->False;
  485. }
  486. template<> inline bool py_cast<bool>(VM* vm, PyObject* obj){
  487. if(obj == vm->True) return true;
  488. if(obj == vm->False) return false;
  489. vm->check_non_tagged_type(obj, vm->tp_bool);
  490. return false;
  491. }
  492. template<> inline bool _py_cast<bool>(VM* vm, PyObject* obj){
  493. return obj == vm->True;
  494. }
  495. template<> inline CString py_cast<CString>(VM* vm, PyObject* obj){
  496. vm->check_non_tagged_type(obj, vm->tp_str);
  497. return PK_OBJ_GET(Str, obj).c_str();
  498. }
  499. template<> inline CString _py_cast<CString>(VM* vm, PyObject* obj){
  500. return PK_OBJ_GET(Str, obj).c_str();
  501. }
  502. inline PyObject* py_var(VM* vm, const char* val){
  503. return VAR(Str(val));
  504. }
  505. template<>
  506. inline const char* py_cast<const char*>(VM* vm, PyObject* obj){
  507. vm->check_non_tagged_type(obj, vm->tp_str);
  508. return PK_OBJ_GET(Str, obj).c_str();
  509. }
  510. template<>
  511. inline const char* _py_cast<const char*>(VM* vm, PyObject* obj){
  512. return PK_OBJ_GET(Str, obj).c_str();
  513. }
  514. inline PyObject* py_var(VM* vm, std::string val){
  515. return VAR(Str(std::move(val)));
  516. }
  517. inline PyObject* py_var(VM* vm, std::string_view val){
  518. return VAR(Str(val));
  519. }
  520. inline PyObject* py_var(VM* vm, NoReturn val){
  521. PK_UNUSED(val);
  522. return vm->None;
  523. }
  524. template<int ARGC>
  525. PyObject* VM::bind_method(PyObject* obj, Str name, NativeFuncC fn) {
  526. check_non_tagged_type(obj, tp_type);
  527. PyObject* nf = VAR(NativeFunc(fn, ARGC, true));
  528. obj->attr().set(name, nf);
  529. return nf;
  530. }
  531. template<int ARGC>
  532. PyObject* VM::bind_func(PyObject* obj, Str name, NativeFuncC fn) {
  533. PyObject* nf = VAR(NativeFunc(fn, ARGC, false));
  534. obj->attr().set(name, nf);
  535. return nf;
  536. }
  537. /***************************************************/
  538. template<typename T>
  539. PyObject* PyArrayGetItem(VM* vm, PyObject* obj, PyObject* index){
  540. static_assert(std::is_same_v<T, List> || std::is_same_v<T, Tuple>);
  541. const T& self = _CAST(T&, obj);
  542. if(is_non_tagged_type(index, vm->tp_slice)){
  543. const Slice& s = _CAST(Slice&, index);
  544. int start, stop, step;
  545. vm->parse_int_slice(s, self.size(), start, stop, step);
  546. List new_list;
  547. for(int i=start; step>0?i<stop:i>stop; i+=step) new_list.push_back(self[i]);
  548. return VAR(T(std::move(new_list)));
  549. }
  550. int i = CAST(int, index);
  551. i = vm->normalized_index(i, self.size());
  552. return self[i];
  553. }
  554. } // namespace pkpy