I'm trying to make a program that typechecks haskell files for me using the GHC API. I've gotten the type checking to work for local files, but I have a specific cabal package that I need to be have available as well (the same package this executable will be a part of). How do add this import dependency?
I also tried compiling with ghc command line to figure this out, using ghc -package PKG-VER --make Test.hs -v
but it only seems to look in the local directory for imports.
My current code looks like this:
import Control.Exception
import Control.Monad
import Control.Monad.State
import DynFlags
import Exception
import GHC
import GHC.Paths (libdir)
typecheck :: MonadIO m => [FilePath] -> FilePath -> m ()
typecheck otherincludes fp =
liftIO . defaultErrorHandler defaultLogAction . runGhc (Just libdir) $ do
dynflags <- getSessionDynFlags
void $ setSessionDynFlags dynflags { includePaths = otherIncludes ++ includePaths dynflags }
target <- guessTarget fp Nothing
setTargets [target]
void $ load LoadAllTargets
deps <- depanal [] False
forM_ deps $ \ms -> parseModule ms >>= typecheckModule
I managed to make your code read and typecheck itself as followS:
here is how it runs in ghci:
So the trick seems to be to pass the exposed packages in the
dynflags
argument tosetSessionDynFlags
. See the DynFlags module for some documentation.