blueloveTH 1 year ago
parent
commit
7215f48007
2 changed files with 27 additions and 1 deletions
  1. 1 1
      src/interpreter/ceval.c
  2. 26 0
      src/public/modules.c

+ 1 - 1
src/interpreter/ceval.c

@@ -137,7 +137,7 @@ FrameResult VM__run_top_frame(VM* self) {
                 Function__ctor(ud, decl, &frame->module);
                 if(decl->nested) {
                     ud->closure = FastLocals__to_namedict(frame->locals, frame->locals_co);
-                    py_Name name = py_namev(c11_string__sv(decl->code.name));
+                    py_Name name = py_name(decl->code.name->data);
                     // capture itself to allow recursion
                     NameDict__set(ud->closure, name, *SP());
                 }

+ 26 - 0
src/public/modules.c

@@ -382,9 +382,35 @@ py_TValue pk_builtins__register() {
     return *builtins;
 }
 
+static bool function__closure__getter(int argc, py_Ref argv) {
+    PY_CHECK_ARGC(1);
+    Function* ud = py_touserdata(argv);
+    if(!ud->closure) {
+        py_newnone(py_retval());
+        return true;
+    }
+    py_Ref r0 = py_pushtmp();
+    py_Ref retval = py_pushtmp();
+    py_newdict(retval);
+    c11__foreach(NameDict_KV, ud->closure, it) {
+        // printf("%s -> %s\n", py_name2str(it->key), py_tpname(it->value.type));
+        py_newstr(r0, py_name2str(it->key));
+        py_dict__setitem(retval, r0, &it->value);
+        if(py_checkexc()) {
+            py_shrink(2);
+            return false;
+        }
+    }
+    py_assign(py_retval(), retval);
+    py_shrink(2);
+    return true;
+}
+
 py_Type pk_function__register() {
     py_Type type =
         pk_newtype("function", tp_object, NULL, (void (*)(void*))Function__dtor, false, true);
+
+    py_bindproperty(type, "__closure__", function__closure__getter, NULL);
     return type;
 }