aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/promise.lux
blob: cb15c95c953e4c863649b0976f97247260b851bf (plain)
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
(;module:
  lux
  (lux (data (coll [list #* "" Functor<List>])
             number
             text/format)
       [io #- run]
       function
       (control functor
                applicative
                ["M" monad #+ do Monad]
                ["p" parser])
       [macro]
       (macro ["s" syntax #+ syntax: Syntax])
       (concurrency [atom #+ Atom atom])
       ))

(def: #export concurrency-level
  Nat
  (_lux_proc ["process" "concurrency-level"] []))

(type: (Promise-State a)
  {#value (Maybe a)
   #observers (List (-> a (IO Unit)))})

(type: #export (Promise a)
  {#;doc "Represents values produced by asynchronous computations (unlike IO, which is synchronous)."}
  (Atom (Promise-State a)))

(def: #hidden (promise' ?value)
  (All [a] (-> (Maybe a) (Promise a)))
  (atom {#value ?value
         #observers (list)}))

(syntax: #export (promise [type s;any])
  {#;doc (doc "Makes an uninitialized Promise (in this example, of Unit)."
              (promise Unit))}
  (wrap (list (` (: (Promise (~ type))
                    (promise' #;None))))))

(def: #export (poll promise)
  {#;doc "Polls a Promise's value."}
  (All [a] (-> (Promise a) (Maybe a)))
  (|> (atom;get promise)
      io;run
      (get@ #value)))

(def: #export (resolved? promise)
  {#;doc "Checks whether a Promise's value has already been resolved."}
  (All [a] (-> (Promise a) Bool))
  (case (poll promise)
    #;None
    false

    (#;Some _)
    true))

(def: #export (resolve value promise)
  {#;doc "Sets an Promise's value if it has not been done yet."}
  (All [a] (-> a (Promise a) (IO Bool)))
  (do Monad<IO>
    [old (atom;get promise)]
    (case (get@ #value old)
      (#;Some _)
      (wrap false)

      #;None
      (do @
        [#let [new (set@ #value (#;Some value) old)]
         succeeded? (atom;compare-and-swap old new promise)]
        (if succeeded?
          (do @
            [_ (M;map @ (function [f] (f value))
                      (get@ #observers old))]
            (wrap true))
          (resolve value promise))))))

(def: (await f promise)
  (All [a] (-> (-> a (IO Unit)) (Promise a) Unit))
  (let [old (io;run (atom;get promise))]
    (case (get@ #value old)
      (#;Some value)
      (io;run (f value))

      #;None
      (let [new (update@ #observers (|>. (#;Cons f)) old)]
        (if (io;run (atom;compare-and-swap old new promise))
          []
          (await f promise))))))

(struct: #export _ (Functor Promise)
  (def: (map f fa)
    (let [fb (promise ($ +1))]
      (exec (await (function [a] (do Monad<IO>
                                   [_ (resolve (f a) fb)]
                                   (wrap [])))
                   fa)
        fb))))

(struct: #export _ (Applicative Promise)
  (def: functor Functor<Promise>)

  (def: (wrap a)
    (atom {#value (#;Some a)
           #observers (list)}))

  (def: (apply ff fa)
    (let [fb (promise ($ +1))]
      (exec (await (function [f]
                     (io (await (function [a] (do Monad<IO>
                                                [_ (resolve (f a) fb)]
                                                (wrap [])))
                                fa)))
                   ff)
        fb))
    ))

(struct: #export _ (Monad Promise)
  (def: applicative Applicative<Promise>)

  (def: (join mma)
    (let [ma (promise ($ +0))]
      (exec (await (function [ma']
                     (io (await (function [a']
                                  (do Monad<IO>
                                    [_ (resolve a' ma)]
                                    (wrap [])))
                                ma')))
                   mma)
        ma))))

(def: #export (seq left right)
  {#;doc "Sequencing combinator."}
  (All [a b] (-> (Promise a) (Promise b) (Promise [a b])))
  (do Monad<Promise>
    [a left
     b right]
    (wrap [a b])))

(def: #export (alt left right)
  {#;doc "Heterogeneous alternative combinator."}
  (All [a b] (-> (Promise a) (Promise b) (Promise (| a b))))
  (let [a|b (promise (Either ($ +0) ($ +1)))]
    (with-expansions
      [<sides> (do-template [<promise> <tag>]
                 [(await (function [value]
                           (do Monad<IO>
                             [_ (resolve (<tag> value) a|b)]
                             (wrap [])))
                         <promise>)]

                 [left  #;Left]
                 [right #;Right]
                 )]
      (exec <sides>
        a|b))))

(def: #export (either left right)
  {#;doc "Homogeneous alternative combinator."}
  (All [a] (-> (Promise a) (Promise a) (Promise a)))
  (let [left||right (promise ($ +0))]
    (with-expansions
      [<sides> (do-template [<promise>]
                 [(await [(function [value]
                            (do Monad<IO>
                              [_ (resolve value left||right)]
                              (wrap [])))]
                         <promise>)]

                 [left]
                 [right]
                 )]
      (exec <sides>
        left||right))))

(def: #export (future computation)
  {#;doc "Runs an I/O computation on its own process and returns an Promise that will eventually host its result."}
  (All [a] (-> (IO a) (Promise a)))
  (let [!out (promise ($ +0))]
    (exec (_lux_proc ["process" "future"] [(io (io;run (resolve (io;run computation)
                                                                !out)))])
      !out)))

(def: #export (wait time)
  {#;doc "Returns a Promise that will be resolved after the specified amount of milliseconds."}
  (-> Nat (Promise Unit))
  (let [!out (promise Unit)]
    (exec (_lux_proc ["process" "schedule"] [time (resolve [] !out)])
      !out)))

(def: #export (time-out time promise)
  {#;doc "Wait for a Promise to be resolved within the specified amount of milliseconds."}
  (All [a] (-> Nat (Promise a) (Promise (Maybe a))))
  (alt (wait time) promise))

(def: #export (delay time value)
  {#;doc "Delivers a value after a certain period has passed."}
  (All [a] (-> Nat a (Promise a)))
  (:: Functor<Promise> map (const value) (wait time)))