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

1

15

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.

Rector answered 31/1, 2014 at 21:56 Comment(3)
Why doesn't the direct reify 'foo work out for you?Nonet
@NikitaVolkov foo just stands for an expression here, such as 1 + 2 + 3, it's not a name.Rector
Oh. Well, since reify is the only reification function of TH and since it only accepts names, I guess you're pretty much bound.Nonet
N
5

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.

Nakada answered 5/12, 2014 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.