Do you know how OCaml now displays errors by quoting back part of the source, highlighting the faulty part? For instance, with a single-line error location:
File "foo.ml", line 1, characters 12-14: 1 | let foo x = yy + 1;; ^^
or a multi-line location:
File "bar.ml", lines 3-5, characters 10-10: 3 | ..........function 4 | | A -> 0 5 | | B -> 1
Do you have your own language/configuration file/… parser or typechecker, that could benefit from nice, user-friendly error messages?
The pp_loc library provides an easy-to-use implementation of the same source-quoting mechanism that is used in the OCaml compiler. It provides a single function
pp which will display the relevant part of the input given the location(s) of the error.
val pp : ?max_lines:int -> input:Input.t -> Format.formatter -> loc list -> unit
(As one can see from the signature,
pp also supports displaying several locations at once on the same source snippet, for multi-location errors.)
The full documentation is available online, and the library is available on opam (
opam install pp_loc).
This new version, thanks to the contribution of @c-cube, makes the
loc type more flexible. It should now be easy to create source locations that can be passed to
pp, however you represent them in your parser (be it as (line,column) pairs, offsets, or any combination of those…). For more details, see the Pp_loc.Position module.
I am completely open to more PRs or ideas for improving the library further, and displaying source locations in even nicer ways!
Happy error message printing!