Created
February 17, 2020 22:20
-
-
Save j14159/54719811d2cfa12258e14d9f0a43e304 to your computer and use it in GitHub Desktop.
Working out `assert_match` that I've been missing from Erlang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Ppxlib | |
exception No_match | |
let assert_match_ext = | |
Extension.declare | |
"ppx_assert_match.assert_match" | |
Extension.Context.Expression | |
Ast_pattern.(ppat __ __) | |
(fun ~loc ~path:_ patt guard -> | |
let open Ast_builder.Default in | |
let main_case = case ~lhs:patt ~guard ~rhs:(eunit ~loc) in | |
let fail_case = case | |
~lhs:(ppat_any ~loc) | |
~guard:(None) | |
~rhs:([%expr failwith "No match."]) | |
in | |
pexp_function ~loc [ main_case; fail_case ] | |
) | |
let _ = | |
Driver.register_transformation ~extensions:[assert_match_ext] "ppx_assert_match" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open OUnit2 | |
let test_exact _ = | |
[%assert_match? ("hello", 2)] ("hello", 2) | |
type test_rec = { x : int; y : float } | |
let test_records _ = | |
let rec_a = { x = 1; y = 2.5 } in | |
[%assert_match? { x = 1; _ }] rec_a; | |
[%assert_match? { x = 1; y } when y > 2.1] rec_a | |
let suite = "Simple early tests" >::: [ "Exact match" >:: test_exact | |
; "Record matches" >:: test_records | |
] | |
let _ = run_test_tt_main suite |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment