1

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.

Luka Horvat
  • 4,283
  • 3
  • 30
  • 48

1 Answers1

6

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.

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, and d 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 between haskell-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 called haskell-src-meta that bridges haskell-src-exts and template-haskell.

For your use case, you can use the parseDecs function from Language.Haskell.Meta.Parse, which has the type String -> Either String [Dec], which is what you’re looking for.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • Hmm, this is almost good enough but it still doesn't help with stuff like TH inexplicably not supporting visible type applications while `haskell-src-exts` does. Not to mention comments/docs. – Luka Horvat Jan 03 '17 at 11:48
  • Regarding [why Template Haskell doesn't expose a parser for the quoters](http://stackoverflow.com/a/40985623/3072788). – Alec Jan 03 '17 at 16:34
  • @Alec So presumably [the proposal for native metaprogramming](https://ghc.haskell.org/trac/ghc/wiki/NativeMetaprogramming) would make that a lot easier? – Alexis King Jan 03 '17 at 17:17
  • @AlexisKing I think that proposal is largely _motivated_ by this very problem, so yes: it would make this a lot easier. Thanks for the link! – Alec Jan 03 '17 at 17:26