Ppxlib way to pass through string as an expression?

Following up on Is there any PPX for template strings in OCaml?


After struggling a lot I made the PPX myself: https://github.com/AriaFallah/ppx_str.

It’s basically template strings for OCaml so you can do

let name = "aria"
let name2 = "ppx_str"

let my_str = [%str "Hello there {name} I am {name2}"]
print_endline my_str

and get

Hello there aria I am ppx_str

Anyways, right now the biggest limitation of the ppx is that you can only put variable names into the string, which prevents you from doing something like:

let name = "aria"
let name2 = "ppx_str"

let my_str = [%str
  "Hello there {name} I am {name2} and I am {string_of_int 1} day old"
]

Right now the code for turning the strings into expressions is:

let start = 1 in
let len = String.length s in
Ast_builder.Default.evar ~loc (String.sub s start (len - 1 - start))

Ideally I would use something like Ast_builder.Default.eexpr if it existed, but as far as I know, it doesn’t. I’m not sure how to proceed at this point. I couldn’t find any real docs for Ppxlib except for one really short blog post. To be honest, I feel like I don’t understand half of my own code because I just based what I was doing off that one blog post + browsing the .mli files in the ppxlib repo.

If I understand your issue, you simply need to parse your string with Parse.expression .

1 Like

I needed to do Lexing.from_string first, but that seemed to do the trick!