Say I have a String
(or Text
or whatever) containing valid Haskell code. Is there a way to convert it into a [Dec]
with Template Haskell?
I'm pretty sure the AST doesn't directly go to GHC so there's going to be a printing and then a parsing stage anyways.
This would be great to have since it would allow different "backends" for TH. For example you could use the AST from haskell-src-exts
which supports more Haskell syntax than TH does.
Why would you think that? That isn’t the case, the TH AST is converted to GHC’s internal AST directly; it never gets converted back to text at any point in that process. (If it did, that would be pretty strange.)
Still, it would be somewhat nice if Template Haskell exposed a way to parse Haskell source to expressions, types, and declarations, basically exposing the parsers behind various
e
,t
, andd
quoters that are built in to Template Haskell. Unfortunately, it does not, and I don’t believe there are currently any plans to change that.Currently, you need to go through
haskell-src-exts
instead. This is somewhat less than ideal, since there are differences betweenhaskell-src-exts
’s parser and GHCs, but it’s as good as you’re currently going to get. To lessen the pain, there is a package calledhaskell-src-meta
that bridgeshaskell-src-exts
andtemplate-haskell
.For your use case, you can use the
parseDecs
function fromLanguage.Haskell.Meta.Parse
, which has the typeString -> Either String [Dec]
, which is what you’re looking for.