GHC as a library - getting output from GHCI

Mads Lindstrøm mads_lindstroem at yahoo.dk
Sun May 6 05:33:28 EDT 2007


Hi Pepe

Pepe Iborra wrote:
> Mads
> 
> On 04/05/2007, at 19:19, Mads Lindstrøm wrote:
> 
> > Hi Pepe
> > 
> > 
> > I would have liked something cross-platform.
> > 
> > 
> 
> 
> Take a look at the unix-compat[1] package by Bjorn Bringert, although
> it looks like it won't help you. Maybe it can be extended.
> 
> > Also, if stmt contains an error, wrapStmt will not be evaluated, and
> > the
> > 
> > resulting error is written to standard output or maybe to standard
> > 
> > error. Whichever way, I am back to the same problem.
> > 
> 
> 
> 
> 
> What else should be the behaviour in the case stmt contains an error?

It could behave like most other IO actions which produce values - return
them to the caller. For instance readFile :: FilePath -> IO String .
runStmt could have the following type:

runStmt :: Session -> String -> IO (RunResult, String)

where the returned String would contain either the error or the result
from evaluating the statement.

> You can capture errors and stop them being written out very easily. 
> Take a look at this snippet (not mine, it's beschmi's code) from
> Shim[2]:
> 

Yes, that works for me.


Greetings,

Mads

> 
> \begin{code}
> load' :: FilePath -> Maybe String -> SHM
> (SuccessFlag,[CompileNote],Session)
> load' sourcefile source = do
>   source' <- addTime source
>   ses <- getSessionFor sourcefile
>   dflags0 <- io $ GHC.getSessionDynFlags ses
>   ref <- io $ MVar.newMVar []
>   let dflags1 = dflags0{ log_action = logMsg ref }
>   io $ GHC.setSessionDynFlags ses dflags1
>   io $ GHC.setTargets ses [Target (TargetFile sourcefile Nothing)
> source']
>   loadResult <- io $ GHC.load ses LoadAllTargets
>   cnotes <- io $ reverse `liftM` MVar.readMVar ref
>   case loadResult of
>        Succeeded -> do -- GHC takes care of setting the right context
>          modq <- io $ findModuleInFile ses sourcefile
>          io $ GHC.setContext ses [modq] []
>          return (Succeeded,cnotes,ses)
>        Failed    -> do   -- We take care of getting at least the
> Prelude
>          io(GHC.setContext ses [] =<< atomM (getPrelude ses))
>          return (Failed,cnotes,ses)
>   where atomM = liftM (:[])
>         logMsg ref severity' srcSpan' style' msg' = do
>           dir <- getCurrentDirectory
>           logS ('\n':show ((mkLocMessage srcSpan' msg') style'))
>           MVar.modifyMVar_ ref
>             (\l -> return $ (CompileNote severity' srcSpan'
>                                          style' msg' dir):l)
> \end{code}
> 
> 
> Here, DynFlags.logAction is being filled with a handler that writes to
> a MVar instead of the default handler that writes to stdout.
> 
> 
> pepe
> 
> 
> [1] - http://hackage.haskell.org/cgi-bin/hackage
> -scripts/package/unix-compat-0.1
> [2] - http://shim.haskellco.de/shim/Shim/Hsinfo.hs



More information about the Glasgow-haskell-users mailing list