Search code examples
haskelltemplate-haskell

Is it possible to use template haskell to get the name of the current file?


The closest I can see is using reifyModule and thisModule, but that doesn't work.

{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH
import Language.Haskell.TH.Syntax

main = putStrLn $(LitE . StringL . show <$> thisModule)

(unsurprisingly) gives back Module (PkgName "main") (ModName "Main") regardless of the file name.


Solution

  • You can get it using location.

    {-# LANGUAGE TemplateHaskell #-}
    import Language.Haskell.TH
    import Language.Haskell.TH.Syntax
    
    main = putStrLn $(LitE . StringL . loc_filename <$> location)