Dereference a TH Name and analyze the value

In the template Haskell Q monad we can generate fresh Names and new declarations, but is it also possible to look up and analyze preexisting values? E.g. analyze the concrete syntax tree representation of a value whose Name we know.

I suspect the answer is “No” because the syntax tree is only available later as a Core Expr, but I was wondering how/whether others have thought about this and what workarounds are there.

3 Likes

You might be interested in parsley, which uses a GHC plugin and TH to analyse the syntax tree of a parser combinator style parser, and then compile it into an efficient state machine style parser.

You might also be interested in th-desugar, which allows turning the TH AST into something a bit closer to Core.

1 Like

thank you! Indeed, I am very interested in parsley but find its internal implementation to be way above my understanding.

1 Like

To look up information about a Name you can use the reify :: Name -> Q Info function.

If it is a variable then you get a VarI Name Type (Maybe Dec), where that Dec theoretically includes the right hand side of the definition of that variable.

Unfortunately, the documentation says that it will always be Nothing:

At present, this value is always Nothing: returning the RHS has not yet been implemented because of lack of interest.

However, even if it did sometimes give the right value, there are some pretty fundamental limitations. The compiler itself does not always know the definition of all variables. For example if the variable was imported from another module.

2 Likes

Yep, ‘reify’ is exactly what I need. Where do I register my vote of interest?

This is the GHC issue that tracks it: #14474: reify RHS of "value" variable · Issues · Glasgow Haskell Compiler / GHC · GitLab

2 Likes