Guest User

Untitled

a guest
Jan 23rd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. {-# LANGUAGE ScopedTypeVariables #-}
  2. module DynLoad (
  3. loadSourceGhc,
  4. execFnGhc
  5. ) where
  6.  
  7. import Control.Exception (throw)
  8. import GHC hiding (loadModule)
  9. import GHC.Paths (libdir)
  10. import HscTypes (SourceError, srcErrorMessages)
  11. import DynFlags
  12. import Unsafe.Coerce
  13. import Bag (bagToList)
  14.  
  15. execFnGhc :: String -> String -> Ghc a
  16. execFnGhc modname fn = do
  17. mod <- findModule (mkModuleName modname) Nothing
  18. setContext [] [mod]
  19. value <- compileExpr (modname ++ "." ++ fn)
  20.  
  21. let value' = (unsafeCoerce value) :: a
  22. return value'
  23.  
  24. loadSourceGhc :: String -> Ghc (Maybe String)
  25. loadSourceGhc path = let
  26. throwingLogger (Just e) = throw e
  27. throwingLogger _ = return ()
  28. in do
  29. dflags <- getSessionDynFlags
  30. setSessionDynFlags (dflags{
  31. ghcLink = LinkInMemory,
  32. hscTarget = HscInterpreted,
  33. packageFlags = [ExposePackage "ghc"]
  34. })
  35. target <- guessTarget path Nothing
  36. addTarget target
  37. r <- loadWithLogger throwingLogger LoadAllTargets
  38. case r of
  39. Failed -> return $ Just "Generic module load error"
  40. Succeeded -> return Nothing
  41.  
  42. `gcatch` \(e :: SourceError) -> let
  43. errors e = concat $ map show (bagToList $ srcErrorMessages e)
  44. in
  45. return $ Just (errors e)
Add Comment
Please, Sign In to add comment