JIT Compilation in OCaml

Is it possible in OCaml to compile some pieces of code during runtime? For example, I don’t wont to read configs or localizations from files or DB and I don’t want to read it from memory, I just want to translate some pieces where I use the configuration data to kind of literals so that L18n.l “main.headers.orders” would not find a corresponding language localization, but JITcompiles this piece of code just like a concrete value - “Orders” string for English.

You could have a PPX that, at compile time, transforms all strings that look like [%i18n.l "main.headers.orders"] into the corresponding string for the language you want, like "Order", though you couldn’t change the language after you’ve compiled that code.

If you wanted to do that at runtime… you could probably generate an mli file and an ml file for each language from your i18n file, use a PPX to translate [%i18n.l "main.headers.orders"] into something like I18n_gen.main_headers_orders and then use Dynlink to load the module with the correct translation at runtime, though that sounds like an awful lot of work for a very small performance gain. But knock yourself out if you want to try.

2 Likes