7

Currently I'm trying to do a translation from a Haskell subset without having to deal with all the parsing, typechecking etc. issues. Documentation didn't help me to figure out a function to get the function's body (all the definitions) by its name.

Context for this call should look something like

fac 0 = 1
fac x = z * fac (x - 1)

getBody = ...

main = do
    x <- runQ $ getBody [| fac |]
    print x

Does anyone knows

  1. whether there are some good and up to date docs on TH (not the reference on Hackage) or
  2. how to make getBody?
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
polkovnikov.ph
  • 6,256
  • 6
  • 44
  • 79
  • 1
    What are you trying to do with `runQ` here? Pretty sure there's no way you're going to get the information you want trying to use TH at run-time. – C. A. McCann Dec 21 '12 at 02:31

1 Answers1

10

In general, the way to find the definition of something with TH is using the reify function. However:

Looks like you'll need to find another route. Have you considered using the haskell-src-exts package for parsing and/or the GHC API or something based on it?

C. A. McCann
  • 76,893
  • 19
  • 209
  • 302
  • Yes, we can't use reify at run-time, but we can use data it returns. It looks like this (mention this code needs to be split into 2 modules due to GHC stage restriction; also runs in GHCi): `conv1 (TyConI x) = [| TyConI $(conv2 x) |]` `conv2 (DataD _ name _ _ _) = [| DataD [] (mkName $(return $ LitE $ stringL $ show name)) [] [] [] |]` `main = print $(reify ''Int >>= conv1)` Also, `reify` would return AST for the _call_ of the function, but not it's body, anyway. There should be reifyDecl function, which is really absent. I feel really grateful for your help. Thank you. – polkovnikov.ph Dec 21 '12 at 16:47
  • @polkovnikov.ph: Using `reify` on the name of something generally does give you the declaration, when that makes sense--for a type it will give you the list of constructors, the `deriving` list, and so on. `reify`ing a function's name gives you a `VarI` for the info, which has a `Maybe Dec` value, i.e. a declaration. If I'm understanding what you want, `reify` would do it, it's just not implemented right now because apparently few other people want it. – C. A. McCann Dec 21 '12 at 17:03
  • To anyone who might read this: I'd be interested in working on this feature in the near future. I could really use it. – jtobin Dec 05 '13 at 04:05
  • 1
    @jtobin: See https://ghc.haskell.org/trac/ghc/ticket/1831 on the GHC Trac if you haven't already, I think that's talking about the same thing. – C. A. McCann Dec 05 '13 at 15:02
  • @jtobin Nice to hear that. I've sent you an email. – polkovnikov.ph Dec 06 '13 at 05:50