| 1 | open Core |
| 2 | open Ppxlib |
| 3 | |
| 4 | let all_localities = [ `global; `local ] |
| 5 | let loc = Location.none |
| 6 | let print_expr expr = Pprintast.string_of_expression expr |> print_string |
| 7 | |
| 8 | let expand extension kind ~modul expr = |
| 9 | List.iteri all_localities ~f:(fun i locality -> |
| 10 | if i > 0 then printf "----\n"; |
| 11 | printf !"locality = %{sexp:[`local|`global]}:\n" locality; |
| 12 | Ppx_let_expander.expand extension kind ~modul ~locality expr |> print_expr; |
| 13 | printf "\n") |
| 14 | ;; |
| 15 | |
| 16 | let%expect_test "while%bind expansion" = |
| 17 | expand |
| 18 | Ppx_let_expander.bind |
| 19 | Ppx_let_expander.Extension_kind.default |
| 20 | ~modul:None |
| 21 | [%expr |
| 22 | while MY_CONDITION do |
| 23 | MY_BODY |
| 24 | done]; |
| 25 | [%expect |
| 26 | {| |
| 27 | locality = global: |
| 28 | let rec __let_syntax_loop__001_ () = |
| 29 | Let_syntax.bind MY_CONDITION |
| 30 | ~f:(function |
| 31 | | true -> Let_syntax.bind MY_BODY ~f:__let_syntax_loop__001_ |
| 32 | | false -> Let_syntax.return ())[@@ppxlib.do_not_enter_value ] in |
| 33 | __let_syntax_loop__001_ () |
| 34 | ---- |
| 35 | locality = local: |
| 36 | let rec __let_syntax_loop__002_ () = |
| 37 | local_ let __nontail__005_ = |
| 38 | Let_syntax.bind MY_CONDITION |
| 39 | ~f:(fun __let_syntax__003_ -> |
| 40 | local_ let __nontail__004_ = |
| 41 | match __let_syntax__003_ with |
| 42 | | true -> |
| 43 | Let_syntax.bind MY_BODY |
| 44 | ~f:__let_syntax_loop__002_ |
| 45 | | false -> Let_syntax.return () in |
| 46 | __nontail__004_) in |
| 47 | __nontail__005_[@@ppxlib.do_not_enter_value ] in |
| 48 | __let_syntax_loop__002_ () |
| 49 | |}] |
| 50 | ;; |
| 51 | |
| 52 | let%expect_test "while%bind trivial test" = |
| 53 | let i = ref 0 in |
| 54 | while%bind.Monad.Ident |
| 55 | incr i; |
| 56 | !i <= 5 |
| 57 | do |
| 58 | printf "%d\n" !i |
| 59 | done; |
| 60 | [%expect {| |
| 61 | 1 |
| 62 | 2 |
| 63 | 3 |
| 64 | 4 |
| 65 | 5 |
| 66 | |}] |
| 67 | ;; |
| 68 | |
| 69 | let%expect_test "monadic use" = |
| 70 | let open Or_error.Let_syntax in |
| 71 | let next i = if i < 5 then Ok (i + 1) else error_s [%message "too big"] in |
| 72 | let t n = |
| 73 | let i = ref 0 in |
| 74 | let result = |
| 75 | while%bind |
| 76 | let%map i' = next !i in |
| 77 | i := i'; |
| 78 | !i <= n |
| 79 | do |
| 80 | printf "%d\n" !i; |
| 81 | Ok () |
| 82 | done |
| 83 | in |
| 84 | print_s [%sexp (result : unit Or_error.t)] |
| 85 | in |
| 86 | t 3; |
| 87 | [%expect {| |
| 88 | 1 |
| 89 | 2 |
| 90 | 3 |
| 91 | (Ok ()) |
| 92 | |}]; |
| 93 | t 10; |
| 94 | [%expect {| |
| 95 | 1 |
| 96 | 2 |
| 97 | 3 |
| 98 | 4 |
| 99 | 5 |
| 100 | (Error "too big") |
| 101 | |}] |
| 102 | ;; |