| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029 |
- #include "pocketpy/ceval.h"
- namespace pkpy{
- #define PREDICT_INT_OP(op) \
- if(is_int(_0) && is_int(_1)){ \
- TOP() = VAR(_0.as<i64>() op _1.as<i64>()); \
- DISPATCH() \
- }
- #define PREDICT_INT_DIV_OP(op) \
- if(is_int(_0) && is_int(_1)){ \
- i64 divisor = _1.as<i64>(); \
- if(_1.as<i64>() == 0) ZeroDivisionError(); \
- TOP() = VAR(_0.as<i64>() op divisor); \
- DISPATCH() \
- }
- #define BINARY_F_COMPARE(func, op, rfunc) \
- PyVar ret; \
- const PyTypeInfo* _ti = _tp_info(_0); \
- if(_ti->m##func){ \
- ret = _ti->m##func(this, _0, _1); \
- }else{ \
- PyVar self; \
- PyVar _2 = get_unbound_method(_0, func, &self, false); \
- if(_2 != nullptr) ret = call_method(self, _2, _1); \
- else ret = NotImplemented; \
- } \
- if(ret == NotImplemented){ \
- PyVar self; \
- PyVar _2 = get_unbound_method(_1, rfunc, &self, false); \
- if(_2 != nullptr) ret = call_method(self, _2, _0); \
- else BinaryOptError(op, _0, _1); \
- if(ret == NotImplemented) BinaryOptError(op, _0, _1); \
- }
- void VM::__op_unpack_sequence(uint16_t arg){
- PyVar _0 = POPX();
- if(is_type(_0, VM::tp_tuple)){
- // fast path for tuple
- Tuple& tuple = PK_OBJ_GET(Tuple, _0);
- if(tuple.size() == arg){
- for(PyVar obj: tuple) PUSH(obj);
- }else{
- ValueError(_S("expected ", (int)arg, " values to unpack, got ", (int)tuple.size()));
- }
- }else{
- auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
- _0 = py_iter(_0);
- const PyTypeInfo* ti = _tp_info(_0);
- for(int i=0; i<arg; i++){
- PyVar _1 = _py_next(ti, _0);
- if(_1 == StopIteration) ValueError("not enough values to unpack");
- PUSH(_1);
- }
- if(_py_next(ti, _0) != StopIteration) ValueError("too many values to unpack");
- }
- }
- bool VM::py_lt(PyVar _0, PyVar _1){
- BINARY_F_COMPARE(__lt__, "<", __gt__);
- return ret == True;
- }
- bool VM::py_le(PyVar _0, PyVar _1){
- BINARY_F_COMPARE(__le__, "<=", __ge__);
- return ret == True;
- }
- bool VM::py_gt(PyVar _0, PyVar _1){
- BINARY_F_COMPARE(__gt__, ">", __lt__);
- return ret == True;
- }
- bool VM::py_ge(PyVar _0, PyVar _1){
- BINARY_F_COMPARE(__ge__, ">=", __le__);
- return ret == True;
- }
- #undef BINARY_F_COMPARE
- PyVar VM::__run_top_frame(){
- Frame* frame = &callstack.top();
- const Frame* base_frame = frame;
- bool need_raise = false;
- while(true){
- try{
- if(need_raise){ need_raise = false; __raise_exc(); }
- /**********************************************************************/
- /* NOTE:
- * Be aware of accidental gc!
- * DO NOT leave any strong reference of PyVar in the C stack
- */
- {
- #if PK_ENABLE_PROFILER
- #define CEVAL_STEP_CALLBACK() \
- if(_ceval_on_step) _ceval_on_step(this, frame, byte); \
- if(_profiler) _profiler->_step(callstack.size(), frame); \
- if(!_next_breakpoint.empty()) { _next_breakpoint._step(this); }
- #else
- #define CEVAL_STEP_CALLBACK() \
- if(_ceval_on_step) _ceval_on_step(this, frame, byte);
- #endif
- __NEXT_FRAME:
- // cache
- const CodeObject* co = frame->co;
- const Bytecode* co_codes = co->codes.data();
- Bytecode byte = co_codes[frame->next_bytecode()];
- CEVAL_STEP_CALLBACK();
- #define DISPATCH() { byte = co_codes[frame->next_bytecode()]; CEVAL_STEP_CALLBACK(); goto __NEXT_STEP;}
- __NEXT_STEP:;
- #if PK_DEBUG_CEVAL_STEP
- __log_s_data();
- #endif
- switch ((Opcode)byte.op)
- {
- case OP_NO_OP: DISPATCH()
- /*****************************************/
- case OP_POP_TOP: POP(); DISPATCH()
- case OP_DUP_TOP: PUSH(TOP()); DISPATCH()
- case OP_ROT_TWO: std::swap(TOP(), SECOND()); DISPATCH()
- case OP_ROT_THREE:{
- PyVar _0 = TOP();
- TOP() = SECOND();
- SECOND() = THIRD();
- THIRD() = _0;
- } DISPATCH()
- case OP_PRINT_EXPR:{
- if(TOP() != None) stdout_write(py_repr(TOP()) + "\n");
- POP();
- } DISPATCH()
- /*****************************************/
- case OP_LOAD_CONST:
- PUSH(co->consts[byte.arg]);
- DISPATCH()
- case OP_LOAD_NONE: PUSH(None); DISPATCH()
- case OP_LOAD_TRUE: PUSH(True); DISPATCH()
- case OP_LOAD_FALSE: PUSH(False); DISPATCH()
- /*****************************************/
- case OP_LOAD_SMALL_INT: PUSH(VAR((int16_t)byte.arg)); DISPATCH()
- /*****************************************/
- case OP_LOAD_ELLIPSIS: PUSH(Ellipsis); DISPATCH()
- case OP_LOAD_FUNCTION: {
- const FuncDecl_& decl = co->func_decls[byte.arg];
- PyVar obj;
- if(decl->nested){
- NameDict_ captured = frame->_locals.to_namedict();
- obj = VAR(Function(decl, frame->_module, nullptr, captured));
- captured->set(decl->code->name, obj);
- }else{
- obj = VAR(Function(decl, frame->_module, nullptr, nullptr));
- }
- PUSH(obj);
- } DISPATCH()
- case OP_LOAD_NULL: PUSH(PY_NULL); DISPATCH()
- /*****************************************/
- case OP_LOAD_FAST: {
- PyVar _0 = frame->_locals[byte.arg];
- if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
- PUSH(_0);
- } DISPATCH()
- case OP_LOAD_NAME: {
- StrName _name(byte.arg);
- PyVar* slot = frame->_locals.try_get_name(_name);
- if(slot != nullptr) {
- if(*slot == PY_NULL) vm->UnboundLocalError(_name);
- PUSH(*slot);
- DISPATCH()
- }
- PyVar _0 = frame->f_closure_try_get(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = frame->f_globals().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = vm->builtins->attr().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- vm->NameError(_name);
- } DISPATCH()
- case OP_LOAD_NONLOCAL: {
- StrName _name(byte.arg);
- PyVar _0 = frame->f_closure_try_get(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = frame->f_globals().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = vm->builtins->attr().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- vm->NameError(_name);
- } DISPATCH()
- case OP_LOAD_GLOBAL:{
- StrName _name(byte.arg);
- PyVar _0 = frame->f_globals().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = vm->builtins->attr().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- vm->NameError(_name);
- } DISPATCH()
- case OP_LOAD_ATTR:{
- TOP() = getattr(TOP(), StrName(byte.arg));
- } DISPATCH()
- case OP_LOAD_CLASS_GLOBAL:{
- PK_ASSERT(__curr_class != nullptr);
- StrName _name(byte.arg);
- PyVar _0 = getattr(__curr_class, _name, false);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- // load global if attribute not found
- _0 = frame->f_globals().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- _0 = vm->builtins->attr().try_get_likely_found(_name);
- if(_0 != nullptr) { PUSH(_0); DISPATCH() }
- vm->NameError(_name);
- } DISPATCH()
- case OP_LOAD_METHOD:{
- PyVar _0;
- TOP() = get_unbound_method(TOP(), StrName(byte.arg), &_0, true, true);
- PUSH(_0);
- }DISPATCH()
- case OP_LOAD_SUBSCR:{
- PyVar _1 = POPX(); // b
- PyVar _0 = TOP(); // a
- auto _ti = _tp_info(_0);
- if(_ti->m__getitem__){
- TOP() = _ti->m__getitem__(this, _0, _1);
- }else{
- TOP() = call_method(_0, __getitem__, _1);
- }
- } DISPATCH()
- case OP_LOAD_SUBSCR_FAST:{
- PyVar _1 = frame->_locals[byte.arg];
- if(_1 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
- PyVar _0 = TOP(); // a
- auto _ti = _tp_info(_0);
- if(_ti->m__getitem__){
- TOP() = _ti->m__getitem__(this, _0, _1);
- }else{
- TOP() = call_method(_0, __getitem__, _1);
- }
- } DISPATCH()
- case OP_LOAD_SUBSCR_SMALL_INT:{
- PyVar _1 = VAR((int16_t)byte.arg);
- PyVar _0 = TOP(); // a
- auto _ti = _tp_info(_0);
- if(_ti->m__getitem__){
- TOP() = _ti->m__getitem__(this, _0, _1);
- }else{
- TOP() = call_method(_0, __getitem__, _1);
- }
- } DISPATCH()
- case OP_STORE_FAST:
- frame->_locals[byte.arg] = POPX();
- DISPATCH()
- case OP_STORE_NAME:{
- StrName _name(byte.arg);
- PyVar _0 = POPX();
- if(frame->_callable != nullptr){
- PyVar* slot = frame->_locals.try_get_name(_name);
- if(slot != nullptr){
- *slot = _0; // store in locals if possible
- }else{
- Function& func = PK_OBJ_GET(Function, frame->_callable);
- if(func.decl == __dynamic_func_decl){
- PK_DEBUG_ASSERT(func._closure != nullptr);
- func._closure->set(_name, _0);
- }else{
- vm->NameError(_name);
- }
- }
- }else{
- frame->f_globals().set(_name, _0);
- }
- } DISPATCH()
- case OP_STORE_GLOBAL:
- frame->f_globals().set(StrName(byte.arg), POPX());
- DISPATCH()
- case OP_STORE_ATTR: {
- PyVar _0 = TOP(); // a
- PyVar _1 = SECOND(); // val
- setattr(_0, StrName(byte.arg), _1);
- STACK_SHRINK(2);
- } DISPATCH()
- case OP_STORE_SUBSCR:{
- PyVar _2 = POPX(); // b
- PyVar _1 = POPX(); // a
- PyVar _0 = POPX(); // val
- auto _ti = _tp_info(_1);
- if(_ti->m__setitem__){
- _ti->m__setitem__(this, _1, _2, _0);
- }else{
- call_method(_1, __setitem__, _2, _0);
- }
- }DISPATCH()
- case OP_STORE_SUBSCR_FAST:{
- PyVar _2 = frame->_locals[byte.arg]; // b
- if(_2 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
- PyVar _1 = POPX(); // a
- PyVar _0 = POPX(); // val
- auto _ti = _tp_info(_1);
- if(_ti->m__setitem__){
- _ti->m__setitem__(this, _1, _2, _0);
- }else{
- call_method(_1, __setitem__, _2, _0);
- }
- }DISPATCH()
- case OP_DELETE_FAST:{
- PyVar _0 = frame->_locals[byte.arg];
- if(_0 == PY_NULL) vm->UnboundLocalError(co->varnames[byte.arg]);
- frame->_locals[byte.arg] = PY_NULL;
- }DISPATCH()
- case OP_DELETE_NAME:{
- StrName _name(byte.arg);
- if(frame->_callable != nullptr){
- PyVar* slot = frame->_locals.try_get_name(_name);
- if(slot != nullptr){
- *slot = PY_NULL;
- }else{
- Function& func = PK_OBJ_GET(Function, frame->_callable);
- if(func.decl == __dynamic_func_decl){
- PK_DEBUG_ASSERT(func._closure != nullptr);
- bool ok = func._closure->del(_name);
- if(!ok) vm->NameError(_name);
- }else{
- vm->NameError(_name);
- }
- }
- }else{
- if(!frame->f_globals().del(_name)) vm->NameError(_name);
- }
- } DISPATCH()
- case OP_DELETE_GLOBAL:{
- StrName _name(byte.arg);
- if(!frame->f_globals().del(_name)) vm->NameError(_name);
- }DISPATCH()
- case OP_DELETE_ATTR:{
- PyVar _0 = POPX();
- delattr(_0, StrName(byte.arg));
- } DISPATCH()
- case OP_DELETE_SUBSCR:{
- PyVar _1 = POPX();
- PyVar _0 = POPX();
- auto _ti = _tp_info(_0);
- if(_ti->m__delitem__){
- _ti->m__delitem__(this, _0, _1);
- }else{
- call_method(_0, __delitem__, _1);
- }
- }DISPATCH()
- /*****************************************/
- case OP_BUILD_LONG: {
- PyVar _0 = builtins->attr().try_get_likely_found(pk_id_long);
- if(_0 == nullptr) AttributeError(builtins, pk_id_long);
- TOP() = call(_0, TOP());
- } DISPATCH()
- case OP_BUILD_IMAG: {
- PyVar _0 = builtins->attr().try_get_likely_found(pk_id_complex);
- if(_0 == nullptr) AttributeError(builtins, pk_id_long);
- TOP() = call(_0, VAR(0), TOP());
- } DISPATCH()
- case OP_BUILD_BYTES: {
- const Str& s = CAST(Str&, TOP());
- unsigned char* p = new unsigned char[s.size];
- memcpy(p, s.data, s.size);
- TOP() = VAR(Bytes(p, s.size));
- } DISPATCH()
- case OP_BUILD_TUPLE:{
- PyVar _0 = VAR(STACK_VIEW(byte.arg).to_tuple());
- STACK_SHRINK(byte.arg);
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_LIST:{
- PyVar _0 = VAR(STACK_VIEW(byte.arg).to_list());
- STACK_SHRINK(byte.arg);
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_DICT:{
- if(byte.arg == 0){
- PUSH(VAR(Dict(this)));
- DISPATCH()
- }
- PyVar _0 = VAR(STACK_VIEW(byte.arg).to_list());
- _0 = call(_t(tp_dict), _0);
- STACK_SHRINK(byte.arg);
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_SET:{
- PyVar _0 = VAR(STACK_VIEW(byte.arg).to_list());
- _0 = call(builtins->attr(pk_id_set), _0);
- STACK_SHRINK(byte.arg);
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_SLICE:{
- PyVar _2 = POPX(); // step
- PyVar _1 = POPX(); // stop
- PyVar _0 = POPX(); // start
- PUSH(VAR(Slice(_0, _1, _2)));
- } DISPATCH()
- case OP_BUILD_STRING: {
- SStream ss;
- ArgsView view = STACK_VIEW(byte.arg);
- for(PyVar obj : view) ss << py_str(obj);
- STACK_SHRINK(byte.arg);
- PUSH(VAR(ss.str()));
- } DISPATCH()
- /*****************************************/
- case OP_BUILD_TUPLE_UNPACK: {
- auto _lock = heap.gc_scope_lock();
- List list;
- __unpack_as_list(STACK_VIEW(byte.arg), list);
- STACK_SHRINK(byte.arg);
- PyVar _0 = VAR(Tuple(std::move(list)));
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_LIST_UNPACK: {
- auto _lock = heap.gc_scope_lock();
- List list;
- __unpack_as_list(STACK_VIEW(byte.arg), list);
- STACK_SHRINK(byte.arg);
- PyVar _0 = VAR(std::move(list));
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_DICT_UNPACK: {
- auto _lock = heap.gc_scope_lock();
- Dict dict(this);
- __unpack_as_dict(STACK_VIEW(byte.arg), dict);
- STACK_SHRINK(byte.arg);
- PyVar _0 = VAR(std::move(dict));
- PUSH(_0);
- } DISPATCH()
- case OP_BUILD_SET_UNPACK: {
- auto _lock = heap.gc_scope_lock();
- List list;
- __unpack_as_list(STACK_VIEW(byte.arg), list);
- STACK_SHRINK(byte.arg);
- PyVar _0 = VAR(std::move(list));
- _0 = call(builtins->attr(pk_id_set), _0);
- PUSH(_0);
- } DISPATCH()
- /*****************************************/
- #define BINARY_OP_SPECIAL(func) \
- _ti = _tp_info(_0); \
- if(_ti->m##func){ \
- TOP() = _ti->m##func(this, _0, _1); \
- }else{ \
- PyVar self; \
- PyVar _2 = get_unbound_method(_0, func, &self, false); \
- if(_2 != nullptr) TOP() = call_method(self, _2, _1); \
- else TOP() = NotImplemented; \
- }
- #define BINARY_OP_RSPECIAL(op, func) \
- if(TOP() == NotImplemented){ \
- PyVar self; \
- PyVar _2 = get_unbound_method(_1, func, &self, false); \
- if(_2 != nullptr) TOP() = call_method(self, _2, _0); \
- else BinaryOptError(op, _0, _1); \
- if(TOP() == NotImplemented) BinaryOptError(op, _0, _1); \
- }
- case OP_BINARY_TRUEDIV:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__truediv__);
- if(TOP() == NotImplemented) BinaryOptError("/", _0, _1);
- } DISPATCH()
- case OP_BINARY_POW:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__pow__);
- if(TOP() == NotImplemented) BinaryOptError("**", _0, _1);
- } DISPATCH()
- case OP_BINARY_ADD:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(+)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__add__);
- BINARY_OP_RSPECIAL("+", __radd__);
- } DISPATCH()
- case OP_BINARY_SUB:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(-)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__sub__);
- BINARY_OP_RSPECIAL("-", __rsub__);
- } DISPATCH()
- case OP_BINARY_MUL:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(*)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__mul__);
- BINARY_OP_RSPECIAL("*", __rmul__);
- } DISPATCH()
- case OP_BINARY_FLOORDIV:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_DIV_OP(/)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__floordiv__);
- if(TOP() == NotImplemented) BinaryOptError("//", _0, _1);
- } DISPATCH()
- case OP_BINARY_MOD:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_DIV_OP(%)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__mod__);
- if(TOP() == NotImplemented) BinaryOptError("%", _0, _1);
- } DISPATCH()
- case OP_COMPARE_LT:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(<)
- TOP() = VAR(py_lt(_0, _1));
- } DISPATCH()
- case OP_COMPARE_LE:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(<=)
- TOP() = VAR(py_le(_0, _1));
- } DISPATCH()
- case OP_COMPARE_EQ:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- TOP() = VAR(py_eq(_0, _1));
- } DISPATCH()
- case OP_COMPARE_NE:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- TOP() = VAR(py_ne(_0, _1));
- } DISPATCH()
- case OP_COMPARE_GT:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(>)
- TOP() = VAR(py_gt(_0, _1));
- } DISPATCH()
- case OP_COMPARE_GE:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(>=)
- TOP() = VAR(py_ge(_0, _1));
- } DISPATCH()
- case OP_BITWISE_LSHIFT:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(<<)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__lshift__);
- if(TOP() == NotImplemented) BinaryOptError("<<", _0, _1);
- } DISPATCH()
- case OP_BITWISE_RSHIFT:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(>>)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__rshift__);
- if(TOP() == NotImplemented) BinaryOptError(">>", _0, _1);
- } DISPATCH()
- case OP_BITWISE_AND:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(&)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__and__);
- if(TOP() == NotImplemented) BinaryOptError("&", _0, _1);
- } DISPATCH()
- case OP_BITWISE_OR:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(|)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__or__);
- if(TOP() == NotImplemented) BinaryOptError("|", _0, _1);
- } DISPATCH()
- case OP_BITWISE_XOR:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- PREDICT_INT_OP(^)
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__xor__);
- if(TOP() == NotImplemented) BinaryOptError("^", _0, _1);
- } DISPATCH()
- case OP_BINARY_MATMUL:{
- PyVar _1 = POPX();
- PyVar _0 = TOP();
- const PyTypeInfo* _ti;
- BINARY_OP_SPECIAL(__matmul__);
- if(TOP() == NotImplemented) BinaryOptError("@", _0, _1);
- } DISPATCH()
- #undef BINARY_OP_SPECIAL
- #undef BINARY_OP_RSPECIAL
- #undef PREDICT_INT_OP
- case OP_IS_OP:{
- PyVar _1 = POPX(); // rhs
- PyVar _0 = TOP(); // lhs
- TOP() = VAR(static_cast<bool>((uint16_t)(_0==_1) ^ byte.arg));
- } DISPATCH()
- case OP_CONTAINS_OP:{
- // a in b -> b __contains__ a
- auto _ti = _tp_info(TOP());
- PyVar _0;
- if(_ti->m__contains__){
- _0 = _ti->m__contains__(this, TOP(), SECOND());
- }else{
- _0 = call_method(TOP(), __contains__, SECOND());
- }
- POP();
- TOP() = VAR(static_cast<bool>((int)CAST(bool, _0) ^ byte.arg));
- } DISPATCH()
- /*****************************************/
- case OP_JUMP_ABSOLUTE:
- frame->jump_abs(byte.arg);
- DISPATCH()
- case OP_JUMP_ABSOLUTE_TOP:
- frame->jump_abs(_CAST(int, POPX()));
- DISPATCH()
- case OP_POP_JUMP_IF_FALSE:{
- if(!py_bool(TOP())) frame->jump_abs(byte.arg);
- POP();
- } DISPATCH()
- case OP_POP_JUMP_IF_TRUE:{
- if(py_bool(TOP())) frame->jump_abs(byte.arg);
- POP();
- } DISPATCH()
- case OP_JUMP_IF_TRUE_OR_POP:{
- if(py_bool(TOP())) frame->jump_abs(byte.arg);
- else POP();
- } DISPATCH()
- case OP_JUMP_IF_FALSE_OR_POP:{
- if(!py_bool(TOP())) frame->jump_abs(byte.arg);
- else POP();
- } DISPATCH()
- case OP_SHORTCUT_IF_FALSE_OR_POP:{
- if(!py_bool(TOP())){ // [b, False]
- STACK_SHRINK(2); // []
- PUSH(vm->False); // [False]
- frame->jump_abs(byte.arg);
- } else POP(); // [b]
- } DISPATCH()
- case OP_LOOP_CONTINUE:
- frame->jump_abs(byte.arg);
- DISPATCH()
- case OP_LOOP_BREAK:
- frame->jump_abs_break(&s_data, byte.arg);
- DISPATCH()
- case OP_GOTO: {
- StrName _name(byte.arg);
- int index = co->labels.try_get_likely_found(_name);
- if(index < 0) RuntimeError(_S("label ", _name.escape(), " not found"));
- frame->jump_abs_break(&s_data, index);
- } DISPATCH()
- /*****************************************/
- case OP_FSTRING_EVAL:{
- PyVar _0 = co->consts[byte.arg];
- std::string_view string = CAST(Str&, _0).sv();
- auto it = __cached_codes.find(string);
- CodeObject_ code;
- if(it == __cached_codes.end()){
- code = vm->compile(string, "<eval>", EVAL_MODE, true);
- __cached_codes[string] = code;
- }else{
- code = it->second;
- }
- _0 = vm->_exec(code.get(), frame->_module, frame->_callable, frame->_locals);
- PUSH(_0);
- } DISPATCH()
- case OP_REPR:
- TOP() = VAR(py_repr(TOP()));
- DISPATCH()
- case OP_CALL:{
- if(heap._should_auto_collect()) heap._auto_collect();
- PyVar _0 = vectorcall(
- byte.arg & 0xFF, // ARGC
- (byte.arg>>8) & 0xFF, // KWARGC
- true
- );
- if(_0 == PY_OP_CALL){
- frame = &callstack.top();
- goto __NEXT_FRAME;
- }
- PUSH(_0);
- } DISPATCH()
- case OP_CALL_TP:{
- if(heap._should_auto_collect()) heap._auto_collect();
- PyVar _0;
- PyVar _1;
- PyVar _2;
- // [callable, <self>, args: tuple, kwargs: dict | NULL]
- if(byte.arg){
- _2 = POPX();
- _1 = POPX();
- for(PyVar obj: _CAST(Tuple&, _1)) PUSH(obj);
- _CAST(Dict&, _2).apply([this](PyVar k, PyVar v){
- PUSH(VAR(StrName(CAST(Str&, k)).index));
- PUSH(v);
- });
- _0 = vectorcall(
- _CAST(Tuple&, _1).size(), // ARGC
- _CAST(Dict&, _2).size(), // KWARGC
- true
- );
- }else{
- // no **kwargs
- _1 = POPX();
- for(PyVar obj: _CAST(Tuple&, _1)) PUSH(obj);
- _0 = vectorcall(
- _CAST(Tuple&, _1).size(), // ARGC
- 0, // KWARGC
- true
- );
- }
- if(_0 == PY_OP_CALL){
- frame = &callstack.top();
- goto __NEXT_FRAME;
- }
- PUSH(_0);
- } DISPATCH()
- case OP_RETURN_VALUE:{
- PyVar _0 = byte.arg == BC_NOARG ? POPX() : None;
- __pop_frame();
- if(frame == base_frame){ // [ frameBase<- ]
- return _0;
- }else{
- frame = &callstack.top();
- PUSH(_0);
- goto __NEXT_FRAME;
- }
- } DISPATCH()
- case OP_YIELD_VALUE:
- return PY_OP_YIELD;
- /*****************************************/
- case OP_LIST_APPEND:{
- PyVar _0 = POPX();
- PK_OBJ_GET(List, SECOND()).push_back(_0);
- } DISPATCH()
- case OP_DICT_ADD: {
- PyVar _0 = POPX();
- const Tuple& t = PK_OBJ_GET(Tuple, _0);
- PK_OBJ_GET(Dict, SECOND()).set(t[0], t[1]);
- } DISPATCH()
- case OP_SET_ADD:{
- PyVar _0 = POPX();
- call_method(SECOND(), pk_id_add, _0);
- } DISPATCH()
- /*****************************************/
- case OP_UNARY_NEGATIVE:
- TOP() = py_negate(TOP());
- DISPATCH()
- case OP_UNARY_NOT:{
- PyVar _0 = TOP();
- if(_0==True) TOP()=False;
- else if(_0==False) TOP()=True;
- else TOP() = VAR(!py_bool(_0));
- } DISPATCH()
- case OP_UNARY_STAR:
- TOP() = VAR(StarWrapper(byte.arg, TOP()));
- DISPATCH()
- case OP_UNARY_INVERT:{
- PyVar _0;
- auto _ti = _tp_info(TOP());
- if(_ti->m__invert__) _0 = _ti->m__invert__(this, TOP());
- else _0 = call_method(TOP(), __invert__);
- TOP() = _0;
- } DISPATCH()
- /*****************************************/
- case OP_GET_ITER:
- TOP() = py_iter(TOP());
- DISPATCH()
- case OP_FOR_ITER:{
- PyVar _0 = py_next(TOP());
- if(_0 == StopIteration) frame->loop_break(&s_data, co);
- else PUSH(_0);
- } DISPATCH()
- case OP_FOR_ITER_STORE_FAST:{
- PyVar _0 = py_next(TOP());
- if(_0 == StopIteration){
- frame->loop_break(&s_data, co);
- }else{
- frame->_locals[byte.arg] = _0;
- }
- } DISPATCH()
- case OP_FOR_ITER_STORE_GLOBAL:{
- PyVar _0 = py_next(TOP());
- if(_0 == StopIteration){
- frame->loop_break(&s_data, co);
- }else{
- frame->f_globals().set(StrName(byte.arg), _0);
- }
- } DISPATCH()
- case OP_FOR_ITER_YIELD_VALUE:{
- PyVar _0 = py_next(TOP());
- if(_0 == StopIteration){
- frame->loop_break(&s_data, co);
- }else{
- PUSH(_0);
- return PY_OP_YIELD;
- }
- } DISPATCH()
- case OP_FOR_ITER_UNPACK:{
- PyVar _0 = TOP();
- const PyTypeInfo* _ti = _tp_info(_0);
- if(_ti->m__next__){
- unsigned n = _ti->m__next__(this, _0);
- if(n == 0){
- // StopIteration
- frame->loop_break(&s_data, co);
- }else if(n == 1){
- // UNPACK_SEQUENCE
- __op_unpack_sequence(byte.arg);
- }else{
- if(n != byte.arg){
- ValueError(_S("expected ", (int)byte.arg, " values to unpack, got ", (int)n));
- }
- }
- }else{
- // FOR_ITER
- _0 = call_method(_0, __next__);
- if(_0 != StopIteration){
- PUSH(_0);
- // UNPACK_SEQUENCE
- __op_unpack_sequence(byte.arg);
- }else{
- frame->loop_break(&s_data, co);
- }
- }
- } DISPATCH()
- /*****************************************/
- case OP_IMPORT_PATH:{
- PyVar _0 = co->consts[byte.arg];
- PUSH(py_import(CAST(Str&, _0)));
- } DISPATCH()
- case OP_POP_IMPORT_STAR: {
- PyVar _0 = POPX(); // pop the module
- PyVar _1 = _0->attr().try_get(__all__);
- StrName _name;
- if(_1 != nullptr){
- for(PyVar key: CAST(List&, _1)){
- _name = StrName::get(CAST(Str&, key).sv());
- PyVar value = _0->attr().try_get_likely_found(_name);
- if(value == nullptr){
- ImportError(_S("cannot import name ", _name.escape()));
- }else{
- frame->f_globals().set(_name, value);
- }
- }
- }else{
- for(auto& [name, value]: _0->attr().items()){
- std::string_view s = name.sv();
- if(s.empty() || s[0] == '_') continue;
- frame->f_globals().set(name, value);
- }
- }
- } DISPATCH()
- /*****************************************/
- case OP_UNPACK_SEQUENCE:{
- __op_unpack_sequence(byte.arg);
- } DISPATCH()
- case OP_UNPACK_EX: {
- auto _lock = heap.gc_scope_lock(); // lock the gc via RAII!!
- PyVar _0 = py_iter(POPX());
- const PyTypeInfo* _ti = _tp_info(_0);
- PyVar _1;
- for(int i=0; i<byte.arg; i++){
- _1 = _py_next(_ti, _0);
- if(_1 == StopIteration) ValueError("not enough values to unpack");
- PUSH(_1);
- }
- List extras;
- while(true){
- _1 = _py_next(_ti, _0);
- if(_1 == StopIteration) break;
- extras.push_back(_1);
- }
- PUSH(VAR(extras));
- } DISPATCH()
- /*****************************************/
- case OP_BEGIN_CLASS:{
- StrName _name(byte.arg);
- PyVar _0 = POPX(); // super
- if(_0 == None) _0 = _t(tp_object);
- check_type(_0, tp_type);
- __curr_class = new_type_object(frame->_module, _name, PK_OBJ_GET(Type, _0));
- } DISPATCH()
- case OP_END_CLASS: {
- PK_ASSERT(__curr_class != nullptr);
- StrName _name(byte.arg);
- frame->_module->attr().set(_name, __curr_class);
- // call on_end_subclass
- PyTypeInfo* ti = &_all_types[PK_OBJ_GET(Type, __curr_class).index];
- if(ti->base != tp_object){
- PyTypeInfo* base_ti = &_all_types[ti->base.index];
- if(base_ti->on_end_subclass) base_ti->on_end_subclass(this, ti);
- }
- __curr_class = nullptr;
- } DISPATCH()
- case OP_STORE_CLASS_ATTR:{
- PK_ASSERT(__curr_class != nullptr);
- StrName _name(byte.arg);
- PyVar _0 = POPX();
- if(is_type(_0, tp_function)){
- PK_OBJ_GET(Function, _0)._class = __curr_class;
- }
- __curr_class->attr().set(_name, _0);
- } DISPATCH()
- case OP_BEGIN_CLASS_DECORATION:{
- PUSH(__curr_class);
- } DISPATCH()
- case OP_END_CLASS_DECORATION:{
- __curr_class = POPX();
- } DISPATCH()
- case OP_ADD_CLASS_ANNOTATION: {
- PK_ASSERT(__curr_class != nullptr);
- StrName _name(byte.arg);
- Type type = PK_OBJ_GET(Type, __curr_class);
- _all_types[type.index].annotated_fields.push_back(_name);
- } DISPATCH()
- /*****************************************/
- case OP_WITH_ENTER:
- PUSH(call_method(TOP(), __enter__));
- DISPATCH()
- case OP_WITH_EXIT:
- call_method(TOP(), __exit__);
- POP();
- DISPATCH()
- /*****************************************/
- case OP_EXCEPTION_MATCH: {
- PyVar assumed_type = POPX();
- check_type(assumed_type, tp_type);
- PyVar e_obj = TOP();
- bool ok = isinstance(e_obj, PK_OBJ_GET(Type, assumed_type));
- PUSH(VAR(ok));
- } DISPATCH()
- case OP_RAISE: {
- if(is_type(TOP(), tp_type)){
- TOP() = call(TOP());
- }
- if(!isinstance(TOP(), tp_exception)){
- TypeError("exceptions must derive from Exception");
- }
- _error(POPX());
- } DISPATCH()
- case OP_RAISE_ASSERT:
- if(byte.arg){
- Str msg = py_str(TOP());
- POP();
- AssertionError(msg);
- }else{
- AssertionError();
- }
- DISPATCH()
- case OP_RE_RAISE: __raise_exc(true); DISPATCH()
- case OP_POP_EXCEPTION: __last_exception = POPX(); DISPATCH()
- /*****************************************/
- case OP_FORMAT_STRING: {
- PyVar _0 = POPX();
- const Str& spec = CAST(Str&, co->consts[byte.arg]);
- PUSH(__format_object(_0, spec));
- } DISPATCH()
- /*****************************************/
- case OP_INC_FAST:{
- PyVar* p = &frame->_locals[byte.arg];
- if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
- *p = VAR(CAST(i64, *p) + 1);
- } DISPATCH()
- case OP_DEC_FAST:{
- PyVar* p = &frame->_locals[byte.arg];
- if(*p == PY_NULL) vm->NameError(co->varnames[byte.arg]);
- *p = VAR(CAST(i64, *p) - 1);
- } DISPATCH()
- case OP_INC_GLOBAL:{
- StrName _name(byte.arg);
- PyVar* p = frame->f_globals().try_get_2_likely_found(_name);
- if(p == nullptr) vm->NameError(_name);
- *p = VAR(CAST(i64, *p) + 1);
- } DISPATCH()
- case OP_DEC_GLOBAL:{
- StrName _name(byte.arg);
- PyVar* p = frame->f_globals().try_get_2_likely_found(_name);
- if(p == nullptr) vm->NameError(_name);
- *p = VAR(CAST(i64, *p) - 1);
- } DISPATCH()
- /*****************************************/
- }
- }
- /**********************************************************************/
- PK_UNREACHABLE()
- }catch(HandledException){
- continue;
- }catch(UnhandledException){
- PyVar e_obj = POPX();
- Exception& _e = PK_OBJ_GET(Exception, e_obj);
- bool is_base_frame_to_be_popped = frame == base_frame;
- __pop_frame();
- if(callstack.empty()) throw _e; // propagate to the top level
- frame = &callstack.top();
- PUSH(e_obj);
- if(is_base_frame_to_be_popped) throw ToBeRaisedException();
- need_raise = true;
- }catch(ToBeRaisedException){
- need_raise = true;
- }
- }
- }
- #undef TOP
- #undef SECOND
- #undef THIRD
- #undef STACK_SHRINK
- #undef PUSH
- #undef POP
- #undef POPX
- #undef STACK_VIEW
- #undef DISPATCH
- #undef CEVAL_STEP_CALLBACK
- } // namespace pkpy
|