diff --git a/include/pocketpy/vm.h b/include/pocketpy/vm.h index ff0f3de2..9a252dac 100644 --- a/include/pocketpy/vm.h +++ b/include/pocketpy/vm.h @@ -156,6 +156,7 @@ public: PyObject* __curr_class; PyObject* __cached_object_new; std::map __cached_codes; + std::map __cached_op_funcs; FuncDecl_ __dynamic_func_decl; #if PK_ENABLE_PROFILER @@ -205,10 +206,12 @@ public: bool py_le(PyObject* lhs, PyObject* rhs); // (lhs, rhs) -> lhs <= rhs bool py_gt(PyObject* lhs, PyObject* rhs); // (lhs, rhs) -> lhs > rhs bool py_ge(PyObject* lhs, PyObject* rhs); // (lhs, rhs) -> lhs >= rhs - bool py_ne(PyObject* lhs, PyObject* rhs) { // (lhs, rhs) -> lhs != rhs + bool py_ne(PyObject* lhs, PyObject* rhs){ // (lhs, rhs) -> lhs != rhs return !py_eq(lhs, rhs); } + PyObject* py_op(std::string_view name); // (name) -> operator.name + void py_exec(std::string_view, PyObject*, PyObject*); // exec(source, globals, locals) PyObject* py_eval(std::string_view, PyObject*, PyObject*); // eval(source, globals, locals) #endif diff --git a/src/vm.cpp b/src/vm.cpp index 81f3f12c..0ce30cc6 100644 --- a/src/vm.cpp +++ b/src/vm.cpp @@ -244,6 +244,18 @@ namespace pkpy{ return false; } + PyObject* VM::py_op(std::string_view name){ + PyObject* func; + auto it = __cached_op_funcs.find(name); + if(it == __cached_op_funcs.end()){ + func = py_import("operator")->attr(StrName::get(name)); + __cached_op_funcs[name] = func; + }else{ + func = it->second; + } + return func; + } + i64 VM::normalized_index(i64 index, int size){ if(index < 0) index += size; if(index < 0 || index >= size){