From ec36c33390baafcabdc25d03db02de3b5069cca5 Mon Sep 17 00:00:00 2001 From: Jon Ruttan Date: Sat, 28 Nov 2026 09:46:34 -0500 Subject: [PATCH] feat: weakref -- ref, finalize, callbacks at gc.collect() stdlib/weakref.py builds ref and finalize on lib/python/_weakref.x: a weak cell holds its object by address, which the collector does not follow, and a free hook flags the cells whose object (or whose ref) the sweep is about to free. gc.collect() then runs the callbacks of the dead refs, newest first, through the new python-gc-after hook. Also fixes lambda **kw, which the lambda emitter dropped. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + lib/python/_weakref.x | 154 ++++++++++++++++++++++++++++++++ lib/python/core.x | 3 +- lib/python/parse.x | 11 ++- lib/python/runtime-flow.x | 6 +- lib/python/util.x | 3 + stdlib/weakref.py | 143 +++++++++++++++++++++++++++++ tests/specs/D14-weakref.spec.md | 58 ++++++++++++ 8 files changed, 373 insertions(+), 6 deletions(-) create mode 100644 lib/python/_weakref.x create mode 100644 stdlib/weakref.py create mode 100644 tests/specs/D14-weakref.spec.md diff --git a/README.md b/README.md index 45c98cb..a91ba28 100644 --- a/README.md +++ b/README.md @@ -261,6 +261,7 @@ rarely touch the same lines. | `textwrap` | Python | `stdlib/textwrap.py` | | `traceback` | x | `lib/python/runtime-flow.x` | | `types` | x | `lib/python/runtime-flow.x` | +| `weakref` | Python | `stdlib/weakref.py`, on `lib/python/_weakref.x` | ### Not planned yet: the network diff --git a/lib/python/_weakref.x b/lib/python/_weakref.x new file mode 100644 index 0000000..7be1d09 --- /dev/null +++ b/lib/python/_weakref.x @@ -0,0 +1,154 @@ +; # x-python -- Python on x-lang +; +; ## lib/python/_weakref.x -- the _weakref module +; +; @description The weak cell that stdlib/weakref.py builds ref and finalize +; on: an object held by its address, which the collector does not follow, +; and a free hook that tells which cells the next sweep leaves dangling. +; @author [Jon Ruttan](jonruttan@gmail.com) +; @copyright 2026 Jon Ruttan +; @license MIT No Attribution (MIT-0) +; +; ., ., +; {O,O} +; ( ) +; " " +; +; A REFERENCE THE COLLECTOR CANNOT SEE is an address: an int, which marks +; nothing. (ptr ->obj) reads it back as the object, and the platform's heap +; does not move, so the address is the object for as long as it lives. +; +; KNOWING WHEN IT DIES is the free hook. The engine fires each free hook +; once a collection, after the mark and before the sweep (x_heap_sweep_phase), +; so at that moment an object's MARK flag says whether the sweep keeps it. +; The hook walks the cells and flags each one whose object is unmarked: dead. +; It also reads the mark of the Python ref that owns the cell, held by +; address the same way, and flags the cell gone when the ref itself is being +; collected -- a ref that dies first calls no callback, as CPython's does not. +; +; THE HOOK WRITES NOTHING NEW. Whatever it allocates is born after the mark, +; unmarked, and the sweep frees it; that is harmless for its own frames but +; fatal for anything it stores. So it only sets the first of a cell that +; already exists to a symbol, which the base already holds. +; +; CALLBACKS RUN AT gc.collect(). A cell flagged dead is answered by dead(), +; newest first as CPython calls them, and weakref.py runs each callback after +; the collect returns -- never inside it, since a callback is Python, and +; Python allocates. A collection the runtime makes on its own (the GC tick in +; util.x) flags cells as well, and their callbacks wait for the next +; gc.collect(). A ref's object reads as None from the moment it is flagged. +; +; A cell is a list, (state referent-address ref-address callback): states +; live, dead, gone. + +(module python/_weakref) +(import python/modules PyModule) +(import python/core python-gc-after python-list-new python-module-new python-tuple-new) +(import x/core/doors int& int= int+ int->ptr obj->ptr ptr->int ptr->obj ptr-ref-word) + +(def %wk-flags-off (* %obj-slot-flags %word-size)) +(def %wk-addr (fn (_ o) (ptr->int (obj->ptr o)))) +(def %wk-marked? + (fn (_ a) (if (int= (int& (ptr-ref-word (int->ptr a) %wk-flags-off) %obj-flag-mark) 0) #f #t))) + +; every cell not yet answered, newest first, and how many were made since the +; list was last pruned +(def %wk-cells (pair () ())) +(def %wk-made (pair 0 ())) +(def %wk-hooked (pair #f ())) + +(def %wk-state (fn (_ c) (first c))) +(def %wk-obj (fn (_ c) (first (rest c)))) +(def %wk-ref (fn (_ c) (first (rest (rest c))))) +(def %wk-callback (fn (_ c) (first (rest (rest (rest c)))))) + +; THE HOOK: no allocation that outlives it +(def %wk-flag! + (fn (self cs) + (if (null? cs) () + (let ((c (first cs))) + (match + ((eq? (%wk-state c) (lit live)) + (match + ((%wk-marked? (%wk-ref c)) + (if (%wk-marked? (%wk-obj c)) () (%set-first! c (lit dead)))) + (#t (%set-first! c (lit gone))))) + (#t ())) + (self (rest cs)))))) +(def %wk-hook (fn (_) (%wk-flag! (first %wk-cells)))) + +; the cells still live, in order +(def %wk-live + (fn (self cs) + (match + ((null? cs) ()) + ((eq? (%wk-state (first cs)) (lit live)) (pair (first cs) (self (rest cs)))) + (#t (self (rest cs)))))) +(def %wk-prune! + (fn (_) + (%set-first! %wk-cells (%wk-live (first %wk-cells))) + (%set-first! %wk-made 0))) + +(def %wk-new + (fn (_ obj ref callback) + (if (first %wk-hooked) () + (do ((prim-ref (lit heap) (lit free-hook!)) %wk-hook) + (%set-first! %wk-hooked #t))) + (if (int= (first %wk-made) 1024) (%wk-prune!) ()) + (%set-first! %wk-made (int+ (first %wk-made) 1)) + (let ((c (list (lit live) (%wk-addr obj) (%wk-addr ref) callback))) + (%set-first! %wk-cells (pair c (first %wk-cells))) + c))) + +(def %wk-get + (fn (_ c) + (if (eq? (%wk-state c) (lit live)) (ptr->obj (int->ptr (%wk-obj c))) ()))) + +; (ref . callback) for each cell flagged dead whose callback is not None, +; newest first; every cell answered or gone leaves the list +(def %wk-dead + (fn (self cs) + (match + ((null? cs) ()) + ((eq? (%wk-state (first cs)) (lit dead)) + (let ((c (first cs))) + (%set-first! c (lit gone)) + (if (null? (%wk-callback c)) + (self (rest cs)) + (pair (python-tuple-new (list (ptr->obj (int->ptr (%wk-ref c))) (%wk-callback c))) + (self (rest cs)))))) + (#t (self (rest cs)))))) + +; the live cells on OBJ, newest first +(def %wk-on + (fn (self cs a) + (match + ((null? cs) ()) + ((if (eq? (%wk-state (first cs)) (lit live)) (int= (%wk-obj (first cs)) a) #f) + (pair (first cs) (self (rest cs) a))) + (#t (self (rest cs) a))))) + +(def python-_weakref-module + (fn (_) + (python-module-new "_weakref" + (list + (pair "new" (fn (_ obj ref callback) (%wk-new obj ref callback))) + (pair "get" (fn (_ c) (%wk-get c))) + (pair "alive" (fn (_ c) (eq? (%wk-state c) (lit live)))) + (pair "kill" (fn (_ c) (%set-first! c (lit gone)) ())) + (pair "dead" + (fn (_) + (let ((out (%wk-dead (first %wk-cells)))) + (%wk-prune!) + (python-list-new out)))) + (pair "refs" + (fn (_ obj) + (python-list-new + (List map (fn (_ c) (ptr->obj (int->ptr (%wk-ref c)))) + (%wk-on (first %wk-cells) (%wk-addr obj)))))) + (pair "on_collect" (fn (_ f) (%set-first! python-gc-after f) ())))))) + +; The row in the table of built-in modules (python/modules). +(PyModule def-static! (lit _weakref) (fn (_ cls) (python-_weakref-module))) + +(provide python/_weakref python-_weakref-module) diff --git a/lib/python/core.x b/lib/python/core.x index c1f9c8c..8e78528 100644 --- a/lib/python/core.x +++ b/lib/python/core.x @@ -100,7 +100,7 @@ python-repl-choose! python-repl-install! python-repl-line python-repl-register! python-repr-of python-rev-onto python-reverse python-set-elems python-set-is python-set-nth python-sig! python-slice-span python-str python-str-cps python-str-display python-str-is - python-str-new python-str-of-x python-sub python-subclass? python-sweep! python-gc-now! python-take + python-str-new python-str-of-x python-sub python-subclass? python-sweep! python-gc-now! python-gc-after python-take python-takes-at-most! python-text->x python-th-float python-tuple-elems python-tuple-is python-tuple-new python-tuple-of-list python-type-of python-banner python-batch python-lex python-parse python-parse-expr python-parse-single python-repl-print @@ -127,6 +127,7 @@ (import python/os) (import python/_random) (import python/_sre) +(import python/_weakref) (import python/struct) (import python/sys) (import python/line diff --git a/lib/python/parse.x b/lib/python/parse.x index b9daa18..7aec227 100644 --- a/lib/python/parse.x +++ b/lib/python/parse.x @@ -794,6 +794,9 @@ (def dflts (first (rest sig))) (def rest-name (first (rest (rest sig)))) (def rest-sym (if (null? rest-name) () (%py-name->sym rest-name))) + ; the **name, which a def's emission binds the same way + (def kw-name (List ref 3 sig)) + (def kw-sym (if (null? kw-name) () (%py-name->sym kw-name))) (def kwonly (List ref 4 sig)) (def nreq (- (python-length names) (python-length dflts))) ; a `:=` in the body binds the lambda's own name, as one in a def body @@ -803,22 +806,22 @@ (%py-param-syms sig))) (def inner (if (null? own) (first b) (list (lit let) (%py-lets own () ()) (first b)))) - (def body ((%py-fn-prelude "" names dflts rest-sym () kwonly nreq) inner)) + (def body ((%py-fn-prelude "" names dflts rest-sym kw-sym kwonly nreq) inner)) ; what its __code__ holds takes no default, as a def's does not (def code-body (if (if (null? dflts) (null? (%py-kwo-dflts kwonly ())) #f) body - ((%py-fn-prelude "" names () rest-sym () (%py-kwo-bare kwonly ()) + ((%py-fn-prelude "" names () rest-sym kw-sym (%py-kwo-bare kwonly ()) (python-length names)) inner))) (def sig-form (list (lit python-sig!) (list (lit fn) (pair (lit %py-fn) (lit %py-more)) body) - "" (pair (lit list) names) nreq (not (null? rest-sym)) () + "" (pair (lit list) names) nreq (not (null? rest-sym)) kw-name (pair (lit list) (%py-kwo-names kwonly ())) #t (list (lit %py-here)) ; what its __code__ is made of (python/runtime-str.x) (list (lit lit) (list (list (lit fn) (pair (lit %py-fn) (lit %py-more)) code-body) - "" names (python-length names) (not (null? rest-sym)) () + "" names (python-length names) (not (null? rest-sym)) kw-name (%py-kwo-names kwonly ()) (%py-co-close co co-line))))) (def all-dflts (%py-append dflts (%py-kwo-dflts kwonly ()))) (pair (if (null? all-dflts) sig-form (list (lit let) (%py-dflt-lets all-dflts 0) sig-form)) diff --git a/lib/python/runtime-flow.x b/lib/python/runtime-flow.x index 4dab80e..060b552 100644 --- a/lib/python/runtime-flow.x +++ b/lib/python/runtime-flow.x @@ -1078,7 +1078,11 @@ (fn (_) (python-module-new "gc" (list - (pair "collect" (fn (_ . a) (%seq (python-gc-now!) 0))) + (pair "collect" + (fn (_ . a) + (python-gc-now!) + (let ((after (first python-gc-after))) (if (null? after) () (%py-call after))) + 0)) (pair "isenabled" (fn (_) (first %py-gc-on))) (pair "enable" (fn (_) (%seq (%set-first! %py-gc-on #t) ()))) (pair "disable" (fn (_) (%seq (%set-first! %py-gc-on #f) ()))))))) diff --git a/lib/python/util.x b/lib/python/util.x index fd5257e..6660bfc 100644 --- a/lib/python/util.x +++ b/lib/python/util.x @@ -108,6 +108,9 @@ (%set-first! %py-gc-every %py-gc-first-every) (%set-first! %py-gc-next 0) (%set-first! %py-gc-last 0))) +; what gc.collect() calls after it collects: a Python callable, or (). +; _weakref sets it, to run the callbacks of the refs the collect killed. +(def python-gc-after (pair () ())) (def python-gc-now! (fn (_) (heap-collect) diff --git a/stdlib/weakref.py b/stdlib/weakref.py new file mode 100644 index 0000000..1058a62 --- /dev/null +++ b/stdlib/weakref.py @@ -0,0 +1,143 @@ +"""Weak references: ref and finalize, as CPython's weakref module has them. + +A ref holds its object by address, in the module _weakref +(lib/python/_weakref.x), so the collector does not see it; the collector's +free hook tells which refs a collection leaves dangling. A dead ref answers +None, and its callback is called with it, newest ref first. finalize is +CPython's: a ref whose callback is the finalizer, kept alive by a registry. + +Divergences: there is no reference counting here, so an object dies at a +collection, and callbacks run when gc.collect() returns -- the collections +the runtime makes on its own clear refs but leave their callbacks for the next +gc.collect(). Finalizers do not run at exit. ref(o) makes a new ref each time +where CPython hands back the one it has. proxy, WeakMethod, WeakSet and the +weak dictionaries are not here yet. +""" + +import _weakref +import sys + +__all__ = ["ref", "getweakrefcount", "getweakrefs", "ReferenceType", "finalize"] + +# CPython refuses these, and here some are not heap objects at all: an int, a +# None or a bool may be a constant the whole runtime shares. +_NOT_WEAK = (type(None), bool, int, float, complex, str, bytes, bytearray, + tuple, list, dict, type(Ellipsis), type(NotImplemented)) + + +def _check(ob): + if type(ob) in _NOT_WEAK: + raise TypeError("cannot create weak reference to %r object" + % type(ob).__name__) + + +class ReferenceType: + """A weak reference to an object: calling it answers the object, or None + once the object has been collected.""" + + def __init__(self, ob, callback=None): + _check(ob) + self.__callback__ = callback + self._hash = None + self._cell = _weakref.new(ob, self, callback) + + def __call__(self): + return _weakref.get(self._cell) + + def __repr__(self): + ob = self() + if ob is None: + return "" % id(self) + return "" % (id(self), type(ob).__name__, id(ob)) + + def __eq__(self, other): + if not isinstance(other, ReferenceType): + return NotImplemented + a, b = self(), other() + if a is None or b is None: + return self is other + return a == b + + def __ne__(self, other): + eq = self.__eq__(other) + return eq if eq is NotImplemented else not eq + + def __hash__(self): + if self._hash is None: + ob = self() + if ob is None: + raise TypeError("weak object has gone away") + self._hash = hash(ob) + return self._hash + + +ref = ReferenceType + + +def getweakrefcount(ob): + return len(_weakref.refs(ob)) + + +def getweakrefs(ob): + return _weakref.refs(ob) + + +class _FinalizeInfo: + pass + + +class finalize: + """Call func(*args, **kwargs) when obj is collected, unless the finalizer + has been called or detached first.""" + + _registry = {} + + def __init__(self, obj, func, *args, **kwargs): + _check(obj) + info = _FinalizeInfo() + info.weakref = ref(obj, self) + info.func = func + info.args = args + info.kwargs = kwargs or None + finalize._registry[self] = info + + def __call__(self, _=None): + info = finalize._registry.pop(self, None) + if info: + return info.func(*info.args, **(info.kwargs or {})) + + def detach(self): + info = finalize._registry.get(self) + obj = info and info.weakref() + if obj is not None and finalize._registry.pop(self, None): + return (obj, info.func, info.args, info.kwargs or {}) + + def peek(self): + info = finalize._registry.get(self) + obj = info and info.weakref() + if obj is not None: + return (obj, info.func, info.args, info.kwargs or {}) + + @property + def alive(self): + return self in finalize._registry + + def __repr__(self): + info = finalize._registry.get(self) + obj = info and info.weakref() + if obj is None: + return "" % id(self) + return "" % (id(self), type(obj).__name__, id(obj)) + + +def _run_callbacks(): + for r, callback in _weakref.dead(): + try: + callback(r) + except Exception as e: + print("Exception ignored while calling weakref callback %r:" % (callback,), + file=sys.stderr) + print("%s: %s" % (type(e).__name__, e), file=sys.stderr) + + +_weakref.on_collect(_run_callbacks) diff --git a/tests/specs/D14-weakref.spec.md b/tests/specs/D14-weakref.spec.md new file mode 100644 index 0000000..8f7c56c --- /dev/null +++ b/tests/specs/D14-weakref.spec.md @@ -0,0 +1,58 @@ +# weakref: weak references and finalizers + +`stdlib/weakref.py`, on the weak cell in `lib/python/_weakref.x`. Each expected +output is a python3.15 run of the same program, its stdout: a callback that +raises reports on stderr. + +### ref answers its object until a collect takes it, then None, and calls its callback with itself + +```python +(python-run "import weakref, gc\nclass A:\n def __str__(self):\n return \"\"\nfor v in (None, True, 0, 1.5, \"s\", b\"b\", (), [], {}):\n try:\n weakref.ref(v)\n except TypeError as e:\n print(type(v).__name__, e)\ndef cb(r):\n print(\"callback\", r(), type(r).__name__)\ndef test():\n a = A()\n r = weakref.ref(a, cb)\n print(r(), r() is a, r.__callback__ is cb, weakref.getweakrefcount(a), weakref.getweakrefs(a) == [r])\n a = None\n gc.collect()\n print(r())\n b = A()\n r2 = weakref.ref(b, cb)\n r2 = None\n gc.collect()\n b = None\n gc.collect()\n print(\"no callback for a ref that died first\")\ntest()\nprint(weakref.ReferenceType is weakref.ref, isinstance(weakref.ref(A()), weakref.ref))\n") +``` +--- +```output +NoneType cannot create weak reference to 'NoneType' object +bool cannot create weak reference to 'bool' object +int cannot create weak reference to 'int' object +float cannot create weak reference to 'float' object +str cannot create weak reference to 'str' object +bytes cannot create weak reference to 'bytes' object +tuple cannot create weak reference to 'tuple' object +list cannot create weak reference to 'list' object +dict cannot create weak reference to 'dict' object + True True 1 True +callback None ReferenceType +None +no callback for a ref that died first +True True +``` + +### refs and finalizers on one object are called newest first + +```python +(python-run "import weakref, gc\nclass A:\n pass\ndef test():\n a = A()\n r1 = weakref.ref(a, lambda r: print(\"ref1\", r()))\n f1 = weakref.finalize(a, lambda: print(\"finalize1\"))\n r2 = weakref.ref(a, lambda r: print(\"ref2\", r()))\n f2 = weakref.finalize(a, print, \"finalize2\", \"with\", \"args\")\n print(r1() is a, f1.alive, r2() is a, f2.alive)\n a = None\n gc.collect()\n print(r1(), f1.alive, r2(), f2.alive)\ntest()\n") +``` +--- +```output +True True True True +finalize2 with args +ref2 None +finalize1 +ref1 None +None False None False +``` + +### finalize: alive, peek, detach and call, and a callback that raises + +```python +(python-run "import weakref, gc\nclass A:\n pass\ndef show(t):\n return None if t is None else (type(t[0]).__name__, t[2], t[3])\na = A()\nf = weakref.finalize(a, lambda *args, **kwargs: (args, kwargs), 1, 2, k=3)\nprint(f.alive, show(f.peek()))\nprint(f(), f.alive, f.peek(), f(), f.detach())\ng = weakref.finalize(a, print, \"never\")\nprint(show(g.detach()), g.alive, g())\ndef test():\n b = A()\n weakref.finalize(b, lambda: 1 / 0)\n weakref.finalize(b, print, \"finalized\")\n b = None\n gc.collect()\n print(\"collect done\")\ntest()\nprint((lambda a, *r, b=1, **kw: (a, r, b, kw))(1, 2, b=3, c=4), (lambda **kw: kw)(x=1))\n") +``` +--- +```output +True ('A', (1, 2), {'k': 3}) +((1, 2), {'k': 3}) False None None None +('A', ('never',), {}) False None +finalized +collect done +(1, (2,), 3, {'c': 4}) {'x': 1} +```