/
trivial-garbage.lisp
477 lines (434 loc) · 18.3 KB
/
trivial-garbage.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10 -*-
;;;; The above modeline is required for Genera. Do not change.
;;
;;; trivial-garbage.lisp --- Trivial Garbage!
;;;
;;; This software is placed in the public domain by Luis Oliveira
;;; <loliveira@common-lisp.net> and is provided with absolutely no
;;; warranty.
#+xcvb (module ())
(defpackage #:trivial-garbage
(:use #:cl)
(:shadow #:make-hash-table)
(:nicknames #:tg)
(:export #:gc
#:make-weak-pointer
#:weak-pointer-value
#:weak-pointer-p
#:make-weak-hash-table
#:hash-table-weakness
#:finalize
#:cancel-finalization)
(:documentation
"@a[http://common-lisp.net/project/trivial-garbage]{trivial-garbage}
provides a portable API to finalizers, weak hash-tables and weak
pointers on all major implementations of the Common Lisp
programming language. For a good introduction to these
data-structures, have a look at
@a[http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html]{Weak
References: Data Types and Implementation} by Bruno Haible.
Source code is available at
@a[https://github.com/trivial-garbage/trivial-garbage]{github},
which you are welcome to use for submitting patches and/or
@a[https://github.com/trivial-garbage/trivial-garbage/issues]{bug
reports}. Discussion takes place on
@a[http://lists.common-lisp.net/cgi-bin/mailman/listinfo/trivial-garbage-devel]{trivial-garbage-devel
at common-lisp.net}.
@a[http://common-lisp.net/project/trivial-garbage/releases/]{Tarball
releases} are available, but the easiest way to install this
library is via @a[http://www.quicklisp.org/]{Quicklisp}:
@code{(ql:quickload :trivial-garbage)}.
@begin[Weak Pointers]{section}
A @em{weak pointer} holds an object in a way that does not prevent
it from being reclaimed by the garbage collector. An object
referenced only by weak pointers is considered unreachable (or
\"weakly reachable\") and so may be collected at any time. When
that happens, the weak pointer's value becomes @code{nil}.
@aboutfun{make-weak-pointer}
@aboutfun{weak-pointer-value}
@aboutfun{weak-pointer-p}
@end{section}
@begin[Weak Hash-Tables]{section}
A @em{weak hash-table} is one that weakly references its keys
and/or values. When both key and value are unreachable (or weakly
reachable) that pair is reclaimed by the garbage collector.
@aboutfun{make-weak-hash-table}
@aboutfun{hash-table-weakness}
@end{section}
@begin[Finalizers]{section}
A @em{finalizer} is a hook that is executed after a given object
has been reclaimed by the garbage collector.
@aboutfun{finalize}
@aboutfun{cancel-finalization}
@end{section}"))
(in-package #:trivial-garbage)
;;;; GC
(defun gc (&key full verbose)
"Initiates a garbage collection. @code{full} forces the collection
of all generations, when applicable. When @code{verbose} is
@em{true}, diagnostic information about the collection is printed
if possible."
(declare (ignorable verbose full))
#+(or cmu scl) (ext:gc :verbose verbose :full full)
#+sbcl (sb-ext:gc :full full)
#+allegro (excl:gc (not (null full)))
#+(or abcl clisp) (ext:gc)
#+ecl (si:gc t)
#+openmcl (ccl:gc)
#+corman (ccl:gc (if full 3 0))
#+lispworks (hcl:gc-generation (if full t 0))
#+clasp (gctools:garbage-collect)
#+mezzano (mezzano.extensions:gc :full full)
#+genera (scl:let-globally ((si:gc-report-stream *standard-output*)
(si:gc-reports-enable verbose)
(si:gc-ephemeral-reports-enable verbose)
(si:gc-warnings-enable verbose))
(if full
(sys:gc-immediately t)
(si:ephemeral-gc-flip))))
;;;; Weak Pointers
#+openmcl
(defvar *weak-pointers* (cl:make-hash-table :test 'eq :weak :value)
"Weak value hash-table mapping between pseudo weak pointers and its values.")
#+genera
(defvar *weak-pointers* (scl:make-hash-table :test 'eq :gc-protect-values nil)
"Weak value hash-table mapping between pseudo weak pointers and its values.")
#+(or allegro openmcl lispworks genera)
(defstruct (weak-pointer (:constructor %make-weak-pointer))
#-(or openmcl genera) pointer)
(defun make-weak-pointer (object)
"Creates a new weak pointer which points to @code{object}. For
portability reasons, @code{object} must not be @code{nil}."
(assert (not (null object)))
#+sbcl (sb-ext:make-weak-pointer object)
#+(or cmu scl) (ext:make-weak-pointer object)
#+clisp (ext:make-weak-pointer object)
#+abcl (ext:make-weak-reference object)
#+ecl (ext:make-weak-pointer object)
#+allegro
(let ((wv (excl:weak-vector 1)))
(setf (svref wv 0) object)
(%make-weak-pointer :pointer wv))
#+(or openmcl genera)
(let ((wp (%make-weak-pointer)))
(setf (gethash wp *weak-pointers*) object)
wp)
#+corman (ccl:make-weak-pointer object)
#+lispworks
(let ((array (make-array 1 :weak t)))
(setf (svref array 0) object)
(%make-weak-pointer :pointer array))
#+clasp (core:make-weak-pointer object)
#+mezzano (mezzano.extensions:make-weak-pointer object))
#-(or allegro openmcl lispworks genera)
(defun weak-pointer-p (object)
"Returns @em{true} if @code{object} is a weak pointer and @code{nil}
otherwise."
#+sbcl (sb-ext:weak-pointer-p object)
#+(or cmu scl) (ext:weak-pointer-p object)
#+clisp (ext:weak-pointer-p object)
#+abcl (typep object 'ext:weak-reference)
#+ecl (typep object 'ext:weak-pointer)
#+corman (ccl:weak-pointer-p object)
#+clasp (core:weak-pointer-valid object)
#+mezzano (mezzano.extensions:weak-pointer-p object))
(defun weak-pointer-value (weak-pointer)
"If @code{weak-pointer} is valid, returns its value. Otherwise,
returns @code{nil}."
#+sbcl (values (sb-ext:weak-pointer-value weak-pointer))
#+(or cmu scl) (values (ext:weak-pointer-value weak-pointer))
#+clisp (values (ext:weak-pointer-value weak-pointer))
#+abcl (values (ext:weak-reference-value weak-pointer))
#+ecl (values (ext:weak-pointer-value weak-pointer))
#+allegro (svref (weak-pointer-pointer weak-pointer) 0)
#+(or openmcl genera) (values (gethash weak-pointer *weak-pointers*))
#+corman (ccl:weak-pointer-obj weak-pointer)
#+lispworks (svref (weak-pointer-pointer weak-pointer) 0)
#+clasp (core:weak-pointer-value weak-pointer)
#+mezzano (values (mezzano.extensions:weak-pointer-value object)))
;;;; Weak Hash-tables
;;; Allegro can apparently create weak hash-tables with both weak keys
;;; and weak values but it's not obvious whether it's an OR or an AND
;;; relation. TODO: figure that out.
(defun weakness-keyword-arg (weakness)
(declare (ignorable weakness))
#+(or sbcl abcl clasp ecl-weak-hash mezzano) :weakness
#+(or clisp openmcl) :weak
#+lispworks :weak-kind
#+allegro (case weakness (:key :weak-keys) (:value :values))
#+cmu :weak-p
#+genera :gc-protect-values)
(defvar *weakness-warnings* '()
"List of weaknesses that have already been warned about this
session. Used by `weakness-missing'.")
(defun weakness-missing (weakness errorp)
"Signal an error or warning, depending on ERRORP, about lack of Lisp
support for WEAKNESS."
(cond (errorp
(error "Your Lisp does not support weak ~(~A~) hash-tables."
weakness))
((member weakness *weakness-warnings*) nil)
(t (push weakness *weakness-warnings*)
(warn "Your Lisp does not support weak ~(~A~) hash-tables."
weakness))))
(defun weakness-keyword-opt (weakness errorp)
(declare (ignorable errorp))
(ecase weakness
(:key
#+(or lispworks sbcl abcl clasp clisp openmcl ecl-weak-hash mezzano) :key
#+(or allegro cmu) t
#-(or lispworks sbcl abcl clisp openmcl allegro cmu ecl-weak-hash clasp mezzano)
(weakness-missing weakness errorp))
(:value
#+allegro :weak
#+(or clisp openmcl sbcl abcl lispworks cmu ecl-weak-hash mezzano) :value
#+genera nil
#-(or allegro clisp openmcl sbcl abcl lispworks cmu ecl-weak-hash mezzano genera)
(weakness-missing weakness errorp))
(:key-or-value
#+(or clisp sbcl abcl cmu mezzano) :key-or-value
#+lispworks :either
#-(or clisp sbcl abcl lispworks cmu mezzano)
(weakness-missing weakness errorp))
(:key-and-value
#+(or clisp abcl sbcl cmu ecl-weak-hash mezzano) :key-and-value
#+lispworks :both
#-(or clisp sbcl abcl lispworks cmu ecl-weak-hash mezzano)
(weakness-missing weakness errorp))))
(defun make-weak-hash-table (&rest args &key weakness (weakness-matters t)
#+openmcl (test #'eql)
&allow-other-keys)
"Returns a new weak hash table. In addition to the standard
arguments accepted by @code{cl:make-hash-table}, this function adds
extra keywords: @code{:weakness} being the kind of weak table it
should create, and @code{:weakness-matters} being whether an error
should be signalled when that weakness isn't available (the default
is to signal an error). @code{weakness} can be one of @code{:key},
@code{:value}, @code{:key-or-value}, @code{:key-and-value}.
If @code{weakness} is @code{:key} or @code{:value}, an entry is
kept as long as its key or value is reachable, respectively. If
@code{weakness} is @code{:key-or-value} or @code{:key-and-value},
an entry is kept if either or both of its key and value are
reachable, respectively.
@code{tg::make-hash-table} is available as an alias for this
function should you wish to import it into your package and shadow
@code{cl:make-hash-table}."
(remf args :weakness)
(remf args :weakness-matters)
(if weakness
(let ((arg (weakness-keyword-arg weakness))
(opt (weakness-keyword-opt weakness weakness-matters)))
(apply #-genera #'cl:make-hash-table #+genera #'scl:make-hash-table
#+openmcl :test #+openmcl (if (eq opt :key) #'eq test)
#+clasp :test #+clasp #'eq
(if arg
(list* arg opt args)
args)))
(apply #'cl:make-hash-table args)))
;;; If you want to use this function to override CL:MAKE-HASH-TABLE,
;;; it's necessary to shadow-import it. For example:
;;;
;;; (defpackage #:foo
;;; (:use #:common-lisp #:trivial-garbage)
;;; (:shadowing-import-from #:trivial-garbage #:make-hash-table))
;;;
(defun make-hash-table (&rest args)
(apply #'make-weak-hash-table args))
(defun hash-table-weakness (ht)
"Returns one of @code{nil}, @code{:key}, @code{:value},
@code{:key-or-value} or @code{:key-and-value}."
#-(or allegro sbcl abcl clisp cmu openmcl lispworks
ecl-weak-hash clasp mezzano genera)
(declare (ignore ht))
;; keep this first if any of the other lisps bugously insert a NIL
;; for the returned (values) even when *read-suppress* is NIL (e.g. clisp)
#.(if (find :sbcl *features*)
(if (find-symbol "HASH-TABLE-WEAKNESS" "SB-EXT")
(read-from-string "(sb-ext:hash-table-weakness ht)")
nil)
(values))
#+abcl (sys:hash-table-weakness ht)
#+ecl-weak-hash (ext:hash-table-weakness ht)
#+allegro (cond ((excl:hash-table-weak-keys ht) :key)
((eq (excl:hash-table-values ht) :weak) :value))
#+clisp (ext:hash-table-weak-p ht)
#+cmu (let ((weakness (lisp::hash-table-weak-p ht)))
(if (eq t weakness) :key weakness))
#+openmcl (ccl::hash-table-weak-p ht)
#+lispworks (system::hash-table-weak-kind ht)
#+clasp (core:hash-table-weakness ht)
#+mezzano (mezzano.extensions:hash-table-weakness ht)
#+genera (if (null (getf (cli::basic-table-options ht) :gc-protect-values t))
:value
nil))
;;;; Finalizers
;;; Note: Lispworks can't finalize gensyms.
#+(or allegro clisp lispworks openmcl)
(defvar *finalizers*
(cl:make-hash-table :test 'eq
#+allegro :weak-keys #+:allegro t
#+(or clisp openmcl) :weak
#+lispworks :weak-kind
#+(or clisp openmcl lispworks) :key)
"Weak hashtable that holds registered finalizers.")
#+corman
(progn
(defvar *finalizers* '()
"Weak alist that holds registered finalizers.")
(defvar *finalizers-cs* (threads:allocate-critical-section)))
#+lispworks
(progn
(hcl:add-special-free-action 'free-action)
(defun free-action (object)
(let ((finalizers (gethash object *finalizers*)))
(unless (null finalizers)
(mapc #'funcall finalizers)))))
#+mezzano
(progn
(defvar *finalizers*
(cl:make-hash-table :test 'eq :weakness :key)
"Weak hashtable that holds registered finalizers.")
(defvar *finalizers-lock* (mezzano.supervisor:make-mutex '*finalizers-lock*)))
;;; Note: ECL bytecmp does not perform escape analysis and unused
;;; variables are not optimized away from its lexenv. That leads to
;;; closing over whole definition lexenv. That's why we define
;;; EXTEND-FINALIZER-FN which defines lambda outside the lexical scope
;;; of FINALIZE (which inludes object) - to prevent closing over
;;; finalized object. This problem does not apply to C compiler.
#+ecl
(defun extend-finalizer-fn (old-fn new-fn)
(if (null old-fn)
(lambda (obj)
(declare (ignore obj))
(funcall new-fn))
(lambda (obj)
(declare (ignore obj))
(funcall new-fn)
(funcall old-fn nil))))
(defun finalize (object function)
"Pushes a new @code{function} to the @code{object}'s list of
finalizers. @code{function} should take no arguments. Returns
@code{object}.
@b{Note:} @code{function} should not attempt to look at
@code{object} by closing over it because that will prevent it from
being garbage collected."
#+genera (declare (ignore object function))
#+(or cmu scl) (ext:finalize object function)
#+sbcl (sb-ext:finalize object function :dont-save t)
#+abcl (ext:finalize object function)
#+ecl (let* ((old-fn (ext:get-finalizer object))
(new-fn (extend-finalizer-fn old-fn function)))
(ext:set-finalizer object new-fn)
object)
#+allegro
(progn
(push (excl:schedule-finalization
object (lambda (obj) (declare (ignore obj)) (funcall function)))
(gethash object *finalizers*))
object)
#+clasp (progn (gctools:finalize object (lambda (obj) (declare (ignore obj)) (funcall function))) object)
#+clisp
;; The CLISP code used to be a bit simpler but we had to workaround
;; a bug regarding the interaction between GC and weak hashtables.
;; See <http://article.gmane.org/gmane.lisp.clisp.general/11028>
;; and <http://article.gmane.org/gmane.lisp.cffi.devel/994>.
(multiple-value-bind (finalizers presentp)
(gethash object *finalizers* (cons 'finalizers nil))
(unless presentp
(setf (gethash object *finalizers*) finalizers)
(ext:finalize object (lambda (obj)
(declare (ignore obj))
(mapc #'funcall (cdr finalizers)))))
(push function (cdr finalizers))
object)
#+openmcl
(progn
(ccl:terminate-when-unreachable
object (lambda (obj) (declare (ignore obj)) (funcall function)))
;; store number of finalizers
(incf (gethash object *finalizers* 0))
object)
#+corman
(flet ((get-finalizers (obj)
(assoc obj *finalizers* :test #'eq :key #'ccl:weak-pointer-obj)))
(threads:with-synchronization *finalizers-cs*
(let ((pair (get-finalizers object)))
(if (null pair)
(push (list (ccl:make-weak-pointer object) function) *finalizers*)
(push function (cdr pair)))))
(ccl:register-finalization
object (lambda (obj)
(threads:with-synchronization *finalizers-cs*
(mapc #'funcall (cdr (get-finalizers obj)))
(setq *finalizers*
(delete obj *finalizers*
:test #'eq :key #'ccl:weak-pointer-obj)))))
object)
#+lispworks
(progn
(let ((finalizers (gethash object *finalizers*)))
(unless finalizers
(hcl:flag-special-free-action object))
(setf (gethash object *finalizers*)
(cons function finalizers)))
object)
#+mezzano
(mezzano.supervisor:with-mutex (*finalizers-lock*)
(let ((finalizer-key (gethash object *finalizers*)))
(unless finalizer-key
(setf finalizer-key
(mezzano.extensions:make-weak-pointer
object
:finalizer (lambda ()
(let ((finalizers (mezzano.supervisor:with-mutex (*finalizers-lock*)
(prog1
(gethash finalizer-key *finalizers*)
(remhash finalizer-key *finalizers*)))))
(mapc #'funcall finalizers)))))
(setf (gethash object *finalizers*) finalizer-key))
(push function (gethash finalizer-key *finalizers*)))
;; Make sure the object doesn't actually get captured by the finalizer lambda.
(prog1 object
(setf object nil)))
#+genera
(error "Finalizers are not available in Genera."))
(defun cancel-finalization (object)
"Cancels all of @code{object}'s finalizers, if any."
#+genera (declare (ignore object))
#+cmu (ext:cancel-finalization object)
#+scl (ext:cancel-finalization object nil)
#+sbcl (sb-ext:cancel-finalization object)
#+abcl (ext:cancel-finalization object)
#+ecl (ext:set-finalizer object nil)
#+allegro
(progn
(mapc #'excl:unschedule-finalization
(gethash object *finalizers*))
(remhash object *finalizers*))
#+clasp (gctools:definalize object)
#+clisp
(multiple-value-bind (finalizers present-p)
(gethash object *finalizers*)
(when present-p
(setf (cdr finalizers) nil))
(remhash object *finalizers*))
#+openmcl
(let ((count (gethash object *finalizers*)))
(unless (null count)
(dotimes (i count)
(ccl:cancel-terminate-when-unreachable object))))
#+corman
(threads:with-synchronization *finalizers-cs*
(setq *finalizers*
(delete object *finalizers* :test #'eq :key #'ccl:weak-pointer-obj)))
#+lispworks
(progn
(remhash object *finalizers*)
(hcl:flag-not-special-free-action object))
#+mezzano
(mezzano.supervisor:with-mutex (*finalizers-lock*)
(let ((finalizer-key (gethash object *finalizers*)))
(when finalizer-key
(setf (gethash finalizer-key *finalizers*) '()))))
#+genera
(error "Finalizers are not available in Genera."))