Search code examples
metaprogrammingocamlsyntactic-sugarocamlyacc

Embedding a domain specific language in an OCaml toplevel -- to Camlp4 or not?


I have some code that includes a menhir-based parser for a domain specific language (a logic). For the sake of my sanity while debugging, it would be great to be able to type instances of this language (formulas) directly in the toplevel like so:

# f = << P(x,y) & x!=y >>

Is campl4/5 my only option? If yes, I find the documentation rather intimidating. Is there an example/tutorial that is close-enough to my use case and that I could conceivably adapt? (For instance, syntax extensions that introduce new keywords do not seem relevant). Thanks!


Solution

  • If you're willing to call a function to do the parsing, you can use ocamlmktop to include your parser into the top level. Then you can install printers for your types using #install_printer. The sessions might look like this then:

    # let x = parse ()
    << type your expression here >>
    # x : type = <<formatted version>>
    

    I have used specialed printers, and they definitely help a lot with complicated types. I've never gotten around to using ocamlmktop. I always just load in my code with #load and #use.

    This is a lot easier than mastering camlp4/5 (IMHO). But maybe it's a bit too crude.