Atlinx
Atlinx

Reputation: 594

How to print file location of calling function in OCaml?

I'm trying to make a custom assert function with greater functionality, except the problem is the assert exception points to inside the custom assert function, which isn't useful for the end user when they're trying to figure out which assertion failed.

Here's what I have so far:

  let assert_eq (exp: 'a) (exp2: 'a) = 
    assert (exp = exp2)

Upvotes: 2

Views: 149

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

OCaml doesn't have an interface for a function to determine details of its call site. The reason it's possible for the built-in assert mechanism is just that: it's a built-in mechanism, not an ordinary function call.

There is a way to determine the current function, filename, line number, and module. In the documentation for Stdlib (in a section named Debugging) you'll find __FUNCTION_, __FILE__, __LINE__, and __MODULE__. There are a few more similar names that capture various combinations. The documentation for Stdlib is here: https://v2.ocaml.org/releases/4.14/api/Stdlib.html

To create an assert function that can access these values from the call site I'm pretty sure you'll need to create a syntax extension that passes them along. The currently favored mechanism for doing this is PPX. The best general description I could find of PPX is here: https://ocaml-ppx.github.io/ppxlib/ppxlib/manual.html#what-is-ppx

In sum, I'd say this is a project that requires advanced features of OCaml.

Upvotes: 6

Related Questions