Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
154 changes: 154 additions & 0 deletions lib/python/_weakref.x
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 2 additions & 1 deletion lib/python/core.x
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
11 changes: 7 additions & 4 deletions lib/python/parse.x
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 "<lambda>" names dflts rest-sym () kwonly nreq) inner))
(def body ((%py-fn-prelude "<lambda>" 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 "<lambda>" names () rest-sym () (%py-kwo-bare kwonly ())
((%py-fn-prelude "<lambda>" 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)
"<lambda>" (pair (lit list) names) nreq (not (null? rest-sym)) ()
"<lambda>" (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)
"<lambda>" names (python-length names) (not (null? rest-sym)) ()
"<lambda>" 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))
Expand Down
6 changes: 5 additions & 1 deletion lib/python/runtime-flow.x
Original file line number Diff line number Diff line change
Expand Up @@ -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) ())))))))
Expand Down
3 changes: 3 additions & 0 deletions lib/python/util.x
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
143 changes: 143 additions & 0 deletions stdlib/weakref.py
Original file line number Diff line number Diff line change
@@ -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 "<weakref at %#x; dead>" % id(self)
return "<weakref at %#x; to %r at %#x>" % (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 "<finalize object at %#x; dead>" % id(self)
return "<finalize object at %#x; for %r at %#x>" % (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)
Loading
Loading