Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GHC as library

Tags:

haskell

api

ghci

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
like image 306
jakubdaniel Avatar asked Oct 03 '15 09:10

jakubdaniel


1 Answers

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" ]
like image 56
jakubdaniel Avatar answered Oct 05 '22 11:10

jakubdaniel