Ocamlformat together with cppo?

Hi everyone.

I have a project with some boilerplate-y implementation code that I would like to extract out, and cppo’s #define macros are perfect for what I would like to do.

However, ocamlformat (which I invoke in the terminal with dune fmt) doesn’t seem to work with files that use foreign cppo syntax (it reports invalid syntax which makes sense since it’s trying to format the file before processing).

I was wondering if anyone had any solutions? [This Stack Overflow answer)[ocaml - use ocamlformat with cppo and dune - Stack Overflow] asks about the same question as well, but I’m a bit lost with the answer because I’m not familiar with OCaml beyond writing code in the language (so the inticracies involving Dune and Makefiles is lost on me).

Would appreciate any help. If my question doesn’t have an answer, that’s okay and I’ll just have ocamlformat ignore the preprocessed files. Thanks in advance.

(I’m open to other ideas of reducing boilerplate instead of using cppo too.)

Hello! ocamlformat requires code that parses without any preprocessing.

If you can post a short illustrative example of the kind of boilerplate you would like to eliminate, there may be alternatives within the language and/or ppx extensions that people can suggest.

1 Like

Hi there! Thanks for the answer! Appreciate it.

The boilerplate I wanted to clean up was a long if-else ladder (not nested) checking different variables (so pattern matching wouldn’t be much help), except that the last else case returns something different in two instances.

I think I’m able to extract the ladder out to a new separate function, and pass the result intended for the last else case to the function as well, which will help so that’s sorted.

You may be able to get something by using some let* sugar:

let ( let* ) v f = ...

let () =
  let* x1 = e1 in
  let* x2 = e2 in
1 Like