package lsp

  1. Overview
  2. Docs
LSP protocol implementation in OCaml

Install

Dune Dependency

Authors

Maintainers

Sources

jsonrpc-1.6.0.tbz
sha256=35e8c7341f8eb1fa39fb0f0e0701a7ed90b9a0bb89ccf84b7ed997cd258cbec3
sha512=c96a7a3ca845ec193e9edc4a74804a22d6e37efc852b54575011879bd2105e0df021408632219f542ca3ad85b36b5c8b72f2b417204d154d5f0dd0839535afa5

doc/src/lsp.fiber/fiber.ml.html

Source file fiber.ml

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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
open! Stdune

type 'a t = ('a -> unit) -> unit

(* This module tries to enforce the following invariants:

   - the execution context passed to a continuation is the same as the current
   one

   - the execution of a fiber always ends with [deref]

   - when an exception is raised by the user code, the exception must be
   forwarded to the execution context that was active at the time the exception
   was raised

   - when an exception is raised by the user code, then we assume that the
   current fiber didn't reach the [deref] point. As a result we have to call
   [deref] at this point on the current execution context

   Remarks:

   - most of the code assumes that errors will be caught by the caller, so when
   we do a context switch, we simply change the current execution context and
   chain to the continuation without catching errors. The current [try..with]
   will catch any raised error and forward to the current execution context. The
   only place we add a [try..with] is at the toplevel or when forking. *)

let of_thunk f k = f () k

module Execution_context : sig
  module K : sig
    (* Represent a suspended fiber *)
    type 'a t

    (* Create a continuation that captures the current execution context *)
    val create : ('a -> unit) -> 'a t

    (* Restart a suspended fiber. [run] doesn't preserve the current execution
       context and should always be called last. *)
    val run : 'a t -> 'a -> unit
  end

  (* Execute the current continuation, making sure to forward errors to the
     current execution context. This function doesn't preserve the current
     execution context. It should be used to execute the current continuation
     before calling [K.run] *)
  val safe_run_k : ('a -> unit) -> 'a -> unit

  (* Execute a function returning a fiber, passing any raised exception to the
     current execution context. This function preserve the current execution
     context. It should be called when creating forks.*)
  val apply : ('a -> 'b t) -> 'a -> 'b t

  val apply2 : ('a -> 'b -> 'c t) -> 'a -> 'b -> 'c t

  (* Add [n] references to the current execution context *)
  val add_refs : int -> unit

  (* Decrese the reference count of the current execution context *)
  val deref : unit -> unit

  (* [wait_errors f] executes [f ()] inside a new execution contexts. Returns a
     fiber that terminates when all the fiber in the sub-context have
     terminated. *)
  val wait_errors : (unit -> 'a t) -> ('a, unit) result t

  (* Set the current error handler. [on_error] is called in the current
     execution context. *)
  val set_error_handler :
    on_error:(Exn_with_backtrace.t -> unit t) -> ('a -> 'b t) -> 'a -> 'b t

  val vars : unit -> Univ_map.t

  val set_vars : Univ_map.t -> ('a -> 'b t) -> 'a -> 'b t

  val set_vars_sync : Univ_map.t -> ('a -> 'b) -> 'a -> 'b

  (* Execute a callback with a fresh execution context. For the toplevel
     [Fiber.run] function. *)
  val new_run : (unit -> 'a) -> 'a

  val reraise_all : Exn_with_backtrace.t list -> unit
end = struct
  type t =
    { on_error : Exn_with_backtrace.t k option
          (* This handler must never raise *)
    ; vars : Univ_map.t
    ; on_release : on_release
    }

  and 'a on_release_exec =
    { k : ('a, unit) result k
    ; mutable ref_count : int
    }

  and on_release =
    | Do_nothing : on_release
    | Exec : _ on_release_exec -> on_release

  and 'a k =
    { run : 'a -> unit
    ; ctx : t
    }

  let create () =
    { on_error = None; vars = Univ_map.empty; on_release = Do_nothing }

  let current = ref (create ())

  let add_refs n =
    let t = !current in
    match t.on_release with
    | Do_nothing -> ()
    | Exec r -> r.ref_count <- r.ref_count + n

  let rec safe_run_k : type a. (a -> unit) -> a -> unit =
   fun k x ->
    try k x with
    | exn -> forward_error exn

  and forward_exn_with_bt t exn =
    match t.on_error with
    | None -> Exn_with_backtrace.reraise exn
    | Some { ctx; run } ->
      current := ctx;
      safe_run_k run exn

  and forward_error exn =
    let exn = Exn_with_backtrace.capture exn in
    forward_exn_with_bt !current exn

  let deref t =
    match t.on_release with
    | Do_nothing -> ()
    | Exec r -> (
      let ref_count = r.ref_count - 1 in
      r.ref_count <- ref_count;
      match ref_count with
      | 0 ->
        current := r.k.ctx;
        (* We need to call [safe_run_k] as we might be the in handler of the
           [try...with] block inside [apply] and so we are no more in a
           [try...with] blocks *)
        safe_run_k r.k.run (Error ())
      | _ -> assert (ref_count > 0))

  let deref () = deref !current

  let wait_errors f k =
    let t = !current in
    let on_release = { k = { ctx = t; run = k }; ref_count = 1 } in
    let child = { t with on_release = Exec on_release } in
    current := child;
    f () (fun x ->
        let ref_count = on_release.ref_count - 1 in
        on_release.ref_count <- ref_count;
        assert (ref_count = 0);
        current := t;
        k (Ok x))

  let set_error_handler ~on_error f x k =
    let t = !current in
    let run exn = on_error exn deref in
    let on_error = Some { run; ctx = t } in
    current := { t with on_error };
    f x (fun x ->
        current := t;
        k x)

  let vars () = !current.vars

  let set_vars vars f x k =
    let t = !current in
    current := { t with vars };
    f x (fun x ->
        current := t;
        k x)

  let set_vars_sync (type b) vars f x : b =
    let t = !current in
    current := { t with vars };
    Exn.protect ~finally:(fun () -> current := t) ~f:(fun () -> f x)

  module K = struct
    type 'a t = 'a k

    let create run = { run; ctx = !current }

    let run { run; ctx } x =
      current := ctx;
      safe_run_k run x
  end

  let apply f x k =
    let backup = !current in
    (try f x k with
    | exn -> forward_error exn);
    current := backup

  let apply2 f x y k =
    let backup = !current in
    (try f x y k with
    | exn -> forward_error exn);
    current := backup

  let reraise_all exns =
    let backup = !current in
    add_refs (List.length exns - 1);
    List.iter exns ~f:(forward_exn_with_bt backup)

  let new_run f =
    let backup = !current in
    Exn.protect
      ~finally:(fun () -> current := backup)
      ~f:(fun () ->
        current := create ();
        f ())
end

module EC = Execution_context
module K = EC.K

let return x k = k x

let never _ = ()

type ('a, 'b) fork_and_join_state =
  | Nothing_yet
  | Got_a of 'a
  | Got_b of 'b

let fork_and_join fa fb k =
  let state = ref Nothing_yet in
  EC.add_refs 1;
  EC.apply fa () (fun a ->
      match !state with
      | Nothing_yet ->
        state := Got_a a;
        EC.deref ()
      | Got_a _ -> assert false
      | Got_b b -> k (a, b));
  fb () (fun b ->
      match !state with
      | Nothing_yet ->
        state := Got_b b;
        EC.deref ()
      | Got_a a -> k (a, b)
      | Got_b _ -> assert false)

let fork_and_join_unit fa fb k =
  let state = ref Nothing_yet in
  EC.add_refs 1;
  EC.apply fa () (fun () ->
      match !state with
      | Nothing_yet ->
        state := Got_a ();
        EC.deref ()
      | Got_a _ -> assert false
      | Got_b b -> k b);
  fb () (fun b ->
      match !state with
      | Nothing_yet ->
        state := Got_b b;
        EC.deref ()
      | Got_a () -> k b
      | Got_b _ -> assert false)

module O = struct
  let ( >>> ) a b k = a (fun () -> b k)

  let ( >>= ) t f k = t (fun x -> f x k)

  let ( >>| ) t f k = t (fun x -> k (f x))

  let ( let+ ) = ( >>| )

  let ( let* ) = ( >>= )

  let ( and* ) a b = fork_and_join (fun () -> a) (fun () -> b)

  let ( and+ ) = ( and* )
end

open O

let map t ~f = t >>| f

let bind t ~f = t >>= f

let both a b =
  let* x = a in
  let* y = b in
  return (x, y)

let sequential_map l ~f =
  let rec loop l acc =
    match l with
    | [] -> return (List.rev acc)
    | x :: l ->
      let* x = f x in
      loop l (x :: acc)
  in
  loop l []

let sequential_iter l ~f =
  let rec loop l =
    match l with
    | [] -> return ()
    | x :: l ->
      let* () = f x in
      loop l
  in
  loop l

let all = sequential_map ~f:Fun.id

let list_of_option_array =
  let rec loop arr i acc =
    if i = 0 then
      acc
    else
      let i = i - 1 in
      match arr.(i) with
      | None -> assert false
      | Some x -> loop arr i (x :: acc)
  in
  fun a -> loop a (Array.length a) []

let parallel_map l ~f k =
  match l with
  | [] -> k []
  | [ x ] -> f x (fun x -> k [ x ])
  | _ ->
    let n = List.length l in
    EC.add_refs (n - 1);
    let left_over = ref n in
    let results = Array.make n None in
    List.iteri l ~f:(fun i x ->
        EC.apply f x (fun y ->
            results.(i) <- Some y;
            decr left_over;
            if !left_over = 0 then
              k (list_of_option_array results)
            else
              EC.deref ()))

let all_concurrently = parallel_map ~f:Fun.id

let[@inline always] parallel_iter_generic ~n ~iter ~f k =
  EC.add_refs (n - 1);
  let left_over = ref n in
  let k () =
    decr left_over;
    if !left_over = 0 then
      k ()
    else
      EC.deref ()
  in
  iter ~f:(fun x -> EC.apply f x k)

let parallel_iter l ~f k =
  match l with
  | [] -> k ()
  | [ x ] -> f x k
  | _ -> parallel_iter_generic ~n:(List.length l) ~iter:(List.iter l) ~f k

let parallel_iter_set (type a s)
    (module S : Set.S with type elt = a and type t = s) t ~(f : a -> unit t) k =
  let len = S.cardinal t in
  match len with
  | 0 -> k ()
  | 1 -> f (Option.value_exn (S.min_elt t)) k
  | n -> parallel_iter_generic ~n ~iter:(S.iter t) ~f k

module Make_map_traversals (Map : Map.S) = struct
  let parallel_iter t ~f k =
    match Map.cardinal t with
    | 0 -> k ()
    | 1 ->
      let x, y = Map.choose t |> Option.value_exn in
      f x y k
    | n ->
      EC.add_refs (n - 1);
      let left_over = ref n in
      let k () =
        decr left_over;
        if !left_over = 0 then
          k ()
        else
          EC.deref ()
      in
      Map.iteri t ~f:(fun x y -> EC.apply2 f x y k)

  let parallel_map t ~f k =
    match Map.cardinal t with
    | 0 -> k Map.empty
    | 1 ->
      let x, y = Map.choose t |> Option.value_exn in
      f x y (fun y -> k (Map.singleton x y))
    | n ->
      EC.add_refs (n - 1);
      let left_over = ref n in
      let cell = ref None in
      let k (refs : _ option ref Map.t) =
        k (Map.mapi refs ~f:(fun _ r -> Option.value_exn !r))
      in
      let refs =
        Map.mapi t ~f:(fun x y ->
            let res = ref None in
            EC.apply2 f x y (fun z ->
                res := Some z;
                decr left_over;
                if !left_over = 0 then
                  Option.iter !cell ~f:k
                else
                  EC.deref ());
            res)
      in
      if !left_over = 0 then
        k refs
      else
        cell := Some refs
end
[@@inline always]

let rec repeat_while : 'a. f:('a -> 'a option t) -> init:'a -> unit t =
 fun ~f ~init ->
  let* result = f init in
  match result with
  | None -> return ()
  | Some init -> repeat_while ~f ~init

module Var = struct
  include Univ_map.Key

  let get var = Univ_map.find (EC.vars ()) var

  let get_exn var = Univ_map.find_exn (EC.vars ()) var

  let set_sync var x f = EC.set_vars_sync (Univ_map.set (EC.vars ()) var x) f ()

  let set var x f k = EC.set_vars (Univ_map.set (EC.vars ()) var x) f () k

  let unset_sync var f =
    EC.set_vars_sync (Univ_map.remove (EC.vars ()) var) f ()

  let unset var f k = EC.set_vars (Univ_map.remove (EC.vars ()) var) f () k

  let create () = create ~name:"var" (fun _ -> Dyn.Encoder.string "var")
end

let with_error_handler f ~on_error k = EC.set_error_handler ~on_error f () k

let wait_errors f k = EC.wait_errors f k

let map_reduce_errors (type a) (module M : Monoid with type t = a) ~on_error f =
  let acc = ref M.empty in
  let on_error exn =
    let+ m = on_error exn in
    acc := M.combine !acc m
  in
  wait_errors (fun () -> with_error_handler ~on_error f) >>| function
  | Ok _ as ok -> ok
  | Error () -> Error !acc

let collect_errors f =
  let module Exns = Monoid.Appendable_list (Exn_with_backtrace) in
  let+ res =
    map_reduce_errors
      (module Exns)
      f
      ~on_error:(fun e -> return (Appendable_list.singleton e))
  in
  match res with
  | Ok x -> Ok x
  | Error l -> Error (Appendable_list.to_list l)

let reraise_all = function
  | [] -> never
  | [ exn ] -> Exn_with_backtrace.reraise exn
  | exns ->
    EC.reraise_all exns;
    never

let finalize f ~finally =
  let* res1 = collect_errors f in
  let* res2 = collect_errors finally in
  let res =
    match (res1, res2) with
    | Ok x, Ok () -> Ok x
    | Error l, Ok _
    | Ok _, Error l ->
      Error l
    | Error l1, Error l2 -> Error (l1 @ l2)
  in
  match res with
  | Ok x -> return x
  | Error l -> reraise_all l

module Ivar = struct
  type 'a state =
    | Full of 'a
    | Empty of 'a K.t Queue.t

  type 'a t = { mutable state : 'a state }

  let create () = { state = Empty (Queue.create ()) }

  let fill t x k =
    match t.state with
    | Full _ -> failwith "Fiber.Ivar.fill"
    | Empty q ->
      t.state <- Full x;
      EC.safe_run_k k ();
      Queue.iter q ~f:(fun k -> K.run k x)

  let read t k =
    match t.state with
    | Full x -> k x
    | Empty q -> Queue.push q (K.create k)

  let peek t k =
    k
      (match t.state with
      | Full x -> Some x
      | Empty _ -> None)
end

module Mvar = struct
  type 'a t =
    { writers : ('a * unit K.t) Queue.t
    ; readers : 'a K.t Queue.t
    ; mutable value : 'a option
    }

  (* Invariant enforced on mvars. We don't actually call this function, but we
     keep it here for documentation and to help understand the implementation: *)
  let _invariant t =
    match t.value with
    | None -> Queue.is_empty t.writers
    | Some _ -> Queue.is_empty t.readers

  let create () =
    { value = None; writers = Queue.create (); readers = Queue.create () }

  let create_full x =
    { value = Some x; writers = Queue.create (); readers = Queue.create () }

  let read t k =
    match t.value with
    | None -> Queue.push t.readers (K.create k)
    | Some v -> (
      match Queue.pop t.writers with
      | None ->
        t.value <- None;
        k v
      | Some (v', w) ->
        t.value <- Some v';
        EC.safe_run_k k v;
        K.run w ())

  let write t x k =
    match t.value with
    | Some _ -> Queue.push t.writers (x, K.create k)
    | None -> (
      match Queue.pop t.readers with
      | None ->
        t.value <- Some x;
        k ()
      | Some r ->
        EC.safe_run_k k ();
        K.run r x)
end

module Mutex = struct
  type t =
    { mutable locked : bool
    ; mutable waiters : unit K.t Queue.t
    }

  let lock t k =
    if t.locked then
      Queue.push t.waiters (K.create k)
    else (
      t.locked <- true;
      k ()
    )

  let unlock t k =
    assert t.locked;
    match Queue.pop t.waiters with
    | None ->
      t.locked <- false;
      k ()
    | Some next ->
      EC.safe_run_k k ();
      K.run next ()

  let with_lock t f =
    let* () = lock t in
    finalize f ~finally:(fun () -> unlock t)

  let create () = { locked = false; waiters = Queue.create () }
end

module Throttle = struct
  type t =
    { mutable size : int
    ; mutable running : int
    ; waiting : unit Ivar.t Queue.t
    }

  let create size = { size; running = 0; waiting = Queue.create () }

  let size t = t.size

  let running t = t.running

  let rec restart t =
    if t.running >= t.size then
      return ()
    else
      match Queue.pop t.waiting with
      | None -> return ()
      | Some ivar ->
        t.running <- t.running + 1;
        let* () = Ivar.fill ivar () in
        restart t

  let resize t n =
    t.size <- n;
    restart t

  let run t ~f =
    finalize
      ~finally:(fun () ->
        t.running <- t.running - 1;
        restart t)
      (fun () ->
        if t.running < t.size then (
          t.running <- t.running + 1;
          f ()
        ) else
          let waiting = Ivar.create () in
          Queue.push t.waiting waiting;
          let* () = Ivar.read waiting in
          f ())
end

module Stream = struct
  module In = struct
    (* Invariant: once [read] has returned [None], it always returns [None] *)
    type nonrec 'a t =
      { mutable read : unit -> 'a option t
      ; mutable reading : bool
      }

    let create_unchecked read = { read; reading = false }

    let create read =
      let t = { read; reading = false } in
      let read () =
        let+ x = read () in
        if Option.is_none x then t.read <- (fun () -> return None);
        x
      in
      t.read <- read;
      t

    let lock t =
      if t.reading then Code_error.raise "Fiber.Stream.In: already reading" [];
      t.reading <- true

    let unlock t = t.reading <- false

    let read t =
      lock t;
      let+ x = t.read () in
      unlock t;
      x

    let empty () = create_unchecked (fun () -> return None)

    let concat (type a) (xs : a t list) =
      let remains = ref xs in
      let rec go () =
        match !remains with
        | [] -> return None
        | x :: xs -> (
          let* v = read x in
          match v with
          | Some v -> return (Some v)
          | None ->
            remains := xs;
            go ())
      in
      create go

    let append x y = concat [ x; y ]

    let of_list xs =
      let xs = ref xs in
      create_unchecked (fun () ->
          match !xs with
          | [] -> return None
          | x :: xs' ->
            xs := xs';
            return (Some x))

    let filter_map t ~f =
      let rec read () =
        t.read () >>= function
        | None ->
          unlock t;
          return None
        | Some x -> (
          match f x with
          | None -> read ()
          | Some y -> return (Some y))
      in
      lock t;
      create_unchecked read

    let sequential_iter t ~f =
      let rec loop t ~f =
        t.read () >>= function
        | None ->
          unlock t;
          return ()
        | Some x ->
          let* () = f x in
          loop t ~f
      in
      lock t;
      loop t ~f

    let parallel_iter t ~f k =
      let n = ref 1 in
      let k () =
        decr n;
        if !n = 0 then (
          unlock t;
          k ()
        ) else
          EC.deref ()
      in
      let rec loop t =
        t.read () (function
          | None -> k ()
          | Some x ->
            EC.add_refs 1;
            incr n;
            EC.apply f x k;
            loop t)
      in
      loop t
  end

  module Out = struct
    type nonrec 'a t = { mutable write : 'a option -> unit t }

    let create write =
      let t = { write } in
      let write x =
        if Option.is_none x then
          t.write <-
            (function
            | None -> return ()
            | Some _ ->
              Code_error.raise "Fiber.Stream.Out: stream output closed" []);
        write x
      in
      t.write <- write;
      t

    let write t x = t.write x

    let null () = create (fun _ -> return ())
  end

  let connect i (o : _ Out.t) =
    In.lock i;
    let rec go () =
      let* a = i.read () in
      let* () = o.write a in
      match a with
      | None ->
        In.unlock i;
        return ()
      | Some _ -> go ()
    in
    go ()

  let supply i (o : _ Out.t) =
    In.lock i;
    let rec go () =
      let* a = i.read () in
      match a with
      | None ->
        In.unlock i;
        return ()
      | Some _ ->
        let* () = o.write a in
        go ()
    in
    go ()

  let pipe () =
    let mvar = Mvar.create () in
    let i = In.create (fun () -> Mvar.read mvar) in
    let o = Out.create (fun x -> Mvar.write mvar x) in
    (i, o)
end

module Pool = struct
  type mvar =
    | Done
    | Task of (unit -> unit t)

  type status =
    | Open
    | Closed

  type t =
    { mvar : mvar Mvar.t
    ; mutable status : status
    }

  let running t k =
    match t.status with
    | Open -> k true
    | Closed -> k false

  let create () = { mvar = Mvar.create (); status = Open }

  let task t ~f k =
    match t.status with
    | Closed ->
      Code_error.raise "pool is closed. new tasks may not be submitted" []
    | Open -> Mvar.write t.mvar (Task f) k

  let stream t =
    Stream.In.create (fun () ->
        let+ next = Mvar.read t.mvar in
        match next with
        | Done -> None
        | Task task -> Some task)

  let stop t k =
    match t.status with
    | Closed -> k ()
    | Open ->
      t.status <- Closed;
      Mvar.write t.mvar Done k

  let run t = stream t |> Stream.In.parallel_iter ~f:(fun task -> task ())
end

type fill = Fill : 'a Ivar.t * 'a -> fill

let run t ~iter =
  EC.new_run (fun () ->
      let result = ref None in
      EC.apply (fun () -> t) () (fun x -> result := Some x);
      let rec loop () =
        match !result with
        | Some res -> res
        | None ->
          let (Fill (ivar, v)) = iter () in
          (* We use [EC.apply] so that the current execution context is
             restored, ensuring that [iter] always run in the same execution
             context. *)
          EC.apply (fun () -> Ivar.fill ivar v) () ignore;
          loop ()
      in
      loop ())
OCaml

Innovation. Community. Security.