Extracting line / column number from https://github.com/janestreet/sexplib

The design of GitHub - janestreet/sexplib: Automated S-expression conversion uses types:

type sexp = Atom of string | List of sexp list

This is great so far. I’m writing code that processes this, and I get to an invalid sexp. (I.e. not all valid sexps are valid data formats for me.)

I now want to extract a line number / column number so I can throw an useful exception. How do I do that ?

README.md mentions:

In most cases users may therefore want to use functions like load_sexp_conv or load_sexp_conv_exn , which load s-expressions from files and convert them. They initially read the file without location annotations for performance reasons. Only if conversions fail will the file be reparsed with location annotations. Type errors can then be reported accurately with file name, line number, column, and file position.

But it is not obvious to me how to do that.


If you’re post-processing valid s-expressions, then you’re probably out-of-luck. It was never designed for your use-case.

I am post-processing valid s-exprs.

There’s Sexp_with_layout module which includes positions in sexps. Maybe that will do?

1 Like

This would work – one question. How do I do string → sexp_with_layout ?

let from_string s =
  let lexbuf = Lexing.from_string s in
  Sexplib.Sexp_with_layout.(Parser.sexp Lexer.main lexbuf)
1 Like

There’s also Sexplib.Sexp.Annotated which also has positions and parse functions… not sure what’s the difference from a shallow look over the docs.

1 Like