blueloveTH 3 years ago
parent
commit
1ad12abbe1
6 changed files with 189 additions and 194 deletions
  1. 24 24
      src/ceval.h
  2. 22 22
      src/cffi.h
  3. 1 1
      src/compiler.h
  4. 109 114
      src/pocketpy.h
  5. 1 1
      src/ref.h
  6. 32 32
      src/vm.h

+ 24 - 24
src/ceval.h

@@ -18,12 +18,12 @@ PyVar VM::run_frame(Frame* frame){
         case OP_LOAD_CONST: frame->push(frame->co->consts[byte.arg]); continue;
         case OP_LOAD_FUNCTION: {
             const PyVar obj = frame->co->consts[byte.arg];
-            Function f = py_cast_v<Function>(this, obj);  // copy
+            Function f = CAST_V(Function, obj);  // copy
             f._module = frame->_module;
-            frame->push(py_var(this, f));
+            frame->push(VAR(f));
         } continue;
         case OP_SETUP_CLOSURE: {
-            Function& f = py_cast<Function>(this, frame->top());    // reference
+            Function& f = CAST(Function, frame->top());    // reference
             f._closure = frame->_locals;
         } continue;
         case OP_LOAD_NAME_REF: {
@@ -70,7 +70,7 @@ PyVar VM::run_frame(Frame* frame){
             continue;
         case OP_BUILD_TUPLE: {
             Args items = frame->pop_n_values_reversed(this, byte.arg);
-            frame->push(py_var(this, std::move(items)));
+            frame->push(VAR(std::move(items)));
         } continue;
         case OP_BUILD_TUPLE_REF: {
             Args items = frame->pop_n_reversed(byte.arg);
@@ -79,13 +79,13 @@ PyVar VM::run_frame(Frame* frame){
         case OP_BUILD_STRING: {
             Args items = frame->pop_n_values_reversed(this, byte.arg);
             StrStream ss;
-            for(int i=0; i<items.size(); i++) ss << py_cast<Str>(this, asStr(items[i]));
-            frame->push(py_var(this, ss.str()));
+            for(int i=0; i<items.size(); i++) ss << CAST(Str, asStr(items[i]));
+            frame->push(VAR(ss.str()));
         } continue;
         case OP_LOAD_EVAL_FN: frame->push(builtins->attr(m_eval)); continue;
         case OP_LIST_APPEND: {
             PyVar obj = frame->pop_value(this);
-            List& list = py_cast<List>(this, frame->top_1());
+            List& list = CAST(List, frame->top_1());
             list.push_back(std::move(obj));
         } continue;
         case OP_BEGIN_CLASS: {
@@ -109,7 +109,7 @@ PyVar VM::run_frame(Frame* frame){
         case OP_RETURN_VALUE: return frame->pop_value(this);
         case OP_PRINT_EXPR: {
             const PyVar expr = frame->top_value(this);
-            if(expr != None) *_stdout << py_cast<Str>(this, asRepr(expr)) << '\n';
+            if(expr != None) *_stdout << CAST(Str, asRepr(expr)) << '\n';
         } continue;
         case OP_POP_TOP: frame->_pop(); continue;
         case OP_BINARY_OP: {
@@ -150,13 +150,13 @@ PyVar VM::run_frame(Frame* frame){
             PyVar rhs = frame->pop_value(this);
             bool ret_c = rhs == frame->top_value(this);
             if(byte.arg == 1) ret_c = !ret_c;
-            frame->top() = py_var(this, ret_c);
+            frame->top() = VAR(ret_c);
         } continue;
         case OP_CONTAINS_OP: {
             PyVar rhs = frame->pop_value(this);
-            bool ret_c = py_cast_v<bool>(this, call(rhs, __contains__, one_arg(frame->pop_value(this))));
+            bool ret_c = CAST_V(bool, call(rhs, __contains__, one_arg(frame->pop_value(this))));
             if(byte.arg == 1) ret_c = !ret_c;
-            frame->push(py_var(this, ret_c));
+            frame->push(VAR(ret_c));
         } continue;
         case OP_UNARY_NEGATIVE:
             frame->top() = num_negated(frame->top_value(this));
@@ -164,10 +164,10 @@ PyVar VM::run_frame(Frame* frame){
         case OP_UNARY_NOT: {
             PyVar obj = frame->pop_value(this);
             const PyVar& obj_bool = asBool(obj);
-            frame->push(py_var(this, !_py_cast_v<bool>(this, obj_bool)));
+            frame->push(VAR(!_CAST_V(bool, obj_bool)));
         } continue;
         case OP_POP_JUMP_IF_FALSE:
-            if(!_py_cast_v<bool>(this, asBool(frame->pop_value(this)))) frame->jump_abs(byte.arg);
+            if(!_CAST_V(bool, asBool(frame->pop_value(this)))) frame->jump_abs(byte.arg);
             continue;
         case OP_LOAD_NONE: frame->push(None); continue;
         case OP_LOAD_TRUE: frame->push(True); continue;
@@ -175,24 +175,24 @@ PyVar VM::run_frame(Frame* frame){
         case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); continue;
         case OP_ASSERT: {
             PyVar _msg = frame->pop_value(this);
-            Str msg = py_cast<Str>(this, asStr(_msg));
+            Str msg = CAST(Str, asStr(_msg));
             PyVar expr = frame->pop_value(this);
             if(asBool(expr) != True) _error("AssertionError", msg);
         } continue;
         case OP_EXCEPTION_MATCH: {
-            const auto& e = py_cast<Exception>(this, frame->top());
+            const auto& e = CAST(Exception, frame->top());
             StrName name = frame->co->names[byte.arg].first;
-            frame->push(py_var(this, e.match_type(name)));
+            frame->push(VAR(e.match_type(name)));
         } continue;
         case OP_RAISE: {
             PyVar obj = frame->pop_value(this);
-            Str msg = obj == None ? "" : py_cast<Str>(this, asStr(obj));
+            Str msg = obj == None ? "" : CAST(Str, asStr(obj));
             StrName type = frame->co->names[byte.arg].first;
             _error(type, msg);
         } continue;
         case OP_RE_RAISE: _raise(); continue;
         case OP_BUILD_LIST:
-            frame->push(py_var(this, frame->pop_n_values_reversed(this, byte.arg).move_to_list()));
+            frame->push(VAR(frame->pop_n_values_reversed(this, byte.arg).move_to_list()));
             continue;
         case OP_BUILD_MAP: {
             Args items = frame->pop_n_values_reversed(this, byte.arg*2);
@@ -203,7 +203,7 @@ PyVar VM::run_frame(Frame* frame){
             frame->push(obj);
         } continue;
         case OP_BUILD_SET: {
-            PyVar list = py_var(this, 
+            PyVar list = VAR(
                 frame->pop_n_values_reversed(this, byte.arg).move_to_list()
             );
             PyVar obj = call(builtins->attr("set"), one_arg(list));
@@ -212,10 +212,10 @@ PyVar VM::run_frame(Frame* frame){
         case OP_DUP_TOP_VALUE: frame->push(frame->top_value(this)); continue;
         case OP_UNARY_STAR: {
             if(byte.arg > 0){   // rvalue
-                frame->top() = py_var(this, StarWrapper(frame->top_value(this), true));
+                frame->top() = VAR(StarWrapper(frame->top_value(this), true));
             }else{
                 PyRef_AS_C(frame->top()); // check ref
-                frame->top() = py_var(this, StarWrapper(frame->top(), false));
+                frame->top() = VAR(StarWrapper(frame->top(), false));
             }
         } continue;
         case OP_CALL_KWARGS_UNPACK: case OP_CALL_KWARGS: {
@@ -284,9 +284,9 @@ PyVar VM::run_frame(Frame* frame){
             PyVar stop = frame->pop_value(this);
             PyVar start = frame->pop_value(this);
             Slice s;
-            if(start != None) { s.start = (int)py_cast_v<i64>(this, start);}
-            if(stop != None) { s.stop = (int)py_cast_v<i64>(this, stop);}
-            frame->push(py_var(this, s));
+            if(start != None) { s.start = (int)CAST_V(i64, start);}
+            if(stop != None) { s.stop = (int)CAST_V(i64, stop);}
+            frame->push(VAR(s));
         } continue;
         case OP_IMPORT_NAME: {
             StrName name = frame->co->names[byte.arg].first;

+ 22 - 22
src/cffi.h

@@ -78,12 +78,12 @@ struct Pointer{
 
         vm->bind_method<1>(type, "__add__", [](VM* vm, Args& args) {
             Pointer& self = vm->_cast<Pointer>(args[0]);
-            return vm->new_object<Pointer>(self + py_cast<i64>(vm, args[1]));
+            return vm->new_object<Pointer>(self + CAST(i64, args[1]));
         });
 
         vm->bind_method<1>(type, "__sub__", [](VM* vm, Args& args) {
             Pointer& self = vm->_cast<Pointer>(args[0]);
-            return vm->new_object<Pointer>(self - py_cast_v<i64>(vm, args[1]));
+            return vm->new_object<Pointer>(self - CAST_V(i64, args[1]));
         });
 
         vm->bind_method<1>(type, "__eq__", [](VM* vm, Args& args) {
@@ -101,13 +101,13 @@ struct Pointer{
         // https://docs.python.org/zh-cn/3/library/ctypes.html
         vm->bind_method<1>(type, "__getitem__", [](VM* vm, Args& args) {
             Pointer& self = vm->_cast<Pointer>(args[0]);
-            i64 index = py_cast_v<i64>(vm, args[1]);
+            i64 index = CAST_V(i64, args[1]);
             return (self+index).get(vm);
         });
 
         vm->bind_method<2>(type, "__setitem__", [](VM* vm, Args& args) {
             Pointer& self = vm->_cast<Pointer>(args[0]);
-            i64 index = py_cast_v<i64>(vm, args[1]);
+            i64 index = CAST_V(i64, args[1]);
             (self+index).set(vm, args[2]);
             return vm->None;
         });
@@ -164,20 +164,20 @@ struct Pointer{
 
     void set(VM* vm, const PyVar& val){
         switch(ctype.index){
-            case C_TYPE("char_"): ref<char>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("int_"): ref<int>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("float_"): ref<float>() = py_cast_v<f64>(vm, val); break;
-            case C_TYPE("double_"): ref<double>() = py_cast_v<f64>(vm, val); break;
-            case C_TYPE("bool_"): ref<bool>() = py_cast_v<bool>(vm, val); break;
+            case C_TYPE("char_"): ref<char>() = CAST_V(i64, val); break;
+            case C_TYPE("int_"): ref<int>() = CAST_V(i64, val); break;
+            case C_TYPE("float_"): ref<float>() = CAST_V(f64, val); break;
+            case C_TYPE("double_"): ref<double>() = CAST_V(f64, val); break;
+            case C_TYPE("bool_"): ref<bool>() = CAST_V(bool, val); break;
             case C_TYPE("void_"): vm->ValueError("cannot set void*"); break;
-            case C_TYPE("int8_"): ref<int8_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("int16_"): ref<int16_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("int32_"): ref<int32_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("int64_"): ref<int64_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("uint8_"): ref<uint8_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("uint16_"): ref<uint16_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("uint32_"): ref<uint32_t>() = py_cast_v<i64>(vm, val); break;
-            case C_TYPE("uint64_"): ref<uint64_t>() = py_cast_v<i64>(vm, val); break;
+            case C_TYPE("int8_"): ref<int8_t>() = CAST_V(i64, val); break;
+            case C_TYPE("int16_"): ref<int16_t>() = CAST_V(i64, val); break;
+            case C_TYPE("int32_"): ref<int32_t>() = CAST_V(i64, val); break;
+            case C_TYPE("int64_"): ref<int64_t>() = CAST_V(i64, val); break;
+            case C_TYPE("uint8_"): ref<uint8_t>() = CAST_V(i64, val); break;
+            case C_TYPE("uint16_"): ref<uint16_t>() = CAST_V(i64, val); break;
+            case C_TYPE("uint32_"): ref<uint32_t>() = CAST_V(i64, val); break;
+            case C_TYPE("uint64_"): ref<uint64_t>() = CAST_V(i64, val); break;
             case C_TYPE("void_p_"): ref<void*>() = vm->_cast<Pointer>(val).ptr; break;
             // use macro here to do extension
             default: UNREACHABLE();
@@ -262,7 +262,7 @@ void add_module_c(VM* vm){
     vm->setattr(mod, "nullptr", vm->new_object<Pointer>(nullptr, C_TYPE_T("void_")));
 
     vm->bind_func<1>(mod, "malloc", [](VM* vm, Args& args) {
-        i64 size = py_cast_v<i64>(vm, args[0]);
+        i64 size = CAST_V(i64, args[0]);
         return vm->new_object<Pointer>(malloc(size), C_TYPE_T("void_"));
     });
 
@@ -280,22 +280,22 @@ void add_module_c(VM* vm){
     vm->bind_func<3>(mod, "memcpy", [](VM* vm, Args& args) {
         Pointer& dst = vm->_cast<Pointer>(args[0]);
         Pointer& src = vm->_cast<Pointer>(args[1]);
-        i64 size = py_cast_v<i64>(vm, args[2]);
+        i64 size = CAST_V(i64, args[2]);
         memcpy(dst.ptr, src.ptr, size);
         return vm->None;
     });
 
     vm->bind_func<3>(mod, "memset", [](VM* vm, Args& args) {
         Pointer& dst = vm->_cast<Pointer>(args[0]);
-        i64 val = py_cast_v<i64>(vm, args[1]);
-        i64 size = py_cast_v<i64>(vm, args[2]);
+        i64 val = CAST_V(i64, args[1]);
+        i64 size = CAST_V(i64, args[2]);
         memset(dst.ptr, (int)val, size);
         return vm->None;
     });
 
     vm->bind_func<1>(mod, "strdup", [ptr_t](VM* vm, Args& args) {
         if(is_type(args[0], vm->tp_str)){
-            const Str& s = py_cast<Str>(vm, args[0]);
+            const Str& s = CAST(Str, args[0]);
             return vm->new_object<Pointer>(strdup(s.c_str()), C_TYPE_T("char_"));
         }else if(is_type(args[0], OBJ_GET(Type, ptr_t))){
             Pointer& p = vm->_cast<Pointer>(args[0]);

+ 1 - 1
src/compiler.h

@@ -360,7 +360,7 @@ private:
     void exprFString() {
         static const std::regex pattern(R"(\{(.*?)\})");
         PyVar value = parser->prev.value;
-        Str s = py_cast<Str>(vm, value);
+        Str s = CAST(Str, value);
         std::sregex_iterator begin(s.begin(), s.end(), pattern);
         std::sregex_iterator end;
         int size = 0;

+ 109 - 114
src/pocketpy.h

@@ -22,7 +22,7 @@ CodeObject_ VM::compile(Str source, Str filename, CompileMode mode) {
 #define BIND_NUM_ARITH_OPT(name, op)                                                                    \
     _vm->_bind_methods<1>({"int","float"}, #name, [](VM* vm, Args& args){                         \
         if(is_both_int(args[0], args[1])){                                                              \
-            return VAR(_py_cast_v<i64>(vm, args[0]) op _py_cast_v<i64>(vm, args[1]));                     \
+            return VAR(_CAST_V(i64, args[0]) op _CAST_V(i64, args[1]));                     \
         }else{                                                                                          \
             return VAR(vm->num_to_float(args[0]) op vm->num_to_float(args[1]));                 \
         }                                                                                               \
@@ -35,7 +35,7 @@ CodeObject_ VM::compile(Str source, Str filename, CompileMode mode) {
             vm->TypeError("unsupported operand type(s) for " #op );                                     \
         }                                                                                               \
         if(is_both_int(args[0], args[1]))                                                               \
-            return VAR(_py_cast_v<i64>(vm, args[0]) op _py_cast_v<i64>(vm, args[1]));                    \
+            return VAR(_CAST_V(i64, args[0]) op _CAST_V(i64, args[1]));                    \
         return VAR(vm->num_to_float(args[0]) op vm->num_to_float(args[1]));                      \
     });
     
@@ -56,15 +56,10 @@ void init_builtins(VM* _vm) {
 #undef BIND_NUM_LOGICAL_OPT
 
     _vm->bind_builtin_func<1>("__sys_stdout_write", [](VM* vm, Args& args) {
-        (*vm->_stdout) << py_cast<Str>(vm, args[0]);
+        (*vm->_stdout) << CAST(Str, args[0]);
         return vm->None;
     });
 
-    // _vm->bind_builtin_func<1>("test", [](VM* vm, Args& args) {
-    //     args[0]->attr().print_stats();
-    //     return vm->None;
-    // });
-
     _vm->bind_builtin_func<0>("super", [](VM* vm, Args& args) {
         const PyVar* self = vm->top_frame()->f_locals().try_get(m_self);
         if(self == nullptr) vm->TypeError("super() can only be called in a class");
@@ -78,19 +73,19 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_builtin_func<1>("eval", [](VM* vm, Args& args) {
-        CodeObject_ code = vm->compile(py_cast<Str>(vm, args[0]), "<eval>", EVAL_MODE);
+        CodeObject_ code = vm->compile(CAST(Str, args[0]), "<eval>", EVAL_MODE);
         return vm->_exec(code, vm->top_frame()->_module, vm->top_frame()->_locals);
     });
 
     _vm->bind_builtin_func<1>("exec", [](VM* vm, Args& args) {
-        CodeObject_ code = vm->compile(py_cast<Str>(vm, args[0]), "<exec>", EXEC_MODE);
+        CodeObject_ code = vm->compile(CAST(Str, args[0]), "<exec>", EXEC_MODE);
         vm->_exec(code, vm->top_frame()->_module, vm->top_frame()->_locals);
         return vm->None;
     });
 
     _vm->bind_builtin_func<-1>("exit", [](VM* vm, Args& args) {
         if(args.size() == 0) std::exit(0);
-        else if(args.size() == 1) std::exit((int)py_cast_v<i64>(vm, args[0]));
+        else if(args.size() == 1) std::exit((int)CAST_V(i64, args[0]));
         else vm->TypeError("exit() takes at most 1 argument");
         return vm->None;
     });
@@ -105,34 +100,34 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_builtin_func<1>("chr", [](VM* vm, Args& args) {
-        i64 i = py_cast_v<i64>(vm, args[0]);
+        i64 i = CAST_V(i64, args[0]);
         if (i < 0 || i > 128) vm->ValueError("chr() arg not in range(128)");
         return VAR(std::string(1, (char)i));
     });
 
     _vm->bind_builtin_func<1>("ord", [](VM* vm, Args& args) {
-        Str s = py_cast<Str>(vm, args[0]);
+        Str s = CAST(Str, args[0]);
         if (s.size() != 1) vm->TypeError("ord() expected an ASCII character");
         return VAR((i64)(s.c_str()[0]));
     });
 
     _vm->bind_builtin_func<2>("hasattr", [](VM* vm, Args& args) {
-        return VAR(vm->getattr(args[0], py_cast<Str>(vm, args[1]), false) != nullptr);
+        return VAR(vm->getattr(args[0], CAST(Str, args[1]), false) != nullptr);
     });
 
     _vm->bind_builtin_func<3>("setattr", [](VM* vm, Args& args) {
-        vm->setattr(args[0], py_cast<Str>(vm, args[1]), args[2]);
+        vm->setattr(args[0], CAST(Str, args[1]), args[2]);
         return vm->None;
     });
 
     _vm->bind_builtin_func<2>("getattr", [](VM* vm, Args& args) {
-        Str name = py_cast<Str>(vm, args[1]);
+        Str name = CAST(Str, args[1]);
         return vm->getattr(args[0], name);
     });
 
     _vm->bind_builtin_func<1>("hex", [](VM* vm, Args& args) {
         std::stringstream ss;
-        ss << std::hex << py_cast_v<i64>(vm, args[0]);
+        ss << std::hex << CAST_V(i64, args[0]);
         return VAR("0x" + ss.str());
     });
 
@@ -167,9 +162,9 @@ void init_builtins(VM* _vm) {
     _vm->bind_static_method<-1>("range", "__new__", [](VM* vm, Args& args) {
         Range r;
         switch (args.size()) {
-            case 1: r.stop = py_cast_v<i64>(vm, args[0]); break;
-            case 2: r.start = py_cast_v<i64>(vm, args[0]); r.stop = py_cast_v<i64>(vm, args[1]); break;
-            case 3: r.start = py_cast_v<i64>(vm, args[0]); r.stop = py_cast_v<i64>(vm, args[1]); r.step = py_cast_v<i64>(vm, args[2]); break;
+            case 1: r.stop = CAST_V(i64, args[0]); break;
+            case 2: r.start = CAST_V(i64, args[0]); r.stop = CAST_V(i64, args[1]); break;
+            case 3: r.start = CAST_V(i64, args[0]); r.stop = CAST_V(i64, args[1]); r.step = CAST_V(i64, args[2]); break;
             default: vm->TypeError("expected 1-3 arguments, but got " + std::to_string(args.size()));
         }
         return VAR(r);
@@ -190,8 +185,8 @@ void init_builtins(VM* _vm) {
 
     _vm->_bind_methods<1>({"int", "float"}, "__pow__", [](VM* vm, Args& args) {
         if(is_both_int(args[0], args[1])){
-            i64 lhs = _py_cast_v<i64>(vm, args[0]);
-            i64 rhs = _py_cast_v<i64>(vm, args[1]);
+            i64 lhs = _CAST_V(i64, args[0]);
+            i64 rhs = _CAST_V(i64, args[1]);
             bool flag = false;
             if(rhs < 0) {flag = true; rhs = -rhs;}
             i64 ret = 1;
@@ -210,10 +205,10 @@ void init_builtins(VM* _vm) {
     /************ PyInt ************/
     _vm->bind_static_method<1>("int", "__new__", [](VM* vm, Args& args) {
         if (is_type(args[0], vm->tp_int)) return args[0];
-        if (is_type(args[0], vm->tp_float)) return VAR((i64)py_cast_v<f64>(vm, args[0]));
-        if (is_type(args[0], vm->tp_bool)) return VAR(_py_cast_v<bool>(vm, args[0]) ? 1 : 0);
+        if (is_type(args[0], vm->tp_float)) return VAR((i64)CAST_V(f64, args[0]));
+        if (is_type(args[0], vm->tp_bool)) return VAR(_CAST_V(bool, args[0]) ? 1 : 0);
         if (is_type(args[0], vm->tp_str)) {
-            const Str& s = py_cast<Str>(vm, args[0]);
+            const Str& s = CAST(Str, args[0]);
             try{
                 size_t parsed = 0;
                 i64 val = S_TO_INT(s, &parsed, 10);
@@ -228,22 +223,22 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<1>("int", "__floordiv__", [](VM* vm, Args& args) {
-        i64 rhs = py_cast_v<i64>(vm, args[1]);
+        i64 rhs = CAST_V(i64, args[1]);
         if(rhs == 0) vm->ZeroDivisionError();
-        return VAR(py_cast_v<i64>(vm, args[0]) / rhs);
+        return VAR(CAST_V(i64, args[0]) / rhs);
     });
 
     _vm->bind_method<1>("int", "__mod__", [](VM* vm, Args& args) {
-        i64 rhs = py_cast_v<i64>(vm, args[1]);
+        i64 rhs = CAST_V(i64, args[1]);
         if(rhs == 0) vm->ZeroDivisionError();
-        return VAR(py_cast_v<i64>(vm, args[0]) % rhs);
+        return VAR(CAST_V(i64, args[0]) % rhs);
     });
 
-    _vm->bind_method<0>("int", "__repr__", CPP_LAMBDA(VAR(std::to_string(py_cast_v<i64>(vm, args[0])))));
-    _vm->bind_method<0>("int", "__json__", CPP_LAMBDA(VAR(std::to_string(py_cast_v<i64>(vm, args[0])))));
+    _vm->bind_method<0>("int", "__repr__", CPP_LAMBDA(VAR(std::to_string(CAST_V(i64, args[0])))));
+    _vm->bind_method<0>("int", "__json__", CPP_LAMBDA(VAR(std::to_string(CAST_V(i64, args[0])))));
 
 #define INT_BITWISE_OP(name,op) \
-    _vm->bind_method<1>("int", #name, CPP_LAMBDA(VAR(py_cast_v<i64>(vm, args[0]) op py_cast_v<i64>(vm, args[1]))));
+    _vm->bind_method<1>("int", #name, CPP_LAMBDA(VAR(CAST_V(i64, args[0]) op CAST_V(i64, args[1]))));
 
     INT_BITWISE_OP(__lshift__, <<)
     INT_BITWISE_OP(__rshift__, >>)
@@ -255,11 +250,11 @@ void init_builtins(VM* _vm) {
 
     /************ PyFloat ************/
     _vm->bind_static_method<1>("float", "__new__", [](VM* vm, Args& args) {
-        if (is_type(args[0], vm->tp_int)) return VAR((f64)py_cast_v<i64>(vm, args[0]));
+        if (is_type(args[0], vm->tp_int)) return VAR((f64)CAST_V(i64, args[0]));
         if (is_type(args[0], vm->tp_float)) return args[0];
-        if (is_type(args[0], vm->tp_bool)) return VAR(_py_cast_v<bool>(vm, args[0]) ? 1.0 : 0.0);
+        if (is_type(args[0], vm->tp_bool)) return VAR(_CAST_V(bool, args[0]) ? 1.0 : 0.0);
         if (is_type(args[0], vm->tp_str)) {
-            const Str& s = py_cast<Str>(vm, args[0]);
+            const Str& s = CAST(Str, args[0]);
             if(s == "inf") return VAR(INFINITY);
             if(s == "-inf") return VAR(-INFINITY);
             try{
@@ -274,7 +269,7 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<0>("float", "__repr__", [](VM* vm, Args& args) {
-        f64 val = py_cast_v<f64>(vm, args[0]);
+        f64 val = CAST_V(f64, args[0]);
         if(std::isinf(val) || std::isnan(val)) return VAR(std::to_string(val));
         StrStream ss;
         ss << std::setprecision(std::numeric_limits<f64>::max_digits10-1-2) << val;
@@ -284,7 +279,7 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<0>("float", "__json__", [](VM* vm, Args& args) {
-        f64 val = py_cast_v<f64>(vm, args[0]);
+        f64 val = CAST_V(f64, args[0]);
         if(std::isinf(val) || std::isnan(val)) vm->ValueError("cannot jsonify 'nan' or 'inf'");
         return VAR(std::to_string(val));
     });
@@ -293,19 +288,19 @@ void init_builtins(VM* _vm) {
     _vm->bind_static_method<1>("str", "__new__", CPP_LAMBDA(vm->asStr(args[0])));
 
     _vm->bind_method<1>("str", "__add__", [](VM* vm, Args& args) {
-        const Str& lhs = py_cast<Str>(vm, args[0]);
-        const Str& rhs = py_cast<Str>(vm, args[1]);
+        const Str& lhs = CAST(Str, args[0]);
+        const Str& rhs = CAST(Str, args[1]);
         return VAR(lhs + rhs);
     });
 
     _vm->bind_method<0>("str", "__len__", [](VM* vm, Args& args) {
-        const Str& self = py_cast<Str>(vm, args[0]);
+        const Str& self = CAST(Str, args[0]);
         return VAR(self.u8_length());
     });
 
     _vm->bind_method<1>("str", "__contains__", [](VM* vm, Args& args) {
-        const Str& self = py_cast<Str>(vm, args[0]);
-        const Str& other = py_cast<Str>(vm, args[1]);
+        const Str& self = CAST(Str, args[0]);
+        const Str& other = CAST(Str, args[1]);
         return VAR(self.find(other) != Str::npos);
     });
 
@@ -313,57 +308,57 @@ void init_builtins(VM* _vm) {
     _vm->bind_method<0>("str", "__iter__", CPP_LAMBDA(vm->PyIter(StringIter(vm, args[0]))));
 
     _vm->bind_method<0>("str", "__repr__", [](VM* vm, Args& args) {
-        const Str& _self = py_cast<Str>(vm, args[0]);
+        const Str& _self = CAST(Str, args[0]);
         return VAR(_self.escape(true));
     });
 
     _vm->bind_method<0>("str", "__json__", [](VM* vm, Args& args) {
-        const Str& _self = py_cast<Str>(vm, args[0]);
+        const Str& _self = CAST(Str, args[0]);
         return VAR(_self.escape(false));
     });
 
     _vm->bind_method<1>("str", "__eq__", [](VM* vm, Args& args) {
         if(is_type(args[0], vm->tp_str) && is_type(args[1], vm->tp_str))
-            return VAR(py_cast<Str>(vm, args[0]) == py_cast<Str>(vm, args[1]));
+            return VAR(CAST(Str, args[0]) == CAST(Str, args[1]));
         return VAR(args[0] == args[1]);
     });
 
     _vm->bind_method<1>("str", "__ne__", [](VM* vm, Args& args) {
         if(is_type(args[0], vm->tp_str) && is_type(args[1], vm->tp_str))
-            return VAR(py_cast<Str>(vm, args[0]) != py_cast<Str>(vm, args[1]));
+            return VAR(CAST(Str, args[0]) != CAST(Str, args[1]));
         return VAR(args[0] != args[1]);
     });
 
     _vm->bind_method<1>("str", "__getitem__", [](VM* vm, Args& args) {
-        const Str& self (py_cast<Str>(vm, args[0]));
+        const Str& self (CAST(Str, args[0]));
 
         if(is_type(args[1], vm->tp_slice)){
-            Slice s = _py_cast_v<Slice>(vm, args[1]);
+            Slice s = _CAST_V(Slice, args[1]);
             s.normalize(self.u8_length());
             return VAR(self.u8_substr(s.start, s.stop));
         }
 
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        int index = (int)CAST_V(i64, args[1]);
         index = vm->normalized_index(index, self.u8_length());
         return VAR(self.u8_getitem(index));
     });
 
     _vm->bind_method<1>("str", "__gt__", [](VM* vm, Args& args) {
-        const Str& self (py_cast<Str>(vm, args[0]));
-        const Str& obj (py_cast<Str>(vm, args[1]));
+        const Str& self (CAST(Str, args[0]));
+        const Str& obj (CAST(Str, args[1]));
         return VAR(self > obj);
     });
 
     _vm->bind_method<1>("str", "__lt__", [](VM* vm, Args& args) {
-        const Str& self (py_cast<Str>(vm, args[0]));
-        const Str& obj (py_cast<Str>(vm, args[1]));
+        const Str& self (CAST(Str, args[0]));
+        const Str& obj (CAST(Str, args[1]));
         return VAR(self < obj);
     });
 
     _vm->bind_method<2>("str", "replace", [](VM* vm, Args& args) {
-        const Str& _self = py_cast<Str>(vm, args[0]);
-        const Str& _old = py_cast<Str>(vm, args[1]);
-        const Str& _new = py_cast<Str>(vm, args[2]);
+        const Str& _self = CAST(Str, args[0]);
+        const Str& _old = CAST(Str, args[1]);
+        const Str& _new = CAST(Str, args[2]);
         Str _copy = _self;
         // replace all occurences of _old with _new in _copy
         size_t pos = 0;
@@ -375,45 +370,45 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<1>("str", "startswith", [](VM* vm, Args& args) {
-        const Str& _self = py_cast<Str>(vm, args[0]);
-        const Str& _prefix = py_cast<Str>(vm, args[1]);
+        const Str& _self = CAST(Str, args[0]);
+        const Str& _prefix = CAST(Str, args[1]);
         return VAR(_self.find(_prefix) == 0);
     });
 
     _vm->bind_method<1>("str", "endswith", [](VM* vm, Args& args) {
-        const Str& _self = py_cast<Str>(vm, args[0]);
-        const Str& _suffix = py_cast<Str>(vm, args[1]);
+        const Str& _self = CAST(Str, args[0]);
+        const Str& _suffix = CAST(Str, args[1]);
         return VAR(_self.rfind(_suffix) == _self.length() - _suffix.length());
     });
 
     _vm->bind_method<1>("str", "join", [](VM* vm, Args& args) {
-        const Str& self = py_cast<Str>(vm, args[0]);
+        const Str& self = CAST(Str, args[0]);
         StrStream ss;
         PyVar obj = vm->asList(args[1]);
-        const List& list = py_cast<List>(vm, obj);
+        const List& list = CAST(List, obj);
         for (int i = 0; i < list.size(); ++i) {
             if (i > 0) ss << self;
-            ss << py_cast<Str>(vm, list[i]);
+            ss << CAST(Str, list[i]);
         }
         return VAR(ss.str());
     });
 
     /************ PyList ************/
     _vm->bind_method<1>("list", "append", [](VM* vm, Args& args) {
-        List& self = py_cast<List>(vm, args[0]);
+        List& self = CAST(List, args[0]);
         self.push_back(args[1]);
         return vm->None;
     });
 
     _vm->bind_method<0>("list", "reverse", [](VM* vm, Args& args) {
-        List& self = py_cast<List>(vm, args[0]);
+        List& self = CAST(List, args[0]);
         std::reverse(self.begin(), self.end());
         return vm->None;
     });
 
     _vm->bind_method<1>("list", "__mul__", [](VM* vm, Args& args) {
-        const List& self = py_cast<List>(vm, args[0]);
-        int n = (int)py_cast_v<i64>(vm, args[1]);
+        const List& self = CAST(List, args[0]);
+        int n = (int)CAST_V(i64, args[1]);
         List result;
         result.reserve(self.size() * n);
         for(int i = 0; i < n; i++) result.insert(result.end(), self.begin(), self.end());
@@ -421,8 +416,8 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<2>("list", "insert", [](VM* vm, Args& args) {
-        List& self = py_cast<List>(vm, args[0]);
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        List& self = CAST(List, args[0]);
+        int index = (int)CAST_V(i64, args[1]);
         if(index < 0) index += self.size();
         if(index < 0) index = 0;
         if(index > self.size()) index = self.size();
@@ -431,22 +426,22 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<0>("list", "clear", [](VM* vm, Args& args) {
-        py_cast<List>(vm, args[0]).clear();
+        CAST(List, args[0]).clear();
         return vm->None;
     });
 
-    _vm->bind_method<0>("list", "copy", CPP_LAMBDA(VAR(py_cast<List>(vm, args[0]))));
+    _vm->bind_method<0>("list", "copy", CPP_LAMBDA(VAR(CAST(List, args[0]))));
 
     _vm->bind_method<1>("list", "__add__", [](VM* vm, Args& args) {
-        const List& self = py_cast<List>(vm, args[0]);
-        const List& obj = py_cast<List>(vm, args[1]);
+        const List& self = CAST(List, args[0]);
+        const List& obj = CAST(List, args[1]);
         List new_list = self;
         new_list.insert(new_list.end(), obj.begin(), obj.end());
         return VAR(new_list);
     });
 
     _vm->bind_method<0>("list", "__len__", [](VM* vm, Args& args) {
-        const List& self = py_cast<List>(vm, args[0]);
+        const List& self = CAST(List, args[0]);
         return VAR(self.size());
     });
 
@@ -455,32 +450,32 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<1>("list", "__getitem__", [](VM* vm, Args& args) {
-        const List& self = py_cast<List>(vm, args[0]);
+        const List& self = CAST(List, args[0]);
 
         if(is_type(args[1], vm->tp_slice)){
-            Slice s = _py_cast_v<Slice>(vm, args[1]);
+            Slice s = _CAST_V(Slice, args[1]);
             s.normalize(self.size());
             List new_list;
             for(size_t i = s.start; i < s.stop; i++) new_list.push_back(self[i]);
             return VAR(std::move(new_list));
         }
 
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        int index = (int)CAST_V(i64, args[1]);
         index = vm->normalized_index(index, self.size());
         return self[index];
     });
 
     _vm->bind_method<2>("list", "__setitem__", [](VM* vm, Args& args) {
-        List& self = py_cast<List>(vm, args[0]);
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        List& self = CAST(List, args[0]);
+        int index = (int)CAST_V(i64, args[1]);
         index = vm->normalized_index(index, self.size());
         self[index] = args[2];
         return vm->None;
     });
 
     _vm->bind_method<1>("list", "__delitem__", [](VM* vm, Args& args) {
-        List& self = py_cast<List>(vm, args[0]);
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        List& self = CAST(List, args[0]);
+        int index = (int)CAST_V(i64, args[1]);
         index = vm->normalized_index(index, self.size());
         self.erase(self.begin() + index);
         return vm->None;
@@ -488,7 +483,7 @@ void init_builtins(VM* _vm) {
 
     /************ PyTuple ************/
     _vm->bind_static_method<1>("tuple", "__new__", [](VM* vm, Args& args) {
-        List list = py_cast<List>(vm, vm->asList(args[0]));
+        List list = CAST(List, vm->asList(args[0]));
         return VAR(std::move(list));
     });
 
@@ -497,23 +492,23 @@ void init_builtins(VM* _vm) {
     });
 
     _vm->bind_method<1>("tuple", "__getitem__", [](VM* vm, Args& args) {
-        const Tuple& self = py_cast<Tuple>(vm, args[0]);
+        const Tuple& self = CAST(Tuple, args[0]);
 
         if(is_type(args[1], vm->tp_slice)){
-            Slice s = _py_cast_v<Slice>(vm, args[1]);
+            Slice s = _CAST_V(Slice, args[1]);
             s.normalize(self.size());
             List new_list;
             for(size_t i = s.start; i < s.stop; i++) new_list.push_back(self[i]);
             return VAR(std::move(new_list));
         }
 
-        int index = (int)py_cast_v<i64>(vm, args[1]);
+        int index = (int)CAST_V(i64, args[1]);
         index = vm->normalized_index(index, self.size());
         return self[index];
     });
 
     _vm->bind_method<0>("tuple", "__len__", [](VM* vm, Args& args) {
-        const Tuple& self = py_cast<Tuple>(vm, args[0]);
+        const Tuple& self = CAST(Tuple, args[0]);
         return VAR(self.size());
     });
 
@@ -521,18 +516,18 @@ void init_builtins(VM* _vm) {
     _vm->bind_static_method<1>("bool", "__new__", CPP_LAMBDA(vm->asBool(args[0])));
 
     _vm->bind_method<0>("bool", "__repr__", [](VM* vm, Args& args) {
-        bool val = py_cast_v<bool>(vm, args[0]);
+        bool val = CAST_V(bool, args[0]);
         return VAR(val ? "True" : "False");
     });
 
     _vm->bind_method<0>("bool", "__json__", [](VM* vm, Args& args) {
-        bool val = py_cast_v<bool>(vm, args[0]);
+        bool val = CAST_V(bool, args[0]);
         return VAR(val ? "true" : "false");
     });
 
     _vm->bind_method<1>("bool", "__xor__", [](VM* vm, Args& args) {
-        bool self = py_cast_v<bool>(vm, args[0]);
-        bool other = py_cast_v<bool>(vm, args[1]);
+        bool self = CAST_V(bool, args[0]);
+        bool other = CAST_V(bool, args[1]);
         return VAR(self ^ other);
     });
 
@@ -569,7 +564,7 @@ void add_module_sys(VM* vm){
     vm->bind_func<0>(mod, "getrecursionlimit", CPP_LAMBDA(VAR(vm->recursionlimit)));
 
     vm->bind_func<1>(mod, "setrecursionlimit", [](VM* vm, Args& args) {
-        vm->recursionlimit = (int)py_cast_v<i64>(vm, args[0]);
+        vm->recursionlimit = (int)CAST_V(i64, args[0]);
         return vm->None;
     });
 }
@@ -577,7 +572,7 @@ void add_module_sys(VM* vm){
 void add_module_json(VM* vm){
     PyVar mod = vm->new_module("json");
     vm->bind_func<1>(mod, "loads", [](VM* vm, Args& args) {
-        const Str& expr = py_cast<Str>(vm, args[0]);
+        const Str& expr = CAST(Str, args[0]);
         CodeObject_ code = vm->compile(expr, "<json>", JSON_MODE);
         return vm->_exec(code, vm->top_frame()->_module, vm->top_frame()->_locals);
     });
@@ -608,8 +603,8 @@ void add_module_dis(VM* vm){
     PyVar mod = vm->new_module("dis");
     vm->bind_func<1>(mod, "dis", [](VM* vm, Args& args) {
         PyVar f = args[0];
-        if(is_type(f, vm->tp_bound_method)) f = py_cast<BoundMethod>(vm, args[0]).method;
-        CodeObject_ code = py_cast<Function>(vm, f).code;
+        if(is_type(f, vm->tp_bound_method)) f = CAST(BoundMethod, args[0]).method;
+        CodeObject_ code = CAST(Function, f).code;
         (*vm->_stdout) << vm->disassemble(code);
         return vm->None;
     });
@@ -636,7 +631,7 @@ struct FileIO {
     static void _register(VM* vm, PyVar mod, PyVar type){
         vm->bind_static_method<2>(type, "__new__", [](VM* vm, Args& args){
             return vm->new_object<FileIO>(
-                vm, py_cast<Str>(vm, args[0]), py_cast<Str>(vm, args[1])
+                vm, CAST(Str, args[0]), CAST(Str, args[1])
             );
         });
 
@@ -649,7 +644,7 @@ struct FileIO {
 
         vm->bind_method<1>(type, "write", [](VM* vm, Args& args){
             FileIO& io = vm->_cast<FileIO>(args[0]);
-            io._fs << py_cast<Str>(vm, args[1]);
+            io._fs << CAST(Str, args[1]);
             return vm->None;
         });
 
@@ -698,7 +693,7 @@ struct ReMatch {
 
         vm->bind_method<1>(type, "group", [](VM* vm, Args& args) {
             auto& self = vm->_cast<ReMatch>(args[0]);
-            int index = (int)py_cast_v<i64>(vm, args[1]);
+            int index = (int)CAST_V(i64, args[1]);
             index = vm->normalized_index(index, self.m.size());
             return VAR(self.m[index].str());
         });
@@ -722,28 +717,28 @@ void add_module_re(VM* vm){
     vm->register_class<ReMatch>(mod);
 
     vm->bind_func<2>(mod, "match", [](VM* vm, Args& args) {
-        const Str& pattern = py_cast<Str>(vm, args[0]);
-        const Str& string = py_cast<Str>(vm, args[1]);
+        const Str& pattern = CAST(Str, args[0]);
+        const Str& string = CAST(Str, args[1]);
         return _regex_search(pattern, string, true, vm);
     });
 
     vm->bind_func<2>(mod, "search", [](VM* vm, Args& args) {
-        const Str& pattern = py_cast<Str>(vm, args[0]);
-        const Str& string = py_cast<Str>(vm, args[1]);
+        const Str& pattern = CAST(Str, args[0]);
+        const Str& string = CAST(Str, args[1]);
         return _regex_search(pattern, string, false, vm);
     });
 
     vm->bind_func<3>(mod, "sub", [](VM* vm, Args& args) {
-        const Str& pattern = py_cast<Str>(vm, args[0]);
-        const Str& repl = py_cast<Str>(vm, args[1]);
-        const Str& string = py_cast<Str>(vm, args[2]);
+        const Str& pattern = CAST(Str, args[0]);
+        const Str& repl = CAST(Str, args[1]);
+        const Str& string = CAST(Str, args[2]);
         std::regex re(pattern);
         return VAR(std::regex_replace(string, re, repl));
     });
 
     vm->bind_func<2>(mod, "split", [](VM* vm, Args& args) {
-        const Str& pattern = py_cast<Str>(vm, args[0]);
-        const Str& string = py_cast<Str>(vm, args[1]);
+        const Str& pattern = CAST(Str, args[0]);
+        const Str& string = CAST(Str, args[1]);
         std::regex re(pattern);
         std::sregex_token_iterator it(string.begin(), string.end(), re, -1);
         std::sregex_token_iterator end;
@@ -759,21 +754,21 @@ void add_module_random(VM* vm){
     PyVar mod = vm->new_module("random");
     std::srand(std::time(0));
     vm->bind_func<1>(mod, "seed", [](VM* vm, Args& args) {
-        std::srand((unsigned int)py_cast_v<i64>(vm, args[0]));
+        std::srand((unsigned int)CAST_V(i64, args[0]));
         return vm->None;
     });
 
     vm->bind_func<0>(mod, "random", CPP_LAMBDA(VAR(std::rand() / (f64)RAND_MAX)));
     vm->bind_func<2>(mod, "randint", [](VM* vm, Args& args) {
-        i64 a = py_cast_v<i64>(vm, args[0]);
-        i64 b = py_cast_v<i64>(vm, args[1]);
+        i64 a = CAST_V(i64, args[0]);
+        i64 b = CAST_V(i64, args[1]);
         if(a > b) std::swap(a, b);
         return VAR(a + std::rand() % (b - a + 1));
     });
 
     vm->bind_func<2>(mod, "uniform", [](VM* vm, Args& args) {
-        f64 a = py_cast_v<f64>(vm, args[0]);
-        f64 b = py_cast_v<f64>(vm, args[1]);
+        f64 a = CAST_V(f64, args[0]);
+        f64 b = CAST_V(f64, args[1]);
         if(a > b) std::swap(a, b);
         return VAR(a + (b - a) * std::rand() / (f64)RAND_MAX);
     });
@@ -868,7 +863,7 @@ extern "C" {
         pkpy::PyVar* val = vm->_main->attr().try_get(name);
         if(val == nullptr) return nullptr;
         try{
-            pkpy::Str& _repr = pkpy::py_cast<pkpy::Str>(vm, vm->asRepr(*val));
+            pkpy::Str& _repr = pkpy::CAST(pkpy::Str, vm->asRepr(*val));
             return strdup(_repr.c_str());
         }catch(...){
             return nullptr;
@@ -884,7 +879,7 @@ extern "C" {
         pkpy::PyVarOrNull ret = vm->exec(source, "<eval>", pkpy::EVAL_MODE);
         if(ret == nullptr) return nullptr;
         try{
-            pkpy::Str& _repr = pkpy::py_cast<pkpy::Str>(vm, vm->asRepr(ret));
+            pkpy::Str& _repr = pkpy::CAST(pkpy::Str, vm->asRepr(ret));
             return strdup(_repr.c_str());
         }catch(...){
             return nullptr;
@@ -971,7 +966,7 @@ extern "C" {
             for(int i=0; i<args.size(); i++){
                 ss << ' ';
                 pkpy::PyVar x = vm->call(args[i], pkpy::__json__);
-                ss << pkpy::py_cast<pkpy::Str>(vm, x);
+                ss << pkpy::CAST(pkpy::Str, x);
             }
             char* packet = strdup(ss.str().c_str());
             switch(ret_code){

+ 1 - 1
src/ref.h

@@ -127,7 +127,7 @@ struct TupleRef : BaseRef {
         for(int i=0; i<objs.size(); i++){
             PyVarOrNull x;
             if(is_type(objs[i], vm->tp_star_wrapper)){
-                auto& star = _py_cast<StarWrapper>(vm, objs[i]);
+                auto& star = _CAST(StarWrapper, objs[i]);
                 if(star.rvalue) vm->ValueError("can't use starred expression here");
                 if(i != objs.size()-1) vm->ValueError("* can only be used at the end");
                 auto ref = vm->PyRef_AS_C(star.obj);

+ 32 - 32
src/vm.h

@@ -448,9 +448,9 @@ PyVar py_var(VM* vm, const char* val){
 
 PyVar VM::num_negated(const PyVar& obj){
     if (is_int(obj)){
-        return py_var(this, -py_cast_v<i64>(this, obj));
+        return VAR(-CAST_V(i64, obj));
     }else if(is_float(obj)){
-        return py_var(this, -py_cast_v<f64>(this, obj));
+        return VAR(-CAST_V(f64, obj));
     }
     TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
     return nullptr;
@@ -458,9 +458,9 @@ PyVar VM::num_negated(const PyVar& obj){
 
 f64 VM::num_to_float(const PyVar& obj){
     if(is_float(obj)){
-        return py_cast_v<f64>(this, obj);
+        return CAST_V(f64, obj);
     } else if (is_int(obj)){
-        return (f64)py_cast_v<i64>(this, obj);
+        return (f64)CAST_V(i64, obj);
     }
     TypeError("expected 'int' or 'float', got " + OBJ_NAME(_t(obj)).escape(true));
     return 0;
@@ -469,22 +469,22 @@ f64 VM::num_to_float(const PyVar& obj){
 const PyVar& VM::asBool(const PyVar& obj){
     if(is_type(obj, tp_bool)) return obj;
     if(obj == None) return False;
-    if(is_type(obj, tp_int)) return py_var(this, py_cast_v<i64>(this, obj) != 0);
-    if(is_type(obj, tp_float)) return py_var(this, py_cast_v<f64>(this, obj) != 0.0);
+    if(is_type(obj, tp_int)) return VAR(CAST_V(i64, obj) != 0);
+    if(is_type(obj, tp_float)) return VAR(CAST_V(f64, obj) != 0.0);
     PyVarOrNull len_fn = getattr(obj, __len__, false);
     if(len_fn != nullptr){
         PyVar ret = call(len_fn);
-        return py_var(this, py_cast_v<i64>(this, ret) > 0);
+        return VAR(CAST_V(i64, ret) > 0);
     }
     return True;
 }
 
 i64 VM::hash(const PyVar& obj){
-    if (is_type(obj, tp_str)) return py_cast<Str>(this, obj).hash();
-    if (is_int(obj)) return py_cast_v<i64>(this, obj);
+    if (is_type(obj, tp_str)) return CAST(Str, obj).hash();
+    if (is_int(obj)) return CAST_V(i64, obj);
     if (is_type(obj, tp_tuple)) {
         i64 x = 1000003;
-        const Tuple& items = py_cast<Tuple>(this, obj);
+        const Tuple& items = CAST(Tuple, obj);
         for (int i=0; i<items.size(); i++) {
             i64 y = hash(items[i]);
             x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2)); // recommended by Github Copilot
@@ -492,9 +492,9 @@ i64 VM::hash(const PyVar& obj){
         return x;
     }
     if (is_type(obj, tp_type)) return obj.bits;
-    if (is_type(obj, tp_bool)) return _py_cast_v<bool>(this, obj) ? 1 : 0;
+    if (is_type(obj, tp_bool)) return _CAST_V(bool, obj) ? 1 : 0;
     if (is_float(obj)){
-        f64 val = py_cast_v<f64>(this, obj);
+        f64 val = CAST_V(f64, obj);
         return (i64)std::hash<f64>()(val);
     }
     TypeError("unhashable type: " +  OBJ_NAME(_t(obj)).escape(true));
@@ -502,7 +502,7 @@ i64 VM::hash(const PyVar& obj){
 }
 
 PyVar VM::asRepr(const PyVar& obj){
-    if(is_type(obj, tp_type)) return py_var(this, "<class '" + OBJ_GET(Str, obj->attr(__name__)) + "'>");
+    if(is_type(obj, tp_type)) return VAR("<class '" + OBJ_GET(Str, obj->attr(__name__)) + "'>");
     return call(obj, __repr__);
 }
 
@@ -512,7 +512,7 @@ PyVar VM::new_type_object(PyVar mod, StrName name, PyVar base){
     setattr(obj, __base__, base);
     Str fullName = name.str();
     if(mod != builtins) fullName = OBJ_NAME(mod) + "." + name.str();
-    setattr(obj, __name__, py_var(this, fullName));
+    setattr(obj, __name__, VAR(fullName));
     setattr(mod, name, obj);
     _all_types.push_back(obj);
     return obj;
@@ -520,7 +520,7 @@ PyVar VM::new_type_object(PyVar mod, StrName name, PyVar base){
 
 PyVar VM::new_module(StrName name) {
     PyVar obj = new_object(tp_module, DummyModule());
-    setattr(obj, __name__, py_var(this, name.str()));
+    setattr(obj, __name__, VAR(name.str()));
     _modules.set(name, obj);
     return obj;
 }
@@ -557,7 +557,7 @@ Str VM::disassemble(CodeObject_ co){
         // ss << pad(byte.arg == -1 ? "" : std::to_string(byte.arg), 5);
         std::string argStr = byte.arg == -1 ? "" : std::to_string(byte.arg);
         if(byte.op == OP_LOAD_CONST){
-            argStr += " (" + py_cast<Str>(this, asRepr(co->consts[byte.arg])) + ")";
+            argStr += " (" + CAST(Str, asRepr(co->consts[byte.arg])) + ")";
         }
         if(byte.op == OP_LOAD_NAME_REF || byte.op == OP_LOAD_NAME || byte.op == OP_RAISE || byte.op == OP_STORE_NAME){
             argStr += " (" + co->names[byte.arg].first.str().escape(true) + ")";
@@ -573,21 +573,21 @@ Str VM::disassemble(CodeObject_ co){
     }
     StrStream consts;
     consts << "co_consts: ";
-    consts << py_cast<Str>(this, asRepr(py_var(this, co->consts)));
+    consts << CAST(Str, asRepr(VAR(co->consts)));
 
     StrStream names;
     names << "co_names: ";
     List list;
     for(int i=0; i<co->names.size(); i++){
-        list.push_back(py_var(this, co->names[i].first.str()));
+        list.push_back(VAR(co->names[i].first.str()));
     }
-    names << py_cast<Str>(this, asRepr(py_var(this, list)));
+    names << CAST(Str, asRepr(VAR(list)));
     ss << '\n' << consts.str() << '\n' << names.str() << '\n';
 
     for(int i=0; i<co->consts.size(); i++){
         PyVar obj = co->consts[i];
         if(is_type(obj, tp_function)){
-            const auto& f = py_cast<Function>(this, obj);
+            const auto& f = CAST(Function, obj);
             ss << disassemble(f.code);
         }
     }
@@ -638,7 +638,7 @@ void VM::init_builtin_types(){
     setattr(_t(tp_object), __base__, None);
     
     for(auto [k, v]: _types.items()){
-        setattr(v, __name__, py_var(this, k.str()));
+        setattr(v, __name__, VAR(k.str()));
     }
 
     std::vector<Str> pb_types = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
@@ -667,7 +667,7 @@ PyVar VM::call(const PyVar& _callable, Args args, const Args& kwargs, bool opCal
 
     const PyVar* callable = &_callable;
     if(is_type(*callable, tp_bound_method)){
-        auto& bm = py_cast<BoundMethod>(this, *callable);
+        auto& bm = CAST(BoundMethod, *callable);
         callable = &bm.method;      // get unbound method
         args.extend_self(bm.obj);
     }
@@ -677,7 +677,7 @@ PyVar VM::call(const PyVar& _callable, Args args, const Args& kwargs, bool opCal
         if(kwargs.size() != 0) TypeError("native_function does not accept keyword arguments");
         return f(this, args);
     } else if(is_type(*callable, tp_function)){
-        const Function& fn = py_cast<Function>(this, *callable);
+        const Function& fn = CAST(Function, *callable);
         NameDict_ locals = make_sp<NameDict>(
             fn.code->perfect_locals_capacity,
             kLocalsLoadFactor,
@@ -698,7 +698,7 @@ PyVar VM::call(const PyVar& _callable, Args args, const Args& kwargs, bool opCal
         if(!fn.starred_arg.empty()){
             List vargs;        // handle *args
             while(i < args.size()) vargs.push_back(std::move(args[i++]));
-            locals->set(fn.starred_arg, py_var(this, Tuple::from_list(std::move(vargs))));
+            locals->set(fn.starred_arg, VAR(Tuple::from_list(std::move(vargs))));
         }else{
             for(StrName key : fn.kwargs_order){
                 if(i < args.size()){
@@ -711,7 +711,7 @@ PyVar VM::call(const PyVar& _callable, Args args, const Args& kwargs, bool opCal
         }
         
         for(int i=0; i<kwargs.size(); i+=2){
-            const Str& key = py_cast<Str>(this, kwargs[i]);
+            const Str& key = CAST(Str, kwargs[i]);
             if(!fn.kwargs.contains(key)){
                 TypeError(key.escape(true) + " is an invalid keyword argument for " + fn.name.str() + "()");
             }
@@ -732,10 +732,10 @@ void VM::unpack_args(Args& args){
     List unpacked;
     for(int i=0; i<args.size(); i++){
         if(is_type(args[i], tp_star_wrapper)){
-            auto& star = _py_cast<StarWrapper>(this, args[i]);
+            auto& star = _CAST(StarWrapper, args[i]);
             if(!star.rvalue) UNREACHABLE();
             PyVar list = asList(star.obj);
-            List& list_c = py_cast<List>(this, list);
+            List& list_c = CAST(List, list);
             unpacked.insert(unpacked.end(), list_c.begin(), list_c.end());
         }else{
             unpacked.push_back(args[i]);
@@ -777,7 +777,7 @@ PyVarOrNull VM::getattr(const PyVar& obj, StrName name, bool throw_err) {
                 return call(descriptor, one_arg(obj));
             }
             if(is_type(*val, tp_function) || is_type(*val, tp_native_function)){
-                return py_var(this, BoundMethod(obj, *val));
+                return VAR(BoundMethod(obj, *val));
             }else{
                 return *val;
             }
@@ -800,12 +800,12 @@ void VM::setattr(PyVar& obj, StrName name, T&& value) {
 template<int ARGC>
 void VM::bind_method(PyVar obj, Str funcName, NativeFuncRaw fn) {
     check_type(obj, tp_type);
-    setattr(obj, funcName, py_var(this, NativeFunc(fn, ARGC, true)));
+    setattr(obj, funcName, VAR(NativeFunc(fn, ARGC, true)));
 }
 
 template<int ARGC>
 void VM::bind_func(PyVar obj, Str funcName, NativeFuncRaw fn) {
-    setattr(obj, funcName, py_var(this, NativeFunc(fn, ARGC, false)));
+    setattr(obj, funcName, VAR(NativeFunc(fn, ARGC, false)));
 }
 
 void VM::_error(Exception e){
@@ -813,7 +813,7 @@ void VM::_error(Exception e){
         e.is_re = false;
         throw e;
     }
-    top_frame()->push(py_var(this, e));
+    top_frame()->push(VAR(e));
     _raise();
 }
 
@@ -845,7 +845,7 @@ PyVar VM::_exec(){
             continue;
         }catch(UnhandledException& e){
             PyVar obj = frame->pop();
-            Exception& _e = py_cast<Exception>(this, obj);
+            Exception& _e = CAST(Exception, obj);
             _e.st_push(frame->snapshot());
             callstack.pop();
             if(callstack.empty()) throw _e;