blueloveTH 1 year ago
parent
commit
3eec499b95
2 changed files with 25 additions and 7 deletions
  1. 8 1
      include/pocketpy/pocketpy.h
  2. 17 6
      src/modules/json.c

+ 8 - 1
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), "<string>", 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 *************/
 

+ 17 - 6
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, "<json>", 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;
-}
+}
+
+bool py_json_loads(const char* source) {
+    py_GlobalRef mod = py_getmodule("json");
+    return py_exec(source, "<json>", EVAL_MODE, mod);
+}
+
+bool py_pusheval(const char* expr, py_GlobalRef module) {
+    bool ok = py_exec(expr, "<string>", EVAL_MODE, module);
+    if(!ok) return false;
+    py_push(py_retval());
+    return true;
+}