GHCApi.hs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module GHCApi where
  2. import Control.Applicative
  3. import Control.Exception
  4. import CoreMonad
  5. import DynFlags
  6. import ErrMsg
  7. import Exception
  8. import GHC
  9. import GHC.Paths (libdir)
  10. import System.Exit
  11. import System.IO
  12. import Types
  13. ----------------------------------------------------------------
  14. withGHC :: Alternative m => Ghc (m a) -> IO (m a)
  15. withGHC = withGHC' "Dummy"
  16. withGHC' :: Alternative m => FilePath -> Ghc (m a) -> IO (m a)
  17. withGHC' file body = ghandle ignore $ runGhc (Just libdir) $ do
  18. dflags <- getSessionDynFlags
  19. defaultCleanupHandler dflags body
  20. where
  21. ignore :: Alternative m => SomeException -> IO (m a)
  22. ignore e = do
  23. hPutStr stderr $ file ++ ":0:0:Error:"
  24. hPrint stderr e
  25. exitSuccess
  26. ----------------------------------------------------------------
  27. initSession0 :: Options -> Ghc [PackageId]
  28. initSession0 opt = getSessionDynFlags >>=
  29. (>>= setSessionDynFlags) . setGhcFlags opt
  30. initSession :: Options -> [String] -> [FilePath] -> Maybe [String] -> Bool -> Ghc LogReader
  31. initSession opt cmdOpts idirs mayPkgs logging = do
  32. dflags <- getSessionDynFlags
  33. let opts = map noLoc cmdOpts
  34. (dflags',_,_) <- parseDynamicFlags dflags opts
  35. (dflags'',readLog) <- liftIO . (>>= setLogger logging)
  36. . setGhcFlags opt . setFlags opt dflags' idirs $ mayPkgs
  37. _ <- setSessionDynFlags dflags''
  38. return readLog
  39. ----------------------------------------------------------------
  40. setFlags :: Options -> DynFlags -> [FilePath] -> Maybe [String] -> DynFlags
  41. setFlags opt d idirs mayPkgs
  42. | expandSplice opt = dopt_set d' Opt_D_dump_splices
  43. | otherwise = d'
  44. where
  45. d' = maySetExpose $ d {
  46. importPaths = idirs
  47. , ghcLink = LinkInMemory
  48. , hscTarget = HscInterpreted
  49. , flags = flags d
  50. }
  51. -- Do hide-all only when depend packages specified
  52. maySetExpose df = maybe df (\x -> (dopt_set df Opt_HideAllPackages) {
  53. packageFlags = map ExposePackage x ++ packageFlags df
  54. }) mayPkgs
  55. ghcPackage :: PackageFlag
  56. ghcPackage = ExposePackage "ghc"
  57. setGhcFlags :: Monad m => Options -> DynFlags -> m DynFlags
  58. setGhcFlags opt flagset =
  59. do (flagset',_,_) <- parseDynamicFlags flagset (map noLoc (ghcOpts opt))
  60. return flagset'
  61. ----------------------------------------------------------------
  62. setTargetFile :: (GhcMonad m) => String -> m ()
  63. setTargetFile file = do
  64. target <- guessTarget file Nothing
  65. setTargets [target]