Did you know that you can navigate the posts by swiping left and right?

GHC-API Tour: How can we know which modules does a data type belongs to?

11 Apr 2015 . category: . Comments

I’ve been reading some documentation of the GHC-API because it would be what I would need in order to complete my project. I was thinking about my project and I felt into the following question: if we have a type, how can we know which modules does it belongs to?
In GHCI we have a very interesting ‘command’ which is

:info <the_function_or_type_you_want_information_about>


So I was thinking that the answer to this question was in the code of this function. I had to look in the GHC source code. And I finally could solve this question. This is the source code:


import Control.Applicative
import DynFlags
import GHC
import GHC.Paths
import GhcMonad ( liftIO )
import HsImpExp ( simpleImportDecl )

--(+++) = liftA2 (++)

preludeModuleName :: ModuleName
preludeModuleName = GHC.mkModuleName "Prelude"

implicitPreludeImport :: InteractiveImport
implicitPreludeImport = IIDecl (simpleImportDecl preludeModuleName)

main = defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
    runGhc (Just libdir) $ do
        dflags <- getSessionDynFlags
        setSessionDynFlags $ dflags { hscTarget = HscInterpreted
                                    , ghcLink   = LinkInMemory
                                    }
        setContext [implicitPreludeImport]

        let typesStr = ["Bool", "Integer", "String", "Char", "Double"]


        printNames typesStr
    where
      nameToStr name = moduleNameString $ moduleName $ nameModule name

      printNames [] = liftIO $ return ()
      printNames (t:ts) = do
        names' <- GHC.parseName t
        liftIO $ mapM_ (putStrLn . (++) (t ++ " -> ") . nameToStr) names'
        printNames ts




Me

Fabián Orccón is an awesome person. He lives in Perú, the land of the Incas.