ocaml/ocaml — pull request #126 by def-lkb (2014-12-13 16:59:45+00:00)
Title: Automatically insert source location

This patch adds an abstract type "source_location".
It receives a special treatment by the type checker: when an optional argument of this type gets erased, it is replaced by the location of the application.

```ocaml
# let current_loc ?loc () = match loc with None -> ("unknown",0,0) | Some loc -> source_location loc;;
val current_loc : ?loc:source_location -> unit -> string * int * int =
# current_loc ();;
- : string * int * int = ("//toplevel//", 1, 0)
```

As this needs semantic information, it is implemented as a special-case in the type-checker, a PPX couldn't do it.
The use of optional arguments is handy to integrate with existing code and to manage expansion time:

- in a monad, you can replace `(>>=) : 'a t -> ('a -> 'b t) -> 'b t` with `(>>=) : ?loc:source_location -> 'a t -> ('a -> 'b t) -> 'b t` to automatically track binding locations (and then implement a tracing facility)
- when writing helpers, one might want to delay expansion: `let helper1 ?loc v = core_function ?loc (f v)`

I think such primitive could help a lot in providing better debugging / logging. I am interested in hearing other people opinions on the subject.