Reputation: 23
Is there such facility in OCaml (e.g., akin to C++ and D)?
For example, when I define my function:
let my_func arg1 arg2 =
static_assert (arg1 < arg2);
(* rest of the function's body *)
and try to call it later like this:
my_func 4 1
I would get assert failure at compile-time?
If there is no such facility in OCaml, would it be possible to implement it with other existing facilities?
Upvotes: 2
Views: 376
Reputation: 35270
Static asserts come from the deficiency of the type systems of the languages you have specified. OCaml already checks everything that is possible to express with its type system. If something can be proofed at compile time as unsound, OCaml will say about this.
But, in OCaml you still can add some checks, that will not affect runtime, but will allow you to verify extra properties and invariants, that are not verified statically. Janestreet provides a pa_test
library that allows you to inline tests into your module and run them as a part of compilation procedure. Not truly static asserts, but still at compile time (at least from the observers perspective). Looks something like this:
TEST_MODULE = struct
let str = "hello\000,\000world\000!\000"
let pos_ref = ref 0
TEST = read_cstring str ~pos_ref = Ok "hello"
TEST = read_cstring str ~pos_ref = Ok ","
TEST = read_cstring str ~pos_ref = Ok "world"
TEST = read_cstring str ~pos_ref = Ok "!"
TEST = String.length str = pos_ref.contents
end
Upvotes: 1
Reputation: 6144
As of right now, there isn't.
The only static checking that is done by the OCaml compiler is the typing (which will allow you to get rid easily of a lot of mistakes you could do on sum types). Through constant propagation, your test can be statically transformed into an immediate exception raising so maybe it could be possible to patch the compiler to print a warning in that case (not an easy patch IMHO).
There are some tools to help you find errors in your code though, you can take a look at that post on the caml-list referencing the currently available helping tools for OCaml.
Upvotes: 1