vm.h 23 KB

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