HsExpr to Template Haskell
Note: perhaps the following is already possible with the current
ghc public API. If yes, please excuses me, point me to the relevant entry point and I'll volunteer to extend the documentation and provides examples to the community ;)
I'd like to convert the result of parsing Haskell with the
ghc library (e.g.
HsExpr) to template haskell (e.g.
A similar task is addressed by haskell-src-meta which converts Haskell AST generated by haskell-src-exts to template Haskell. However this couple of libraries does have a few limitations, including not being in sync with GHC or being an important dependency.
There is a lot of library in hackage which depends on
I've found a few example of library which may benefit from this feature:
- https://github.com/guibou/PyF/issues/9 (I'm the author of that one)
GHC does already have this functionality internally in template haskell quasi quotations. For example, you can get the template haskell
Expr from a fixed Haskell expression:
Prelude> :set -XTemplateHaskell Prelude> :set -XQuasiQuotes Prelude> import Language.Haskell.TH.Syntax Prelude Language.Haskell.TH.Syntax> run runIO runQ Prelude Language.Haskell.TH.Syntax> runQ [|1 + x|] InfixE (Just (LitE (IntegerL 1))) (VarE GHC.Num.+) (Just (UnboundVarE x))
I'd like to be able to do the same thing but with
1 + x being an arbitrary input. Something such as:
let arbitraryString = "1 + x" in runQArbitrary arbitraryString
Note that all of that may be implemented as an external library, for example we do have a work in progress here:
https://github.com/guibou/PyF/pull/51/files#diff-76e09c15fc15b8e30b846079a39c5ea7120c7aa5d42e52738ee83106d8e4b706 however this approach suffer from the same limitation as
- May not be in sync with GHC, so may not compile, or perfectly match GHC behavior
- Duplicate work with something that is already done in GHC.
- Adds another dependency to a project. This is less dramatic because the bloat was mostly from
haskell-src-exts, but still.