dflemstr
dflemstr

Reputation: 26147

How to get the literal value of a TemplateHaskell named variable

If I have a Name in TemplateHaskell and want to find out the value of the variable that it names, provided that the variable is declared as a literal, can this be done?

var = "foo"
-- Can `contentsOf` be defined?
$((contentsOf . mkName $ "var") >>= guard . (== "foo"))

Upvotes: 6

Views: 210

Answers (1)

hammar
hammar

Reputation: 139830

In theory, yes. In practice, no.

Finding out stuff about existing names is done using reify :: Name -> Q Info, and for a definition like that you would get back a VarI value, which includes a Maybe Dec field. This would seem to suggest that you might in some cases be able to get the syntax tree for the declaration of the variable, which would allow you to extract the literal, however current versions of GHC always returns Nothing in this field, so you're out of luck for a pure TH solution.

However, TH does allow arbitrary IO actions to be run, so you could potentially work around this by loading and parsing the module yourself using something like haskell-src-exts, however I suspect that would be more trouble than it's worth.

Upvotes: 4

Related Questions