some cleanup

This commit is contained in:
blueloveTH 2024-01-19 13:26:51 +08:00
parent 77d727a7c2
commit ec75972d92
6 changed files with 279 additions and 371 deletions

View File

@ -9,7 +9,7 @@ pipeline = [
["config.h", "export.h", "common.h", "memory.h", "vector.h", "str.h", "tuplelist.h", "namedict.h", "error.h"],
["obj.h", "dict.h", "codeobject.h", "frame.h"],
["gc.h", "vm.h", "ceval.h", "lexer.h", "expr.h", "compiler.h", "repl.h"],
["_generated.h", "cffi.h", "bindings.h", "iter.h", "base64.h", "csv.h", "collections.h", "random.h", "re.h", "linalg.h", "easing.h", "io.h"],
["_generated.h", "cffi.h", "bindings.h", "iter.h", "base64.h", "csv.h", "collections.h", "random.h", "re.h", "linalg.h", "easing.h", "io.h", "modules.h"],
["pocketpy.h", "pocketpy_c.h"]
]

View File

@ -0,0 +1,15 @@
#include "bindings.h"
namespace pkpy{
void add_module_timeit(VM* vm);
void add_module_operator(VM* vm);
void add_module_time(VM* vm);
void add_module_sys(VM* vm);
void add_module_json(VM* vm);
void add_module_math(VM* vm);
void add_module_traceback(VM* vm);
void add_module_dis(VM* vm);
void add_module_gc(VM* vm);
} // namespace pkpy

View File

@ -15,18 +15,4 @@
#include "bindings.h"
#include "collections.h"
#include "csv.h"
namespace pkpy {
void init_builtins(VM* _vm);
void add_module_timeit(VM* vm);
void add_module_time(VM* vm);
void add_module_sys(VM* vm);
void add_module_json(VM* vm);
void add_module_math(VM* vm);
void add_module_dis(VM* vm);
void add_module_traceback(VM* vm);
void add_module_gc(VM* vm);
} // namespace pkpy
#include "modules.h"

262
src/modules.cpp Normal file
View File

@ -0,0 +1,262 @@
#include "pocketpy/modules.h"
namespace pkpy{
void add_module_timeit(VM* vm){
PyObject* mod = vm->new_module("timeit");
vm->bind_func<2>(mod, "timeit", [](VM* vm, ArgsView args) {
PyObject* f = args[0];
i64 iters = CAST(i64, args[1]);
auto now = std::chrono::system_clock::now();
for(i64 i=0; i<iters; i++) vm->call(f);
auto end = std::chrono::system_clock::now();
f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - now).count() / 1000.0;
return VAR(elapsed);
});
}
void add_module_operator(VM* vm){
PyObject* mod = vm->new_module("operator");
vm->bind_func<2>(mod, "lt", [](VM* vm, ArgsView args) { return VAR(vm->py_lt(args[0], args[1]));});
vm->bind_func<2>(mod, "le", [](VM* vm, ArgsView args) { return VAR(vm->py_le(args[0], args[1]));});
vm->bind_func<2>(mod, "eq", [](VM* vm, ArgsView args) { return VAR(vm->py_eq(args[0], args[1]));});
vm->bind_func<2>(mod, "ne", [](VM* vm, ArgsView args) { return VAR(vm->py_ne(args[0], args[1]));});
vm->bind_func<2>(mod, "ge", [](VM* vm, ArgsView args) { return VAR(vm->py_ge(args[0], args[1]));});
vm->bind_func<2>(mod, "gt", [](VM* vm, ArgsView args) { return VAR(vm->py_gt(args[0], args[1]));});
}
struct PyStructTime{
PY_CLASS(PyStructTime, time, struct_time)
int tm_year;
int tm_mon;
int tm_mday;
int tm_hour;
int tm_min;
int tm_sec;
int tm_wday;
int tm_yday;
int tm_isdst;
PyStructTime(std::time_t t){
std::tm* tm = std::localtime(&t);
tm_year = tm->tm_year + 1900;
tm_mon = tm->tm_mon + 1;
tm_mday = tm->tm_mday;
tm_hour = tm->tm_hour;
tm_min = tm->tm_min;
tm_sec = tm->tm_sec;
tm_wday = (tm->tm_wday + 6) % 7;
tm_yday = tm->tm_yday + 1;
tm_isdst = tm->tm_isdst;
}
PyStructTime* _() { return this; }
static void _register(VM* vm, PyObject* mod, PyObject* type){
vm->bind_notimplemented_constructor<PyStructTime>(type);
PY_READONLY_FIELD(PyStructTime, "tm_year", _, tm_year);
PY_READONLY_FIELD(PyStructTime, "tm_mon", _, tm_mon);
PY_READONLY_FIELD(PyStructTime, "tm_mday", _, tm_mday);
PY_READONLY_FIELD(PyStructTime, "tm_hour", _, tm_hour);
PY_READONLY_FIELD(PyStructTime, "tm_min", _, tm_min);
PY_READONLY_FIELD(PyStructTime, "tm_sec", _, tm_sec);
PY_READONLY_FIELD(PyStructTime, "tm_wday", _, tm_wday);
PY_READONLY_FIELD(PyStructTime, "tm_yday", _, tm_yday);
PY_READONLY_FIELD(PyStructTime, "tm_isdst", _, tm_isdst);
}
};
void add_module_time(VM* vm){
PyObject* mod = vm->new_module("time");
PyStructTime::register_class(vm, mod);
vm->bind_func<0>(mod, "time", [](VM* vm, ArgsView args) {
auto now = std::chrono::system_clock::now();
return VAR(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() / 1000.0);
});
vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
f64 seconds = CAST_F(args[0]);
auto begin = std::chrono::system_clock::now();
while(true){
auto now = std::chrono::system_clock::now();
f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
if(elapsed >= seconds) break;
}
return vm->None;
});
vm->bind_func<0>(mod, "localtime", [](VM* vm, ArgsView args) {
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);
return VAR_T(PyStructTime, t);
});
}
void add_module_sys(VM* vm){
PyObject* mod = vm->new_module("sys");
vm->setattr(mod, "version", VAR(PK_VERSION));
vm->setattr(mod, "platform", VAR(kPlatformStrings[PK_SYS_PLATFORM]));
PyObject* stdout_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
PyObject* stderr_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
vm->setattr(mod, "stdout", stdout_);
vm->setattr(mod, "stderr", stderr_);
vm->bind_func<1>(stdout_, "write", [](VM* vm, ArgsView args) {
Str& s = CAST(Str&, args[0]);
vm->stdout_write(s);
return vm->None;
});
vm->bind_func<1>(stderr_, "write", [](VM* vm, ArgsView args) {
Str& s = CAST(Str&, args[0]);
vm->_stderr(s.data, s.size);
return vm->None;
});
}
void add_module_json(VM* vm){
PyObject* mod = vm->new_module("json");
vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args) {
std::string_view sv;
if(is_non_tagged_type(args[0], vm->tp_bytes)){
sv = PK_OBJ_GET(Bytes, args[0]).sv();
}else{
sv = CAST(Str&, args[0]).sv();
}
CodeObject_ code = vm->compile(sv, "<json>", JSON_MODE);
return vm->_exec(code, vm->top_frame()->_module);
});
vm->bind_func<1>(mod, "dumps", [](VM* vm, ArgsView args) {
return vm->py_json(args[0]);
});
}
// https://docs.python.org/3.5/library/math.html
void add_module_math(VM* vm){
PyObject* mod = vm->new_module("math");
mod->attr().set("pi", VAR(3.1415926535897932384));
mod->attr().set("e" , VAR(2.7182818284590452354));
mod->attr().set("inf", VAR(std::numeric_limits<double>::infinity()));
mod->attr().set("nan", VAR(std::numeric_limits<double>::quiet_NaN()));
vm->bind_func<1>(mod, "ceil", PK_LAMBDA(VAR((i64)std::ceil(CAST_F(args[0])))));
vm->bind_func<1>(mod, "fabs", PK_LAMBDA(VAR(std::fabs(CAST_F(args[0])))));
vm->bind_func<1>(mod, "floor", PK_LAMBDA(VAR((i64)std::floor(CAST_F(args[0])))));
vm->bind_func<1>(mod, "fsum", [](VM* vm, ArgsView args) {
List& list = CAST(List&, args[0]);
double sum = 0;
double c = 0;
for(PyObject* arg : list){
double x = CAST_F(arg);
double y = x - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
return VAR(sum);
});
vm->bind_func<2>(mod, "gcd", [](VM* vm, ArgsView args) {
i64 a = CAST(i64, args[0]);
i64 b = CAST(i64, args[1]);
if(a < 0) a = -a;
if(b < 0) b = -b;
while(b != 0){
i64 t = b;
b = a % b;
a = t;
}
return VAR(a);
});
vm->bind_func<1>(mod, "isfinite", PK_LAMBDA(VAR(std::isfinite(CAST_F(args[0])))));
vm->bind_func<1>(mod, "isinf", PK_LAMBDA(VAR(std::isinf(CAST_F(args[0])))));
vm->bind_func<1>(mod, "isnan", PK_LAMBDA(VAR(std::isnan(CAST_F(args[0])))));
vm->bind_func<2>(mod, "isclose", [](VM* vm, ArgsView args) {
f64 a = CAST_F(args[0]);
f64 b = CAST_F(args[1]);
return VAR(std::fabs(a - b) <= Number::kEpsilon);
});
vm->bind_func<1>(mod, "exp", PK_LAMBDA(VAR(std::exp(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log", PK_LAMBDA(VAR(std::log(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log2", PK_LAMBDA(VAR(std::log2(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log10", PK_LAMBDA(VAR(std::log10(CAST_F(args[0])))));
vm->bind_func<2>(mod, "pow", PK_LAMBDA(VAR(std::pow(CAST_F(args[0]), CAST_F(args[1])))));
vm->bind_func<1>(mod, "sqrt", PK_LAMBDA(VAR(std::sqrt(CAST_F(args[0])))));
vm->bind_func<1>(mod, "acos", PK_LAMBDA(VAR(std::acos(CAST_F(args[0])))));
vm->bind_func<1>(mod, "asin", PK_LAMBDA(VAR(std::asin(CAST_F(args[0])))));
vm->bind_func<1>(mod, "atan", PK_LAMBDA(VAR(std::atan(CAST_F(args[0])))));
vm->bind_func<2>(mod, "atan2", PK_LAMBDA(VAR(std::atan2(CAST_F(args[0]), CAST_F(args[1])))));
vm->bind_func<1>(mod, "cos", PK_LAMBDA(VAR(std::cos(CAST_F(args[0])))));
vm->bind_func<1>(mod, "sin", PK_LAMBDA(VAR(std::sin(CAST_F(args[0])))));
vm->bind_func<1>(mod, "tan", PK_LAMBDA(VAR(std::tan(CAST_F(args[0])))));
vm->bind_func<1>(mod, "degrees", PK_LAMBDA(VAR(CAST_F(args[0]) * 180 / 3.1415926535897932384)));
vm->bind_func<1>(mod, "radians", PK_LAMBDA(VAR(CAST_F(args[0]) * 3.1415926535897932384 / 180)));
vm->bind_func<1>(mod, "modf", [](VM* vm, ArgsView args) {
f64 i;
f64 f = std::modf(CAST_F(args[0]), &i);
return VAR(Tuple({VAR(f), VAR(i)}));
});
vm->bind_func<1>(mod, "factorial", [](VM* vm, ArgsView args) {
i64 n = CAST(i64, args[0]);
if(n < 0) vm->ValueError("factorial() not defined for negative values");
i64 r = 1;
for(i64 i=2; i<=n; i++) r *= i;
return VAR(r);
});
}
void add_module_traceback(VM* vm){
PyObject* mod = vm->new_module("traceback");
vm->bind_func<0>(mod, "print_exc", [](VM* vm, ArgsView args) {
if(vm->_last_exception==nullptr) vm->ValueError("no exception");
Exception& e = _CAST(Exception&, vm->_last_exception);
vm->stdout_write(e.summary());
return vm->None;
});
vm->bind_func<0>(mod, "format_exc", [](VM* vm, ArgsView args) {
if(vm->_last_exception==nullptr) vm->ValueError("no exception");
Exception& e = _CAST(Exception&, vm->_last_exception);
return VAR(e.summary());
});
}
void add_module_dis(VM* vm){
PyObject* mod = vm->new_module("dis");
static const auto get_code = [](VM* vm, PyObject* obj)->CodeObject_{
if(is_type(obj, vm->tp_str)){
const Str& source = CAST(Str, obj);
return vm->compile(source, "<dis>", EXEC_MODE);
}
PyObject* f = obj;
if(is_type(f, vm->tp_bound_method)) f = CAST(BoundMethod, obj).func;
return CAST(Function&, f).decl->code;
};
vm->bind_func<1>(mod, "dis", [](VM* vm, ArgsView args) {
CodeObject_ code = get_code(vm, args[0]);
vm->stdout_write(vm->disassemble(code));
return vm->None;
});
}
void add_module_gc(VM* vm){
PyObject* mod = vm->new_module("gc");
vm->bind_func<0>(mod, "collect", PK_LAMBDA(VAR(vm->heap.collect())));
}
} // namespace pkpy

View File

@ -1342,265 +1342,6 @@ void init_builtins(VM* _vm) {
Generator::register_class(_vm, _vm->builtins);
}
void add_module_timeit(VM* vm){
PyObject* mod = vm->new_module("timeit");
vm->bind_func<2>(mod, "timeit", [](VM* vm, ArgsView args) {
PyObject* f = args[0];
i64 iters = CAST(i64, args[1]);
auto now = std::chrono::system_clock::now();
for(i64 i=0; i<iters; i++) vm->call(f);
auto end = std::chrono::system_clock::now();
f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - now).count() / 1000.0;
return VAR(elapsed);
});
}
void add_module_operator(VM* vm){
PyObject* mod = vm->new_module("operator");
vm->bind_func<2>(mod, "lt", [](VM* vm, ArgsView args) { return VAR(vm->py_lt(args[0], args[1]));});
vm->bind_func<2>(mod, "le", [](VM* vm, ArgsView args) { return VAR(vm->py_le(args[0], args[1]));});
vm->bind_func<2>(mod, "eq", [](VM* vm, ArgsView args) { return VAR(vm->py_eq(args[0], args[1]));});
vm->bind_func<2>(mod, "ne", [](VM* vm, ArgsView args) { return VAR(vm->py_ne(args[0], args[1]));});
vm->bind_func<2>(mod, "ge", [](VM* vm, ArgsView args) { return VAR(vm->py_ge(args[0], args[1]));});
vm->bind_func<2>(mod, "gt", [](VM* vm, ArgsView args) { return VAR(vm->py_gt(args[0], args[1]));});
}
struct PyStructTime{
PY_CLASS(PyStructTime, time, struct_time)
int tm_year;
int tm_mon;
int tm_mday;
int tm_hour;
int tm_min;
int tm_sec;
int tm_wday;
int tm_yday;
int tm_isdst;
PyStructTime(std::time_t t){
std::tm* tm = std::localtime(&t);
tm_year = tm->tm_year + 1900;
tm_mon = tm->tm_mon + 1;
tm_mday = tm->tm_mday;
tm_hour = tm->tm_hour;
tm_min = tm->tm_min;
tm_sec = tm->tm_sec;
tm_wday = (tm->tm_wday + 6) % 7;
tm_yday = tm->tm_yday + 1;
tm_isdst = tm->tm_isdst;
}
PyStructTime* _() { return this; }
static void _register(VM* vm, PyObject* mod, PyObject* type){
vm->bind_notimplemented_constructor<PyStructTime>(type);
PY_READONLY_FIELD(PyStructTime, "tm_year", _, tm_year);
PY_READONLY_FIELD(PyStructTime, "tm_mon", _, tm_mon);
PY_READONLY_FIELD(PyStructTime, "tm_mday", _, tm_mday);
PY_READONLY_FIELD(PyStructTime, "tm_hour", _, tm_hour);
PY_READONLY_FIELD(PyStructTime, "tm_min", _, tm_min);
PY_READONLY_FIELD(PyStructTime, "tm_sec", _, tm_sec);
PY_READONLY_FIELD(PyStructTime, "tm_wday", _, tm_wday);
PY_READONLY_FIELD(PyStructTime, "tm_yday", _, tm_yday);
PY_READONLY_FIELD(PyStructTime, "tm_isdst", _, tm_isdst);
}
};
void add_module_time(VM* vm){
PyObject* mod = vm->new_module("time");
PyStructTime::register_class(vm, mod);
vm->bind_func<0>(mod, "time", [](VM* vm, ArgsView args) {
auto now = std::chrono::system_clock::now();
return VAR(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() / 1000.0);
});
vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
f64 seconds = CAST_F(args[0]);
auto begin = std::chrono::system_clock::now();
while(true){
auto now = std::chrono::system_clock::now();
f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
if(elapsed >= seconds) break;
}
return vm->None;
});
vm->bind_func<0>(mod, "localtime", [](VM* vm, ArgsView args) {
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);
return VAR_T(PyStructTime, t);
});
}
void add_module_sys(VM* vm){
PyObject* mod = vm->new_module("sys");
vm->setattr(mod, "version", VAR(PK_VERSION));
vm->setattr(mod, "platform", VAR(kPlatformStrings[PK_SYS_PLATFORM]));
PyObject* stdout_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
PyObject* stderr_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
vm->setattr(mod, "stdout", stdout_);
vm->setattr(mod, "stderr", stderr_);
vm->bind_func<1>(stdout_, "write", [](VM* vm, ArgsView args) {
Str& s = CAST(Str&, args[0]);
vm->stdout_write(s);
return vm->None;
});
vm->bind_func<1>(stderr_, "write", [](VM* vm, ArgsView args) {
Str& s = CAST(Str&, args[0]);
vm->_stderr(s.data, s.size);
return vm->None;
});
}
void add_module_json(VM* vm){
PyObject* mod = vm->new_module("json");
vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args) {
std::string_view sv;
if(is_non_tagged_type(args[0], vm->tp_bytes)){
sv = PK_OBJ_GET(Bytes, args[0]).sv();
}else{
sv = CAST(Str&, args[0]).sv();
}
CodeObject_ code = vm->compile(sv, "<json>", JSON_MODE);
return vm->_exec(code, vm->top_frame()->_module);
});
vm->bind_func<1>(mod, "dumps", [](VM* vm, ArgsView args) {
return vm->py_json(args[0]);
});
}
// https://docs.python.org/3.5/library/math.html
void add_module_math(VM* vm){
PyObject* mod = vm->new_module("math");
mod->attr().set("pi", VAR(3.1415926535897932384));
mod->attr().set("e" , VAR(2.7182818284590452354));
mod->attr().set("inf", VAR(std::numeric_limits<double>::infinity()));
mod->attr().set("nan", VAR(std::numeric_limits<double>::quiet_NaN()));
vm->bind_func<1>(mod, "ceil", PK_LAMBDA(VAR((i64)std::ceil(CAST_F(args[0])))));
vm->bind_func<1>(mod, "fabs", PK_LAMBDA(VAR(std::fabs(CAST_F(args[0])))));
vm->bind_func<1>(mod, "floor", PK_LAMBDA(VAR((i64)std::floor(CAST_F(args[0])))));
vm->bind_func<1>(mod, "fsum", [](VM* vm, ArgsView args) {
List& list = CAST(List&, args[0]);
double sum = 0;
double c = 0;
for(PyObject* arg : list){
double x = CAST_F(arg);
double y = x - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
return VAR(sum);
});
vm->bind_func<2>(mod, "gcd", [](VM* vm, ArgsView args) {
i64 a = CAST(i64, args[0]);
i64 b = CAST(i64, args[1]);
if(a < 0) a = -a;
if(b < 0) b = -b;
while(b != 0){
i64 t = b;
b = a % b;
a = t;
}
return VAR(a);
});
vm->bind_func<1>(mod, "isfinite", PK_LAMBDA(VAR(std::isfinite(CAST_F(args[0])))));
vm->bind_func<1>(mod, "isinf", PK_LAMBDA(VAR(std::isinf(CAST_F(args[0])))));
vm->bind_func<1>(mod, "isnan", PK_LAMBDA(VAR(std::isnan(CAST_F(args[0])))));
vm->bind_func<2>(mod, "isclose", [](VM* vm, ArgsView args) {
f64 a = CAST_F(args[0]);
f64 b = CAST_F(args[1]);
return VAR(std::fabs(a - b) <= Number::kEpsilon);
});
vm->bind_func<1>(mod, "exp", PK_LAMBDA(VAR(std::exp(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log", PK_LAMBDA(VAR(std::log(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log2", PK_LAMBDA(VAR(std::log2(CAST_F(args[0])))));
vm->bind_func<1>(mod, "log10", PK_LAMBDA(VAR(std::log10(CAST_F(args[0])))));
vm->bind_func<2>(mod, "pow", PK_LAMBDA(VAR(std::pow(CAST_F(args[0]), CAST_F(args[1])))));
vm->bind_func<1>(mod, "sqrt", PK_LAMBDA(VAR(std::sqrt(CAST_F(args[0])))));
vm->bind_func<1>(mod, "acos", PK_LAMBDA(VAR(std::acos(CAST_F(args[0])))));
vm->bind_func<1>(mod, "asin", PK_LAMBDA(VAR(std::asin(CAST_F(args[0])))));
vm->bind_func<1>(mod, "atan", PK_LAMBDA(VAR(std::atan(CAST_F(args[0])))));
vm->bind_func<2>(mod, "atan2", PK_LAMBDA(VAR(std::atan2(CAST_F(args[0]), CAST_F(args[1])))));
vm->bind_func<1>(mod, "cos", PK_LAMBDA(VAR(std::cos(CAST_F(args[0])))));
vm->bind_func<1>(mod, "sin", PK_LAMBDA(VAR(std::sin(CAST_F(args[0])))));
vm->bind_func<1>(mod, "tan", PK_LAMBDA(VAR(std::tan(CAST_F(args[0])))));
vm->bind_func<1>(mod, "degrees", PK_LAMBDA(VAR(CAST_F(args[0]) * 180 / 3.1415926535897932384)));
vm->bind_func<1>(mod, "radians", PK_LAMBDA(VAR(CAST_F(args[0]) * 3.1415926535897932384 / 180)));
vm->bind_func<1>(mod, "modf", [](VM* vm, ArgsView args) {
f64 i;
f64 f = std::modf(CAST_F(args[0]), &i);
return VAR(Tuple({VAR(f), VAR(i)}));
});
vm->bind_func<1>(mod, "factorial", [](VM* vm, ArgsView args) {
i64 n = CAST(i64, args[0]);
if(n < 0) vm->ValueError("factorial() not defined for negative values");
i64 r = 1;
for(i64 i=2; i<=n; i++) r *= i;
return VAR(r);
});
}
void add_module_traceback(VM* vm){
PyObject* mod = vm->new_module("traceback");
vm->bind_func<0>(mod, "print_exc", [](VM* vm, ArgsView args) {
if(vm->_last_exception==nullptr) vm->ValueError("no exception");
Exception& e = _CAST(Exception&, vm->_last_exception);
vm->stdout_write(e.summary());
return vm->None;
});
vm->bind_func<0>(mod, "format_exc", [](VM* vm, ArgsView args) {
if(vm->_last_exception==nullptr) vm->ValueError("no exception");
Exception& e = _CAST(Exception&, vm->_last_exception);
return VAR(e.summary());
});
}
void add_module_dis(VM* vm){
PyObject* mod = vm->new_module("dis");
static const auto get_code = [](VM* vm, PyObject* obj)->CodeObject_{
if(is_type(obj, vm->tp_str)){
const Str& source = CAST(Str, obj);
return vm->compile(source, "<dis>", EXEC_MODE);
}
PyObject* f = obj;
if(is_type(f, vm->tp_bound_method)) f = CAST(BoundMethod, obj).func;
return CAST(Function&, f).decl->code;
};
vm->bind_func<1>(mod, "dis", [](VM* vm, ArgsView args) {
CodeObject_ code = get_code(vm, args[0]);
vm->stdout_write(vm->disassemble(code));
return vm->None;
});
}
void add_module_gc(VM* vm){
PyObject* mod = vm->new_module("gc");
vm->bind_func<0>(mod, "collect", PK_LAMBDA(VAR(vm->heap.collect())));
}
void VM::post_init(){
init_builtins(this);

View File

@ -221,13 +221,6 @@ except:
assert type(12 * '12') is str
# 未完全测试准确性-----------------------------------------------
# 116: 554: _vm->bind_method<1>("str", "index", [](VM* vm, ArgsView args) {
# #####: 555: const Str& self = _CAST(Str&, args[0]);
# #####: 556: const Str& sub = CAST(Str&, args[1]);
# #####: 557: int index = self.index(sub);
# #####: 558: if(index == -1) vm->ValueError("substring not found");
# #####: 559: return VAR(index);
# #####: 560: });
# test str.index:
assert type('25363546'.index('63')) is int
try:
@ -239,11 +232,6 @@ except:
# 未完全测试准确性-----------------------------------------------
# 116: 562: _vm->bind_method<1>("str", "find", [](VM* vm, ArgsView args) {
# #####: 563: const Str& self = _CAST(Str&, args[0]);
# #####: 564: const Str& sub = CAST(Str&, args[1]);
# #####: 565: return VAR(self.index(sub));
# -: 566: });
# test str.find:
assert '25363546'.find('63') == 3
assert '25363546'.find('err') == -1
@ -258,15 +246,6 @@ except:
pass
# 未完全测试准确性----------------------------------------------
# 116: 648: _vm->bind_method<1>("list", "index", [](VM* vm, ArgsView args) {
# #####: 649: List& self = _CAST(List&, args[0]);
# #####: 650: PyObject* obj = args[1];
# #####: 651: for(int i=0; i<self.size(); i++){
# #####: 652: if(vm->py_eq(self[i], obj)) return VAR(i);
# -: 653: }
# #####: 654: vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
# #####: 655: return vm->None;
# #####: 656: });
# test list.index:
assert type([1,2,3,4,5].index(4)) is int
try:
@ -279,18 +258,6 @@ except:
# 未完全测试准确性----------------------------------------------
# 118: 658: _vm->bind_method<1>("list", "remove", [](VM* vm, ArgsView args) {
# 1: 659: List& self = _CAST(List&, args[0]);
# 1: 660: PyObject* obj = args[1];
# 2: 661: for(int i=0; i<self.size(); i++){
# 2: 662: if(vm->py_eq(self[i], obj)){
# 1: 663: self.erase(i);
# 1: 664: return vm->None;
# -: 665: }
# -: 666: }
# #####: 667: vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
# #####: 668: return vm->None;
# 1: 669: });
# test list.remove:
try:
[1,2,3,4,5].remove(6)
@ -301,22 +268,6 @@ except:
# 未完全测试准确性----------------------------------------------
# 2536: 671: _vm->bind_method<-1>("list", "pop", [](VM* vm, ArgsView args) {
# 1210: 672: List& self = _CAST(List&, args[0]);
# 1210: 673: if(args.size() == 1+0){
# 1208: 674: if(self.empty()) vm->IndexError("pop from empty list");
# 1208: 675: return self.popx_back();
# -: 676: }
# 2: 677: if(args.size() == 1+1){
# 2: 678: int index = CAST(int, args[1]);
# 2: 679: index = vm->normalized_index(index, self.size());
# 2: 680: PyObject* ret = self[index];
# 2: 681: self.erase(index);
# -: 682: return ret;
# -: 683: }
# #####: 684: vm->TypeError("pop() takes at most 1 argument");
# #####: 685: return vm->None;
# 1210: 686: });
# test list.pop:
try:
[1,2,3,4,5].pop(1,2,3,4)
@ -407,13 +358,6 @@ assert slice.__dict__['start'].__signature__ == 'start'
assert type(repr(slice(1,1,1))) is str
# /************ mappingproxy ************/
# 未完全测试准确性-----------------------------------------------
# 116: 968: _vm->bind_method<0>("mappingproxy", "keys", [](VM* vm, ArgsView args) {
# #####: 969: MappingProxy& self = _CAST(MappingProxy&, args[0]);
# #####: 970: List keys;
# #####: 971: for(StrName name : self.attr().keys()) keys.push_back(VAR(name.sv()));
# #####: 972: return VAR(std::move(keys));
# #####: 973: });
# test mappingproxy.keys:
class A():
def __init__(self):
@ -427,12 +371,6 @@ assert type(my_mappingproxy.keys()) is list
# 未完全测试准确性-----------------------------------------------
# 116: 975: _vm->bind_method<0>("mappingproxy", "values", [](VM* vm, ArgsView args) {
# #####: 976: MappingProxy& self = _CAST(MappingProxy&, args[0]);
# #####: 977: List values;
# #####: 978: for(auto& item : self.attr().items()) values.push_back(item.second);
# #####: 979: return VAR(std::move(values));
# #####: 980: });
# test mappingproxy.values:
class A():
def __init__(self):
@ -499,25 +437,6 @@ assert type(repr(my_mappingproxy)) is str
# /************ dict ************/
# 未完全测试准确性-----------------------------------------------
# 202: 1033: _vm->bind_method<-1>("dict", "__init__", [](VM* vm, ArgsView args){
# 43: 1034: if(args.size() == 1+0) return vm->None;
# 42: 1035: if(args.size() == 1+1){
# 42: 1036: auto _lock = vm->heap.gc_scope_lock();
# 42: 1037: Dict& self = _CAST(Dict&, args[0]);
# 42: 1038: List& list = CAST(List&, args[1]);
# 165: 1039: for(PyObject* item : list){
# 123: 1040: Tuple& t = CAST(Tuple&, item);
# 123: 1041: if(t.size() != 2){
# #####: 1042: vm->ValueError("dict() takes an iterable of tuples (key, value)");
# #####: 1043: return vm->None;
# -: 1044: }
# 123: 1045: self.set(t[0], t[1]);
# 246: 1046: }
# 42: 1047: return vm->None;
# 42: 1048: }
# #####: 1049: vm->TypeError("dict() takes at most 1 argument");
# #####: 1050: return vm->None;
# 43: 1051: });
# test dict:
assert type(dict([(1,2)])) is dict
@ -546,22 +465,7 @@ except:
for k in {1:2, 2:3, 3:4}:
assert k in [1,2,3]
# 未完全测试准确性-----------------------------------------------
# 166: 1098: _vm->bind_method<-1>("dict", "get", [](VM* vm, ArgsView args) {
# 25: 1099: Dict& self = _CAST(Dict&, args[0]);
# 25: 1100: if(args.size() == 1+1){
# #####: 1101: PyObject* ret = self.try_get(args[1]);
# #####: 1102: if(ret != nullptr) return ret;
# #####: 1103: return vm->None;
# 25: 1104: }else if(args.size() == 1+2){
# 25: 1105: PyObject* ret = self.try_get(args[1]);
# 25: 1106: if(ret != nullptr) return ret;
# 19: 1107: return args[2];
# -: 1108: }
# #####: 1109: vm->TypeError("get() takes at most 2 arguments");
# #####: 1110: return vm->None;
# 25: 1111: });
# test dict.get
assert {1:2, 3:4}.get(1) == 2