Skip to content

Commit

Permalink
Support ;%lwt as sequence syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
hcarty committed Jan 20, 2018
1 parent 77c6522 commit 1977f63
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/ppx/ppx_lwt.ml
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ let gen_top_binds vbs =
[Vb.mk (Pat.tuple (vbs |> List.map (fun { pvb_pat; _ } -> pvb_pat)))
[%expr Lwt_main.run [%e gen_exp vbs 0]]]

let lwt_sequence mapper ~lhs ~rhs =
let lhs, rhs = mapper.expr mapper lhs, mapper.expr mapper rhs in
if !debug then
[%expr Lwt.backtrace_bind (fun exn -> try raise exn with exn -> exn)
[%e lhs] (fun () -> [%e rhs])]
else
[%expr Lwt.bind [%e lhs] (fun () -> [%e rhs])]

(** For expressions only *)
(* We only expand the first level after a %lwt.
After that, we call the mapper to expand sub-expressions. *)
Expand All @@ -141,6 +149,9 @@ let lwt_expression mapper exp attributes =
let pexp_attributes = attributes @ exp.pexp_attributes in
match exp.pexp_desc with

(* $e$;%lwt $e'$ ≡ [Lwt.bind $e$ (fun $p$ -> $e'$)] *)
| Pexp_sequence (lhs, rhs) ->
lwt_sequence mapper ~lhs ~rhs
(* [let%lwt $p$ = $e$ in $e'$] ≡ [Lwt.bind $e$ (fun $p$ -> $e'$)] *)
| Pexp_let (Nonrecursive, vbl , e) ->
let new_exp =
Expand Down
10 changes: 10 additions & 0 deletions src/ppx/ppx_lwt.mli
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,16 @@ $ ocamlfind ocamlc -package lwt.ppx \
{2 Sequence}
With OCaml 4.04.0 and on a convenient syntax is available for sequencing Lwt
operations using [;%lwt]. This allows free mixing of standard [;]
sequencing and [;%lwt] sequencing without extra parentheses:
{[
let i = ref 0 in
write stdout "Hello, ";%lwt
incr i;
write stdout "world!"
]}
It is also possible to sequence Lwt operations with the [>>] operator:
{[
write stdout "Hello, " >> write stdout "world!"
Expand Down
10 changes: 10 additions & 0 deletions test/ppx/main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ let suite = suite "ppx" [
(Lwt.return (!lst = [1;2]))
) ;

test "sequence with semicolon"
(fun () ->
let lst = ref [] in
lst := 2 :: !lst;
Lwt.return_unit;%lwt
lst := 1 :: !lst;
Lwt.return_unit;%lwt
Lwt.return (!lst = [1;2])
) ;

test "log"
(fun () ->
Lwt_log.ign_debug "bar";
Expand Down

0 comments on commit 1977f63

Please sign in to comment.