1 (use-modules (srfi srfi-9)
6 ;; @@: Using immutable agendas here, so wouldn't it make sense to
7 ;; replace this queue stuff with using pfds based immutable queues?
9 (define-immutable-record-type <agenda>
10 (make-agenda-intern queue prompt-tag port-mapping)
13 (prompt-tag agenda-prompt-tag)
14 (port-mapping agenda-port-mapping))
16 (define (make-async-prompt-tag)
17 (make-prompt-tag "prompt"))
19 (define* (make-agenda #:key
21 (prompt (make-prompt-tag))
22 (port-mapping (make-port-mapping)))
23 (make-agenda-intern queue prompt port-mapping))
25 (define (make-port-mapping)
28 (define* (port-mapping-set! port-mapping port #:optional read write except)
29 "Sets port-mapping for reader / writer / exception handlers"
30 (if (not (or read write except))
31 (throw 'no-handlers-given "No handlers given for port" port))
32 (hashq-set! port-mapping port
33 `#(,read ,write ,except)))
35 (define (port-mapping-remove! port-mapping port)
36 (hashq-remove! port-mapping port))
38 ;; TODO: This is O(n), I'm pretty sure :\
39 ;; ... it might be worthwhile for us to have a
40 ;; port-mapping record that keeps a count of how many
41 ;; handlers (maybe via a promise?)
42 (define (port-mapping-empty? port-mapping)
43 "Is this port mapping empty?"
44 (eq? (hash-count (const #t) port-mapping) 0))
46 (define (port-mapping-non-empty? port-mapping)
47 "Whether this port-mapping contains any elements"
48 (not (port-mapping-empty? port-mapping)))
50 (define %current-agenda (make-parameter #f))
52 (define* (start-agenda agenda #:optional stop-condition)
53 (let loop ((agenda agenda))
55 ;; @@: Hm, maybe here would be a great place to handle
56 ;; select'ing on ports.
57 ;; We could compose over agenda-run-once and agenda-read-ports
58 (parameterize ((%current-agenda agenda))
59 (agenda-run-once agenda))))
60 (if (and stop-condition (stop-condition agenda))
64 (define (agenda-run-once agenda)
65 "Run once through the agenda, and produce a new agenda
67 (define (call-proc proc)
69 (agenda-prompt-tag agenda)
75 (let ((queue (agenda-queue agenda))
76 (next-queue (make-q)))
77 (while (not (q-empty? queue))
78 (let* ((proc (q-pop! queue))
79 (proc-result (call-proc proc))
82 (enq! next-queue new-proc))))
83 ;; @@: We might support delay-wrapped procedures here
85 ((? procedure? new-proc)
87 (((? procedure? new-procs) ...)
94 ;; TODO: Selecting on ports would happen here?
95 ;; Return new agenda, with next queue set
96 (set-field agenda (agenda-queue) next-queue)))