What would be the simplest example of sending an expression to ghci via its api for evaluation and printing the result? I am not able to find a complete example that would work. Yes, I have tried https://wiki.haskell.org/GHC/As_a_library but I keep getting errors that do not tell me much: no package state yet: call GHC.setSessionDynFlags
. Wherever I try setSessionDynFlags
with whatever arguments, or setContext
, I always end up with an error. I currently 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
So my problem was solved when I added this initialization at the beginning of the GHC
expression that I run with runGhc (Just libdir)
:
df <- getSessionDynFlags
setSessionDynFlags $ df { hscTarget = HscInterpreted
, ghcLink = LinkInMemory
}
setContext $ map (IIDecl . simpleImportDecl . mkModuleName) [ "Prelude" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With