Is it possible to get a type of any expression using Template Haskell?

578 views Asked by At

Given an expression foo, I could declare a top-level function

bar = foo

and get the type of foo as Type by reifying bar:

case reify 'bar of
  VarI _ t _ _ -> t

Is there a direct way of getting the type of foo, without creating the redundant definition of bar? Ideally as function of type Exp -> Q Type.

1

There are 1 answers

0
Christian Conkle On

You're asking for a function of a type like Exp -> Q Info or Exp -> Q Type, yes? TH doesn't provide such a function. The only TH function that produces an Info is reify, and no other TH type seems to expose the type information you're after. It appears that the current TH API does not provide a way to reify arbitrary expressions.

I'm not an expert in GHC's internals, but poking around in compiler/typecheck/TcSplice.hs seems to confirm that reify works by looking up an already-compiled (and typechecked) entity and converting the compiler's existing knowledge of its type etc. into TH's Info type. That information wouldn't exist for an arbitrary Exp. I imagine we'd have to plumb the expression back through another compiler pass.