Quasi-quotes allow generating AST code during compilations, but it inserts generated code at the place where Quasi-quote was written. Is it possible in any way to insert the compile-time generated code elsewhere? For example in specific module files which are different from the one where QQ was written? It would depend on hard-coded module structure, but that’s fine.
If that’s not possible with QQ but anyone knows a different way of achieving it, I am open for suggestions.
To answer this, it’s helpful to know what a quasi-quoter is. From the GHC Documentation, a quasi-quoter is a value of
That is, it’s a parser from an arbitrary String to one or more of
ExpQ,PatQ,TypeQ, andDecQ, which are Template Haskell representations of expressions, patterns, types, and declarations respectively.When you use a quasi-quote, GHC applies the parser to the String to create a
ExpQ(or other type), then splices in the resulting template haskell expression to produce an actual value.It sounds like what you’re asking to do is separate the quasiquote parsing and splicing, so that you have access to the TH expression. Then you can import that expression into another module and splice it there yourself.
Knowing the type of a quasi-quoter, it’s readily apparent this is possible. Normally you use a QQ as
Instead, you can extract the parser yourself, get a TH expression, and splice it later:
Of course if you’re writing all this yourself, you can skip the quasi-quotes and use a parser and Template Haskell directly. It’s pretty much the same thing either way.