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" ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.