Code execution in compile time

I’ve not used PPX yet, but the examples of its use looks ugly to me (sorry, but that’s mine opinion as unexperienced developer in OCaml). Few years ago I came to the idea of let’s call it staged execution, when we have at least two stages: one for compile time and one for runtime and later I found something similar already implemented in Zig and few other languages. I’m curious if it is possible to perform something similar in OCaml by keeping application code to look like normal OCaml code? What the drawbacks of such an approach? Or maybe you just can explain me why I’m wrong and PPX is a great tool.

You will be interested by MetaOCaml BER MetaOCaml. See also MetaOCaml GitHub Community · GitHub.

Cheers,
Nicolas

1 Like

Thank you for your response! It looks like the project is dead, because the last version of OCaml, that MetaOCaml supports is 4.11 and the last commit was 2 years ago.

My understanding is that the project is very much alive, it is just that syncing with the latest version of OCaml is not a priority. @yallop will know more.

Cheers,
Nicolas

I like metaquot (ppx!) as an alternative for staged execution. It is a bit lower-level, but if you:

  1. Generate OCaml AST expressions with metaquot and metapp
  2. Make a Dune (executable (name gen) (modules ...) (preprocess (pps metaquot.ppx))) and a (rule (target stage1.ml) (actions (run gen %{target}))) that will print the OCaml AST into stage1.ml

then you can use Stage1 as a module in your other code (etc).

The metapp page describes its differences from ppx_stage (which I don’t know about).

1 Like

As was posted recently in the OCaml compiler “newsletter” (OCaml compiler development newsletter, issue 6: March 2022 to September 2022), it seems that work on native macros is starting up again (roughly equivalent to TH or MetaOCaml, but module-aware), per @yallop https://www.cl.cam.ac.uk/~jdy22/projects/modular-macros/

Obviously not anything ready for prime time yet, but it’s great to see progress being made in this area.

2 Likes