vm.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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;
  46. Type base;
  47. Str name;
  48. bool subclass_enabled;
  49. // cached special methods
  50. // unary operators
  51. PyObject* (*m__repr__)(VM* vm, PyObject*) = nullptr;
  52. PyObject* (*m__str__)(VM* vm, PyObject*) = nullptr;
  53. i64 (*m__hash__)(VM* vm, PyObject*) = nullptr;
  54. i64 (*m__len__)(VM* vm, PyObject*) = nullptr;
  55. PyObject* (*m__iter__)(VM* vm, PyObject*) = nullptr;
  56. PyObject* (*m__next__)(VM* vm, PyObject*) = nullptr;
  57. PyObject* (*m__json__)(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 cls_t);
  141. PyObject* exec(Str source, Str filename, CompileMode mode, PyObject* _module=nullptr);
  142. template<typename ...Args>
  143. PyObject* _exec(Args&&... args){
  144. callstack.emplace(&s_data, s_data._sp, std::forward<Args>(args)...);
  145. return _run_top_frame();
  146. }
  147. void _push_varargs(){ }
  148. void _push_varargs(PyObject* _0){ PUSH(_0); }
  149. void _push_varargs(PyObject* _0, PyObject* _1){ PUSH(_0); PUSH(_1); }
  150. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2){ PUSH(_0); PUSH(_1); PUSH(_2); }
  151. void _push_varargs(PyObject* _0, PyObject* _1, PyObject* _2, PyObject* _3){ PUSH(_0); PUSH(_1); PUSH(_2); PUSH(_3); }
  152. void stdout_write(const Str& s){
  153. _stdout(this, s.data, s.size);
  154. }
  155. template<typename... Args>
  156. PyObject* call(PyObject* callable, Args&&... args){
  157. PUSH(callable);
  158. PUSH(PY_NULL);
  159. _push_varargs(args...);
  160. return vectorcall(sizeof...(args));
  161. }
  162. template<typename... Args>
  163. PyObject* call_method(PyObject* self, PyObject* callable, Args&&... args){
  164. PUSH(callable);
  165. PUSH(self);
  166. _push_varargs(args...);
  167. return vectorcall(sizeof...(args));
  168. }
  169. template<typename... Args>
  170. PyObject* call_method(PyObject* self, StrName name, Args&&... args){
  171. PyObject* callable = get_unbound_method(self, name, &self);
  172. return call_method(self, callable, args...);
  173. }
  174. PyObject* new_type_object(PyObject* mod, StrName name, Type base, bool subclass_enabled=true);
  175. Type _new_type_object(StrName name, Type base=0);
  176. PyObject* _find_type_object(const Str& type);
  177. Type _type(const Str& type);
  178. PyTypeInfo* _type_info(const Str& type);
  179. PyTypeInfo* _type_info(Type type);
  180. const PyTypeInfo* _inst_type_info(PyObject* obj);
  181. #define BIND_UNARY_SPECIAL(name) \
  182. void bind##name(Type type, PyObject* (*f)(VM*, PyObject*)){ \
  183. _all_types[type].m##name = f; \
  184. PyObject* nf = bind_method<0>(_t(type), #name, [](VM* vm, ArgsView args){ \
  185. return lambda_get_userdata<PyObject*(*)(VM*, PyObject*)>(args.begin())(vm, args[0]);\
  186. }); \
  187. PK_OBJ_GET(NativeFunc, nf).set_userdata(f); \
  188. }
  189. BIND_UNARY_SPECIAL(__repr__)
  190. BIND_UNARY_SPECIAL(__str__)
  191. BIND_UNARY_SPECIAL(__iter__)
  192. BIND_UNARY_SPECIAL(__next__)
  193. BIND_UNARY_SPECIAL(__json__)
  194. BIND_UNARY_SPECIAL(__neg__)
  195. BIND_UNARY_SPECIAL(__bool__)
  196. BIND_UNARY_SPECIAL(__invert__)
  197. void bind__hash__(Type type, i64 (*f)(VM* vm, PyObject*));
  198. void bind__len__(Type type, i64 (*f)(VM* vm, PyObject*));
  199. #undef BIND_UNARY_SPECIAL
  200. #define BIND_BINARY_SPECIAL(name) \
  201. void bind##name(Type type, BinaryFuncC f){ \
  202. PyObject* obj = _t(type); \
  203. _all_types[type].m##name = f; \
  204. PyObject* nf = bind_method<1>(obj, #name, [](VM* vm, ArgsView args){ \
  205. return lambda_get_userdata<BinaryFuncC>(args.begin())(vm, args[0], args[1]); \
  206. }); \
  207. PK_OBJ_GET(NativeFunc, nf).set_userdata(f); \
  208. }
  209. BIND_BINARY_SPECIAL(__eq__)
  210. BIND_BINARY_SPECIAL(__lt__)
  211. BIND_BINARY_SPECIAL(__le__)
  212. BIND_BINARY_SPECIAL(__gt__)
  213. BIND_BINARY_SPECIAL(__ge__)
  214. BIND_BINARY_SPECIAL(__contains__)
  215. BIND_BINARY_SPECIAL(__add__)
  216. BIND_BINARY_SPECIAL(__sub__)
  217. BIND_BINARY_SPECIAL(__mul__)
  218. BIND_BINARY_SPECIAL(__truediv__)
  219. BIND_BINARY_SPECIAL(__floordiv__)
  220. BIND_BINARY_SPECIAL(__mod__)
  221. BIND_BINARY_SPECIAL(__pow__)
  222. BIND_BINARY_SPECIAL(__matmul__)
  223. BIND_BINARY_SPECIAL(__lshift__)
  224. BIND_BINARY_SPECIAL(__rshift__)
  225. BIND_BINARY_SPECIAL(__and__)
  226. BIND_BINARY_SPECIAL(__or__)
  227. BIND_BINARY_SPECIAL(__xor__)
  228. #undef BIND_BINARY_SPECIAL
  229. void bind__getitem__(Type type, PyObject* (*f)(VM*, PyObject*, PyObject*)){
  230. PyObject* obj = _t(type);
  231. _all_types[type].m__getitem__ = f;
  232. PyObject* nf = bind_method<1>(obj, "__getitem__", [](VM* vm, ArgsView args){
  233. return lambda_get_userdata<PyObject*(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  234. });
  235. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  236. }
  237. void bind__setitem__(Type type, void (*f)(VM*, PyObject*, PyObject*, PyObject*)){
  238. PyObject* obj = _t(type);
  239. _all_types[type].m__setitem__ = f;
  240. PyObject* nf = bind_method<2>(obj, "__setitem__", [](VM* vm, ArgsView args){
  241. lambda_get_userdata<void(*)(VM* vm, PyObject*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1], args[2]);
  242. return vm->None;
  243. });
  244. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  245. }
  246. void bind__delitem__(Type type, void (*f)(VM*, PyObject*, PyObject*)){
  247. PyObject* obj = _t(type);
  248. _all_types[type].m__delitem__ = f;
  249. PyObject* nf = bind_method<1>(obj, "__delitem__", [](VM* vm, ArgsView args){
  250. lambda_get_userdata<void(*)(VM*, PyObject*, PyObject*)>(args.begin())(vm, args[0], args[1]);
  251. return vm->None;
  252. });
  253. PK_OBJ_GET(NativeFunc, nf).set_userdata(f);
  254. }
  255. bool py_equals(PyObject* lhs, PyObject* rhs);
  256. template<int ARGC>
  257. PyObject* bind_func(Str type, Str name, NativeFuncC fn) {
  258. return bind_func<ARGC>(_find_type_object(type), name, fn);
  259. }
  260. template<int ARGC>
  261. PyObject* bind_method(Str type, Str name, NativeFuncC fn) {
  262. return bind_method<ARGC>(_find_type_object(type), name, fn);
  263. }
  264. template<int ARGC, typename __T>
  265. PyObject* bind_constructor(__T&& type, NativeFuncC fn) {
  266. static_assert(ARGC==-1 || ARGC>=1);
  267. return bind_func<ARGC>(std::forward<__T>(type), "__new__", fn);
  268. }
  269. template<typename T, typename __T>
  270. PyObject* bind_default_constructor(__T&& type) {
  271. return bind_constructor<1>(std::forward<__T>(type), [](VM* vm, ArgsView args){
  272. Type t = PK_OBJ_GET(Type, args[0]);
  273. return vm->heap.gcnew<T>(t, T());
  274. });
  275. }
  276. template<typename T, typename __T>
  277. PyObject* bind_notimplemented_constructor(__T&& type) {
  278. return bind_constructor<-1>(std::forward<__T>(type), [](VM* vm, ArgsView args){
  279. PK_UNUSED(args);
  280. vm->NotImplementedError();
  281. return vm->None;
  282. });
  283. }
  284. template<int ARGC>
  285. PyObject* bind_builtin_func(Str name, NativeFuncC fn) {
  286. return bind_func<ARGC>(builtins, name, fn);
  287. }
  288. int normalized_index(int index, int size);
  289. PyObject* py_next(PyObject* obj);
  290. /***** Error Reporter *****/
  291. void _error(StrName name, const Str& msg){
  292. _error(Exception(name, msg));
  293. }
  294. void _raise(){
  295. bool ok = top_frame()->jump_to_exception_handler();
  296. if(ok) throw HandledException();
  297. else throw UnhandledException();
  298. }
  299. void StackOverflowError() { _error("StackOverflowError", ""); }
  300. void IOError(const Str& msg) { _error("IOError", msg); }
  301. void NotImplementedError(){ _error("NotImplementedError", ""); }
  302. void TypeError(const Str& msg){ _error("TypeError", msg); }
  303. void IndexError(const Str& msg){ _error("IndexError", msg); }
  304. void ValueError(const Str& msg){ _error("ValueError", msg); }
  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 AttributeError(PyObject* obj, StrName name){
  310. // OBJ_NAME calls getattr, which may lead to a infinite recursion
  311. _error("AttributeError", fmt("type ", OBJ_NAME(_t(obj)).escape(), " has no attribute ", name.escape()));
  312. }
  313. void AttributeError(Str msg){ _error("AttributeError", msg); }
  314. void check_type(PyObject* obj, Type type){
  315. if(is_type(obj, type)) return;
  316. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", got " + OBJ_NAME(_t(obj)).escape());
  317. }
  318. void check_args_size(int size, int min_size, int max_size){
  319. if(size >= min_size && size <= max_size) return;
  320. TypeError(fmt("expected ", min_size, "-", max_size, " arguments, got ", size));
  321. }
  322. void check_non_tagged_type(PyObject* obj, Type type){
  323. if(is_non_tagged_type(obj, type)) return;
  324. TypeError("expected " + OBJ_NAME(_t(type)).escape() + ", got " + OBJ_NAME(_t(obj)).escape());
  325. }
  326. void check_int(PyObject* obj){
  327. if(is_int(obj)) return;
  328. check_type(obj, tp_int); // if failed, redirect to check_type to raise TypeError
  329. }
  330. void check_int_or_float(PyObject* obj);
  331. PyObject* _t(Type t){
  332. return _all_types[t.index].obj;
  333. }
  334. PyObject* _t(PyObject* obj){
  335. if(is_int(obj)) return _t(tp_int);
  336. if(is_float(obj)) return _t(tp_float);
  337. return _all_types[obj->type].obj;
  338. }
  339. struct ImportContext{
  340. // 0: normal; 1: __init__.py; 2: relative
  341. std::vector<std::pair<StrName, int>> pending;
  342. struct Temp{
  343. VM* vm;
  344. StrName name;
  345. Temp(VM* vm, StrName name, int type): vm(vm), name(name){
  346. ImportContext* ctx = &vm->_import_context;
  347. ctx->pending.emplace_back(name, type);
  348. }
  349. ~Temp(){
  350. ImportContext* ctx = &vm->_import_context;
  351. ctx->pending.pop_back();
  352. }
  353. };
  354. Temp temp(VM* vm, StrName name, int type){
  355. return Temp(vm, name, type);
  356. }
  357. };
  358. ImportContext _import_context;
  359. PyObject* py_import(StrName name, bool relative=false);
  360. ~VM();
  361. #if PK_DEBUG_CEVAL_STEP
  362. void _log_s_data(const char* title = nullptr);
  363. #endif
  364. void _unpack_as_list(ArgsView args, List& list);
  365. void _unpack_as_dict(ArgsView args, Dict& dict);
  366. PyObject* vectorcall(int ARGC, int KWARGC=0, bool op_call=false);
  367. CodeObject_ compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope=false);
  368. PyObject* py_negate(PyObject* obj);
  369. bool py_bool(PyObject* obj);
  370. i64 py_hash(PyObject* obj);
  371. PyObject* py_list(PyObject*);
  372. PyObject* new_module(StrName name);
  373. Str disassemble(CodeObject_ co);
  374. void init_builtin_types();
  375. PyObject* getattr(PyObject* obj, StrName name, bool throw_err=true);
  376. PyObject* get_unbound_method(PyObject* obj, StrName name, PyObject** self, bool throw_err=true, bool fallback=false);
  377. void parse_int_slice(const Slice& s, int length, int& start, int& stop, int& step);
  378. PyObject* format(Str, PyObject*);
  379. void setattr(PyObject* obj, StrName name, PyObject* value);
  380. template<int ARGC>
  381. PyObject* bind_method(PyObject*, Str, NativeFuncC);
  382. template<int ARGC>
  383. PyObject* bind_func(PyObject*, Str, NativeFuncC);
  384. void _error(Exception);
  385. PyObject* _run_top_frame();
  386. void post_init();
  387. PyObject* _py_generator(Frame&& frame, ArgsView buffer);
  388. void _prepare_py_call(PyObject**, ArgsView, ArgsView, const FuncDecl_&);
  389. // new style binding api
  390. PyObject* bind(PyObject*, const char*, const char*, NativeFuncC, UserData userdata={});
  391. PyObject* bind(PyObject*, const char*, NativeFuncC, UserData userdata={});
  392. PyObject* bind_property(PyObject*, Str, NativeFuncC fget, NativeFuncC fset=nullptr);
  393. };
  394. DEF_NATIVE_2(Str, tp_str)
  395. DEF_NATIVE_2(List, tp_list)
  396. DEF_NATIVE_2(Tuple, tp_tuple)
  397. DEF_NATIVE_2(Function, tp_function)
  398. DEF_NATIVE_2(NativeFunc, tp_native_func)
  399. DEF_NATIVE_2(BoundMethod, tp_bound_method)
  400. DEF_NATIVE_2(Range, tp_range)
  401. DEF_NATIVE_2(Slice, tp_slice)
  402. DEF_NATIVE_2(Exception, tp_exception)
  403. DEF_NATIVE_2(Bytes, tp_bytes)
  404. DEF_NATIVE_2(MappingProxy, tp_mappingproxy)
  405. DEF_NATIVE_2(Dict, tp_dict)
  406. DEF_NATIVE_2(Property, tp_property)
  407. DEF_NATIVE_2(StarWrapper, tp_star_wrapper)
  408. #undef DEF_NATIVE_2
  409. #define PY_CAST_INT(T) \
  410. template<> inline T py_cast<T>(VM* vm, PyObject* obj){ \
  411. vm->check_int(obj); \
  412. return (T)(PK_BITS(obj) >> 2); \
  413. } \
  414. template<> inline T _py_cast<T>(VM* vm, PyObject* obj){ \
  415. PK_UNUSED(vm); \
  416. return (T)(PK_BITS(obj) >> 2); \
  417. }
  418. PY_CAST_INT(char)
  419. PY_CAST_INT(short)
  420. PY_CAST_INT(int)
  421. PY_CAST_INT(long)
  422. PY_CAST_INT(long long)
  423. PY_CAST_INT(unsigned char)
  424. PY_CAST_INT(unsigned short)
  425. PY_CAST_INT(unsigned int)
  426. PY_CAST_INT(unsigned long)
  427. PY_CAST_INT(unsigned long long)
  428. template<> inline float py_cast<float>(VM* vm, PyObject* obj){
  429. if(is_float(obj)){
  430. i64 bits = PK_BITS(obj) & Number::c1;
  431. return BitsCvt(bits)._float;
  432. }
  433. if(is_int(obj)){
  434. return (float)_py_cast<i64>(vm, obj);
  435. }
  436. vm->check_int_or_float(obj); // error!
  437. return 0;
  438. }
  439. template<> inline float _py_cast<float>(VM* vm, PyObject* obj){
  440. return py_cast<float>(vm, obj);
  441. }
  442. template<> inline double py_cast<double>(VM* vm, PyObject* obj){
  443. if(is_float(obj)){
  444. i64 bits = PK_BITS(obj) & Number::c1;
  445. return BitsCvt(bits)._float;
  446. }
  447. if(is_int(obj)){
  448. return (float)_py_cast<i64>(vm, obj);
  449. }
  450. vm->check_int_or_float(obj); // error!
  451. return 0;
  452. }
  453. template<> inline double _py_cast<double>(VM* vm, PyObject* obj){
  454. return py_cast<double>(vm, obj);
  455. }
  456. #define PY_VAR_INT(T) \
  457. inline PyObject* py_var(VM* vm, T _val){ \
  458. i64 val = static_cast<i64>(_val); \
  459. if(((val << 2) >> 2) != val){ \
  460. vm->_error("OverflowError", std::to_string(val) + " is out of range"); \
  461. } \
  462. val = (val << 2) | 0b01; \
  463. return reinterpret_cast<PyObject*>(val); \
  464. }
  465. PY_VAR_INT(char)
  466. PY_VAR_INT(short)
  467. PY_VAR_INT(int)
  468. PY_VAR_INT(long)
  469. PY_VAR_INT(long long)
  470. PY_VAR_INT(unsigned char)
  471. PY_VAR_INT(unsigned short)
  472. PY_VAR_INT(unsigned int)
  473. PY_VAR_INT(unsigned long)
  474. PY_VAR_INT(unsigned long long)
  475. #define PY_VAR_FLOAT(T) \
  476. inline PyObject* py_var(VM* vm, T _val){ \
  477. PK_UNUSED(vm); \
  478. BitsCvt val(static_cast<f64>(_val)); \
  479. i64 bits = val._int & Number::c1; \
  480. i64 tail = val._int & Number::c2; \
  481. if(tail == 0b10){ \
  482. if(bits&0b100) bits += 0b100; \
  483. }else if(tail == 0b11){ \
  484. bits += 0b100; \
  485. } \
  486. bits |= 0b10; \
  487. return reinterpret_cast<PyObject*>(bits); \
  488. }
  489. PY_VAR_FLOAT(float)
  490. PY_VAR_FLOAT(double)
  491. #undef PY_VAR_INT
  492. #undef PY_VAR_FLOAT
  493. inline PyObject* py_var(VM* vm, bool val){
  494. return val ? vm->True : vm->False;
  495. }
  496. template<> inline bool py_cast<bool>(VM* vm, PyObject* obj){
  497. if(obj == vm->True) return true;
  498. if(obj == vm->False) return false;
  499. vm->check_non_tagged_type(obj, vm->tp_bool);
  500. return false;
  501. }
  502. template<> inline bool _py_cast<bool>(VM* vm, PyObject* obj){
  503. return obj == vm->True;
  504. }
  505. template<> inline CString py_cast<CString>(VM* vm, PyObject* obj){
  506. vm->check_non_tagged_type(obj, vm->tp_str);
  507. return PK_OBJ_GET(Str, obj).c_str();
  508. }
  509. template<> inline CString _py_cast<CString>(VM* vm, PyObject* obj){
  510. return PK_OBJ_GET(Str, obj).c_str();
  511. }
  512. inline PyObject* py_var(VM* vm, const char val[]){
  513. return VAR(Str(val));
  514. }
  515. inline PyObject* py_var(VM* vm, std::string val){
  516. return VAR(Str(std::move(val)));
  517. }
  518. inline PyObject* py_var(VM* vm, std::string_view val){
  519. return VAR(Str(val));
  520. }
  521. inline PyObject* py_var(VM* vm, NoReturn val){
  522. PK_UNUSED(val);
  523. return vm->None;
  524. }
  525. inline PyObject* py_var(VM* vm, PyObject* val){
  526. PK_UNUSED(vm);
  527. return val;
  528. }
  529. template<int ARGC>
  530. PyObject* VM::bind_method(PyObject* obj, Str name, NativeFuncC fn) {
  531. check_non_tagged_type(obj, tp_type);
  532. PyObject* nf = VAR(NativeFunc(fn, ARGC, true));
  533. obj->attr().set(name, nf);
  534. return nf;
  535. }
  536. template<int ARGC>
  537. PyObject* VM::bind_func(PyObject* obj, Str name, NativeFuncC fn) {
  538. PyObject* nf = VAR(NativeFunc(fn, ARGC, false));
  539. obj->attr().set(name, nf);
  540. return nf;
  541. }
  542. /***************************************************/
  543. template<typename T>
  544. PyObject* PyArrayGetItem(VM* vm, PyObject* obj, PyObject* index){
  545. static_assert(std::is_same_v<T, List> || std::is_same_v<T, Tuple>);
  546. const T& self = _CAST(T&, obj);
  547. if(is_non_tagged_type(index, vm->tp_slice)){
  548. const Slice& s = _CAST(Slice&, index);
  549. int start, stop, step;
  550. vm->parse_int_slice(s, self.size(), start, stop, step);
  551. List new_list;
  552. for(int i=start; step>0?i<stop:i>stop; i+=step) new_list.push_back(self[i]);
  553. return VAR(T(std::move(new_list)));
  554. }
  555. int i = CAST(int, index);
  556. i = vm->normalized_index(i, self.size());
  557. return self[i];
  558. }
  559. } // namespace pkpy