Using GHC as a library

What would be the simplest example of sending a ghci expression via its api to evaluate and print the result? I cannot find a complete example that would work. Yes, I tried https://wiki.haskell.org/GHC/As_a_library , but I keep getting errors that don’t tell me much: no package state yet: call GHC.setSessionDynFlags . Wherever I try to setSessionDynFlags with any arguments or setContext , I always get an error. Currently I have (no setXYZ ):

 import GHC import GHC.Paths ( libdir ) import GhcMonad import Debugger import DynFlags import Outputable import Language.Haskell.HsColour import Language.Haskell.HsColour.Colourise colour :: String -> String colour = hscolour TTY defaultColourPrefs True True "" False ghci :: IO () ghci = runGhc (Just libdir) $ do r <- runStmt "[1, 2, 3]" RunToCompletion case r of RunOk ns -> do mapM_ ( \n -> do mty <- lookupName n case mty of Just (AnId id) -> do t <- obtainTermFromId maxBound True id fl <- getSessionDynFlags liftIO $ putStrLn $ colour $ show $ withPprStyleDoc fl defaultUserStyle $ ppr t return () otherwise -> return () ) ns otherwise -> return () main :: IO () main = ghci 
+7
api haskell ghci
source share
1 answer

So, my problem was solved when I added this initialization at the beginning of the GHC expression, which I run with runGhc (Just libdir) :

 df <- getSessionDynFlags setSessionDynFlags $ df { hscTarget = HscInterpreted , ghcLink = LinkInMemory } setContext $ map (IIDecl . simpleImportDecl . mkModuleName) [ "Prelude" ] 
+1
source share

All Articles