1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4 -----------------------------------------------------------------------------
6 -- Monadery code used in InteractiveUI
8 -- (c) The GHC Team 2005-2006
10 -----------------------------------------------------------------------------
12 module GhciMonad where
14 #include "HsVersions.h"
17 import Outputable hiding (printForUser, printForUserPartWay)
18 import qualified Outputable
19 import Panic hiding (showException)
28 import MonadUtils ( MonadIO, liftIO )
35 import Data.Int ( Int64 )
39 import System.Environment
41 import Control.Monad as Monad
44 -----------------------------------------------------------------------------
47 type Command = (String, String -> GHCi Bool, Maybe String, String -> IO [String])
49 data GHCiState = GHCiState
56 options :: [GHCiOption],
57 prelude :: GHC.Module,
59 breaks :: ![(Int, BreakLocation)],
60 tickarrays :: ModuleEnv TickArray,
61 -- tickarrays caches the TickArray for loaded modules,
62 -- so that we don't rebuild it each time the user sets
64 -- ":" at the GHCi prompt repeats the last command, so we
66 last_command :: Maybe Command,
68 remembered_ctx :: [(CtxtCmd, [String], [String])],
69 -- we remember the :module commands between :loads, so that
70 -- on a :reload we can replay them. See bugs #2049,
71 -- \#1873, #1360. Previously we tried to remember modules that
72 -- were supposed to be in the context but currently had errors,
73 -- but this was complicated. Just replaying the :module commands
74 -- seems to be the right thing.
75 ghc_e :: Bool -- True if this is 'ghc -e' (or runghc)
83 type TickArray = Array Int [(BreakIndex,SrcSpan)]
86 = ShowTiming -- show time/allocs after evaluation
87 | ShowType -- show the type of expressions
88 | RevertCAFs -- revert CAFs after every evaluation
93 { breakModule :: !GHC.Module
94 , breakLoc :: !SrcSpan
95 , breakTick :: {-# UNPACK #-} !Int
96 , onBreakCmd :: String
99 instance Eq BreakLocation where
100 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
101 breakTick loc1 == breakTick loc2
103 prettyLocations :: [(Int, BreakLocation)] -> SDoc
104 prettyLocations [] = text "No active breakpoints."
105 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
107 instance Outputable BreakLocation where
108 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
109 if null (onBreakCmd loc)
111 else doubleQuotes (text (onBreakCmd loc))
113 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
114 recordBreak brkLoc = do
116 let oldActiveBreaks = breaks st
117 -- don't store the same break point twice
118 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
119 (nm:_) -> return (True, nm)
121 let oldCounter = break_ctr st
122 newCounter = oldCounter + 1
123 setGHCiState $ st { break_ctr = newCounter,
124 breaks = (oldCounter, brkLoc) : oldActiveBreaks
126 return (False, oldCounter)
128 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> Ghc a }
130 reflectGHCi :: (Session, IORef GHCiState) -> GHCi a -> IO a
131 reflectGHCi (s, gs) m = unGhc (unGHCi m gs) s
133 reifyGHCi :: ((Session, IORef GHCiState) -> IO a) -> GHCi a
134 reifyGHCi f = GHCi f'
136 -- f' :: IORef GHCiState -> Ghc a
137 f' gs = reifyGhc (f'' gs)
138 -- f'' :: IORef GHCiState -> Session -> IO a
141 startGHCi :: GHCi a -> GHCiState -> Ghc a
142 startGHCi g state = do ref <- liftIO $ newIORef state; unGHCi g ref
144 instance Monad GHCi where
145 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
146 return a = GHCi $ \_ -> return a
148 instance Functor GHCi where
149 fmap f m = m >>= return . f
151 ghciHandleGhcException :: (GhcException -> GHCi a) -> GHCi a -> GHCi a
152 ghciHandleGhcException = handleGhcException
154 getGHCiState :: GHCi GHCiState
155 getGHCiState = GHCi $ \r -> liftIO $ readIORef r
156 setGHCiState :: GHCiState -> GHCi ()
157 setGHCiState s = GHCi $ \r -> liftIO $ writeIORef r s
159 liftGhc :: Ghc a -> GHCi a
160 liftGhc m = GHCi $ \_ -> m
162 instance MonadIO GHCi where
163 liftIO m = liftGhc $ liftIO m
165 instance GhcMonad GHCi where
166 setSession s' = liftGhc $ setSession s'
167 getSession = liftGhc $ getSession
169 instance ExceptionMonad GHCi where
170 gcatch m h = GHCi $ \r -> unGHCi m r `gcatch` (\e -> unGHCi (h e) r)
171 gblock (GHCi m) = GHCi $ \r -> gblock (m r)
172 gunblock (GHCi m) = GHCi $ \r -> gunblock (m r)
174 instance WarnLogMonad GHCi where
175 setWarnings warns = liftGhc $ setWarnings warns
176 getWarnings = liftGhc $ getWarnings
178 -- for convenience...
179 getPrelude :: GHCi Module
180 getPrelude = getGHCiState >>= return . prelude
182 GLOBAL_VAR(saved_sess, no_saved_sess, Session)
184 no_saved_sess :: Session
185 no_saved_sess = error "no saved_ses"
187 saveSession :: GHCi ()
191 writeIORef saved_sess s
193 splatSavedSession :: GHCi ()
194 splatSavedSession = io (writeIORef saved_sess no_saved_sess)
196 -- restoreSession :: IO Session
197 -- restoreSession = readIORef saved_sess
199 withRestoredSession :: Ghc a -> IO a
200 withRestoredSession ghc = do
201 s <- readIORef saved_sess
204 getDynFlags :: GHCi DynFlags
206 GHC.getSessionDynFlags
208 setDynFlags :: DynFlags -> GHCi [PackageId]
209 setDynFlags dflags = do
210 GHC.setSessionDynFlags dflags
212 isOptionSet :: GHCiOption -> GHCi Bool
214 = do st <- getGHCiState
215 return (opt `elem` options st)
217 setOption :: GHCiOption -> GHCi ()
219 = do st <- getGHCiState
220 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
222 unsetOption :: GHCiOption -> GHCi ()
224 = do st <- getGHCiState
225 setGHCiState (st{ options = filter (/= opt) (options st) })
230 printForUser :: SDoc -> GHCi ()
231 printForUser doc = do
232 unqual <- GHC.getPrintUnqual
233 io $ Outputable.printForUser stdout unqual doc
235 printForUserPartWay :: SDoc -> GHCi ()
236 printForUserPartWay doc = do
237 unqual <- GHC.getPrintUnqual
238 io $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
240 runStmt :: String -> GHC.SingleStep -> GHCi GHC.RunResult
241 runStmt expr step = do
244 withProgName (progname st) $
247 GHC.handleSourceError (\e -> do GHC.printExceptionAndWarnings e
248 return GHC.RunFailed) $ do
249 GHC.runStmt expr step
251 resume :: GHC.SingleStep -> GHCi GHC.RunResult
252 resume step = GHC.resume step
254 -- --------------------------------------------------------------------------
255 -- timing & statistics
257 timeIt :: GHCi a -> GHCi a
259 = do b <- isOptionSet ShowTiming
262 else do allocs1 <- io $ getAllocations
263 time1 <- io $ getCPUTime
265 allocs2 <- io $ getAllocations
266 time2 <- io $ getCPUTime
267 io $ printTimes (fromIntegral (allocs2 - allocs1))
271 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
272 -- defined in ghc/rts/Stats.c
274 printTimes :: Integer -> Integer -> IO ()
275 printTimes allocs psecs
276 = do let secs = (fromIntegral psecs / (10^(12::Integer))) :: Float
277 secs_str = showFFloat (Just 2) secs
279 parens (text (secs_str "") <+> text "secs" <> comma <+>
280 text (show allocs) <+> text "bytes")))
282 -----------------------------------------------------------------------------
285 revertCAFs :: GHCi ()
289 when (not (ghc_e s)) $ io turnOffBuffering
290 -- Have to turn off buffering again, because we just
291 -- reverted stdout, stderr & stdin to their defaults.
293 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
294 -- Make it "safe", just in case
296 -----------------------------------------------------------------------------
297 -- To flush buffers for the *interpreted* computation we need
298 -- to refer to *its* stdout/stderr handles
300 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
301 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
302 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
304 -- After various attempts, I believe this is the least bad way to do
305 -- what we want. We know look up the address of the static stdin,
306 -- stdout, and stderr closures in the loaded base package, and each
307 -- time we need to refer to them we cast the pointer to a Handle.
308 -- This avoids any problems with the CAF having been reverted, because
309 -- we'll always get the current value.
311 -- The previous attempt that didn't work was to compile an expression
312 -- like "hSetBuffering stdout NoBuffering" into an expression of type
313 -- IO () and run this expression each time we needed it, but the
314 -- problem is that evaluating the expression might cache the contents
315 -- of the Handle rather than referring to it from its static address
316 -- each time. There's no safe workaround for this.
318 initInterpBuffering :: Ghc ()
319 initInterpBuffering = do -- make sure these are linked
320 dflags <- GHC.getSessionDynFlags
324 -- ToDo: we should really look up these names properly, but
325 -- it's a fiddle and not all the bits are exposed via the GHC
327 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdin_closure"
328 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdout_closure"
329 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stderr_closure"
331 let f ref (Just ptr) = writeIORef ref ptr
332 f _ Nothing = panic "interactiveUI:setBuffering2"
333 zipWithM f [stdin_ptr,stdout_ptr,stderr_ptr]
334 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
337 flushInterpBuffers :: GHCi ()
339 = io $ do getHandle stdout_ptr >>= hFlush
340 getHandle stderr_ptr >>= hFlush
342 turnOffBuffering :: IO ()
344 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
345 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
347 getHandle :: IORef (Ptr ()) -> IO Handle
349 (Ptr addr) <- readIORef ref
350 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)