Debian Codegraph @

%3a166/show-shared.sls

raw
1
2 ;;; shared structure utilities
3
4 (library (srfi :166 show-shared)
5 (export
6 extract-shared-objects call-with-shared-ref call-with-shared-ref/cdr)
7 (import (rnrs)
8 (rnrs mutable-pairs)
9 (only (srfi :69)
10 make-hash-table
11 hash-table-delete!
12 hash-table-ref
13 hash-table-ref/default
14 hash-table-set!
15 hash-table-update!/default
16 hash-table-walk))
17 (begin
18 (define (extract-shared-objects x cyclic-only?)
19 (let ((seen (make-hash-table eq?)))
20 ;; find shared references
21 (let find ((x x))
22 (cond ;; only interested in pairs and vectors (and records later)
23 ((or (pair? x) (vector? x))
24 ;; increment the count
25 (hash-table-update!/default seen x (lambda (n) (+ n 1)) 0)
26 ;; walk if this is the first time
27 (cond
28 ((> (hash-table-ref seen x) 1))
29 ((pair? x)
30 (find (car x))
31 (find (cdr x)))
32 ((vector? x)
33 (do ((i 0 (+ i 1)))
34 ((= i (vector-length x)))
35 (find (vector-ref x i)))))
36 ;; delete if this shouldn't count as a shared reference
37 (if (and cyclic-only? (<= (hash-table-ref/default seen x 0) 1))
38 (hash-table-delete! seen x)))))
39 ;; extract shared references
40 (let ((res (make-hash-table eq?))
41 (count 0))
42 (hash-table-walk
43 seen
44 (lambda (k v)
45 (cond
46 ((> v 1)
47 (hash-table-set! res k (cons count #f))
48 (set! count (+ count 1))))))
49 (cons res 0))))
50
51 (define (gen-shared-ref cell shares)
52 (set-car! cell (cdr shares))
53 (set-cdr! cell #t)
54 (set-cdr! shares (+ (cdr shares) 1))
55 (string-append (number->string (car cell))))
56
57 (define (call-with-shared-ref obj shares each proc)
58 (let ((cell (hash-table-ref/default (car shares) obj #f)))
59 (cond
60 ((and (pair? cell) (cdr cell))
61 (each "#" (number->string (car cell)) "#"))
62 ((pair? cell)
63 (each "#" (gen-shared-ref cell shares) "=" proc))
64 (else
65 (each proc)))))
66
67 (define (call-with-shared-ref/cdr obj shares each proc . o)
68 (let ((sep (if (pair? o) (car o) ""))
69 (cell (hash-table-ref/default (car shares) obj #f)))
70 (cond
71 ((and (pair? cell) (cdr cell))
72 (each sep ". #" (number->string (car cell)) "#"))
73 ((pair? cell)
74 (each sep ". #" (gen-shared-ref cell shares) "=(" proc ")"))
75 (else
76 (each sep proc)))))
77 ))