-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathasync.sc
108 lines (78 loc) · 3.39 KB
/
async.sc
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
(library (core async)
(export
generator
yield
coroutine
coroutine-run
coroutine-dead?
coroutine-status
coroutine-running?
)
(import
(chezscheme))
(define *meta-cont* (box (lambda (v) (error 'core-async "No Top Level generator"))))
(define-syntax generator
(lambda (stx)
(syntax-case stx ()
((generator expr ...) #`(letrec ((#,(datum->syntax #'generator `*cont*)
(lambda (v)
(reset-cont expr ...))))
(lambda ()
(#,(datum->syntax #'generator `*cont*) (void))))))))
(define-syntax yield
(lambda (stx)
(syntax-case stx ()
((yield v) #`(call/cc (lambda (k)
(set! #,(datum->syntax #'yield `*cont*) (lambda (va) (reset-cont (k va))))
((unbox *meta-cont*) v)))))))
(define-syntax reset-cont
(syntax-rules ()
((_ expr ...) (let ((preserved (unbox *meta-cont*)))
(call/cc (lambda (k)
(dynamic-wind
(lambda () (set-box! *meta-cont* k))
(lambda () (let ((result (let () expr ...)))
((unbox *meta-cont*) result)))
(lambda () (set-box! *meta-cont* preserved)))))))))
(define-syntax coroutine
(lambda (stx)
(syntax-case stx ()
((coroutine (arguments ...) expr ...)
(with-syntax ((yield (datum->syntax #'coroutine 'yield)))
#`(letrec ((arguments #f) ...
(*cont*
(lambda args
(define args-tmp args)
(define-syntax yield
(lambda (stx)
(syntax-case stx ()
((_) #`(yield (void)))
((_ v) #`(call/cc (lambda (k)
(set! *cont*
(lambda args
(define args-tmp args)
(begin (set! arguments (car args-tmp))
(set! args-tmp (cdr args-tmp))) ...
(reset-cont (k))))
((unbox *meta-cont*) v)))))))
(begin (set! arguments (car args-tmp))
(set! args-tmp (cdr args-tmp))) ...
(reset-cont expr ... (set! *status* 'dead))))
(*status*
'running))
(lambda cmd
(if (eq? (car cmd) 'status) *status*
(apply *cont* (cdr cmd))))))))))
(define coroutine-run
(lambda (c . args)
(apply c (cons 'run args))))
(define coroutine-dead?
(lambda (c)
(eq? (c 'status) 'dead)))
(define coroutine-running?
(lambda (c)
(eq? (c 'status) 'running)))
(define coroutine-status
(lambda (c)
(c 'status)))
)