From 3eec499b95968b37023a3bd53b14c27f8c692a53 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Mon, 12 Aug 2024 10:54:30 +0800 Subject: [PATCH] ... --- include/pocketpy/pocketpy.h | 9 ++++++++- src/modules/json.c | 23 +++++++++++++++++------ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/include/pocketpy/pocketpy.h b/include/pocketpy/pocketpy.h index 78379525..b5334138 100644 --- a/include/pocketpy/pocketpy.h +++ b/include/pocketpy/pocketpy.h @@ -76,6 +76,8 @@ bool py_exec(const char* source, enum py_CompileMode mode, py_Ref module) PY_RAISE; +#define py_eval(source, module) py_exec((source), "", EVAL_MODE, (module)) + /// Compile a source string into a code object. /// Use python's `exec()` or `eval()` to execute it. bool py_compile(const char* source, @@ -374,6 +376,9 @@ bool py_pushmethod(py_Name name); /// The result will be set to `py_retval()`. /// The stack size will be reduced by `argc + kwargc`. bool py_vectorcall(uint16_t argc, uint16_t kwargc) PY_RAISE; +/// Evaluate an expression and push the result to the stack. +/// This function is used for testing. +bool py_pusheval(const char* expr, py_GlobalRef module) PY_RAISE; /************* Modules *************/ @@ -474,7 +479,9 @@ bool py_repr(py_Ref val) PY_RAISE; /// Python equivalent to `len(val)`. bool py_len(py_Ref val) PY_RAISE; /// Python equivalent to `json.dumps(val)`. -bool py_json(py_Ref val) PY_RAISE; +bool py_json_dumps(py_Ref val) PY_RAISE; +/// Python equivalent to `json.loads(val)`. +bool py_json_loads(const char* source) PY_RAISE; /************* Unchecked Functions *************/ diff --git a/src/modules/json.c b/src/modules/json.c index 693f13e3..55152435 100644 --- a/src/modules/json.c +++ b/src/modules/json.c @@ -10,13 +10,12 @@ static bool json_loads(int argc, py_Ref argv) { PY_CHECK_ARGC(1); PY_CHECK_ARG_TYPE(0, tp_str); const char* source = py_tostr(argv); - py_GlobalRef mod = py_getmodule("json"); - return py_exec(source, "", EVAL_MODE, mod); + return py_json_loads(source); } static bool json_dumps(int argc, py_Ref argv) { PY_CHECK_ARGC(1); - return py_json(argv); + return py_json_dumps(argv); } void pk__add_module_json() { @@ -98,14 +97,26 @@ static bool json__write_object(c11_sbuf* buf, py_TValue* obj) { } } -bool py_json(py_Ref val) { +bool py_json_dumps(py_Ref val) { c11_sbuf buf; c11_sbuf__ctor(&buf); bool ok = json__write_object(&buf, val); - if(!ok){ + if(!ok) { c11_sbuf__dtor(&buf); return false; } c11_sbuf__py_submit(&buf, py_retval()); return true; -} \ No newline at end of file +} + +bool py_json_loads(const char* source) { + py_GlobalRef mod = py_getmodule("json"); + return py_exec(source, "", EVAL_MODE, mod); +} + +bool py_pusheval(const char* expr, py_GlobalRef module) { + bool ok = py_exec(expr, "", EVAL_MODE, module); + if(!ok) return false; + py_push(py_retval()); + return true; +}