Is it possible to generate and run TemplateHaskell generated code at runtime?
Using C, at runtime, I can:
- create the source code of a function,
- call out to gcc to compile it to a .so (linux) (or use llvm, etc.),
- load the .so and
- call the function.
Is a similar thing possible with Template Haskell?
From what I understand you want to create and run a code at runtime which I think you can do using GHC API but I am not very sure of the scope of what you can achieve. If you want something like hot code swapping you can look at the package hotswap.
Yes, it's possible. The GHC API will compile Template Haskell. A proof-of-concept is available at https://github.com/JohnLato/meta-th, which, although not very sophisticated, shows one general technique that even provides a modicum of type safety. Template Haskell expressions are build using the
Meta
type, which can then be compiled and loaded into a usable function.This function takes an
ExpQ
, and first runs it in IO to create a plainExp
. TheExp
is then pretty-printed into source code, which is compiled and loaded at run-time. In practice, I've found that one of the more difficult obstacles is specifying the correct imports in the generated TH code.