1 {-# OPTIONS_GHC -fno-cse -fno-warn-orphans #-}
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)
22 import HscTypes hiding (liftIO)
28 import qualified MonadUtils
35 import Data.Int ( Int64 )
39 import System.Environment
41 import Control.Monad as Monad
44 import System.Console.Haskeline (CompletionFunc, InputT)
45 import qualified System.Console.Haskeline as Haskeline
46 import Control.Monad.Trans as Trans
48 -----------------------------------------------------------------------------
51 type Command = (String, String -> InputT GHCi Bool, CompletionFunc GHCi)
53 data GHCiState = GHCiState
60 options :: [GHCiOption],
61 prelude :: GHC.Module,
63 breaks :: ![(Int, BreakLocation)],
64 tickarrays :: ModuleEnv TickArray,
65 -- tickarrays caches the TickArray for loaded modules,
66 -- so that we don't rebuild it each time the user sets
68 -- ":" at the GHCi prompt repeats the last command, so we
70 last_command :: Maybe Command,
72 remembered_ctx :: [CtxtCmd],
73 -- we remember the :module commands between :loads, so that
74 -- on a :reload we can replay them. See bugs #2049,
75 -- \#1873, #1360. Previously we tried to remember modules that
76 -- were supposed to be in the context but currently had errors,
77 -- but this was complicated. Just replaying the :module commands
78 -- seems to be the right thing.
79 ghc_e :: Bool -- True if this is 'ghc -e' (or runghc)
83 = SetContext [String] [String]
84 | AddModules [String] [String]
85 | RemModules [String] [String]
88 type TickArray = Array Int [(BreakIndex,SrcSpan)]
91 = ShowTiming -- show time/allocs after evaluation
92 | ShowType -- show the type of expressions
93 | RevertCAFs -- revert CAFs after every evaluation
98 { breakModule :: !GHC.Module
99 , breakLoc :: !SrcSpan
100 , breakTick :: {-# UNPACK #-} !Int
101 , onBreakCmd :: String
104 instance Eq BreakLocation where
105 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
106 breakTick loc1 == breakTick loc2
108 prettyLocations :: [(Int, BreakLocation)] -> SDoc
109 prettyLocations [] = text "No active breakpoints."
110 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
112 instance Outputable BreakLocation where
113 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
114 if null (onBreakCmd loc)
116 else doubleQuotes (text (onBreakCmd loc))
118 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
119 recordBreak brkLoc = do
121 let oldActiveBreaks = breaks st
122 -- don't store the same break point twice
123 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
124 (nm:_) -> return (True, nm)
126 let oldCounter = break_ctr st
127 newCounter = oldCounter + 1
128 setGHCiState $ st { break_ctr = newCounter,
129 breaks = (oldCounter, brkLoc) : oldActiveBreaks
131 return (False, oldCounter)
133 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> Ghc a }
135 reflectGHCi :: (Session, IORef GHCiState) -> GHCi a -> IO a
136 reflectGHCi (s, gs) m = unGhc (unGHCi m gs) s
138 reifyGHCi :: ((Session, IORef GHCiState) -> IO a) -> GHCi a
139 reifyGHCi f = GHCi f'
141 -- f' :: IORef GHCiState -> Ghc a
142 f' gs = reifyGhc (f'' gs)
143 -- f'' :: IORef GHCiState -> Session -> IO a
146 startGHCi :: GHCi a -> GHCiState -> Ghc a
147 startGHCi g state = do ref <- liftIO $ newIORef state; unGHCi g ref
149 instance Monad GHCi where
150 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
151 return a = GHCi $ \_ -> return a
153 instance Functor GHCi where
154 fmap f m = m >>= return . f
156 ghciHandleGhcException :: (GhcException -> GHCi a) -> GHCi a -> GHCi a
157 ghciHandleGhcException = handleGhcException
159 getGHCiState :: GHCi GHCiState
160 getGHCiState = GHCi $ \r -> liftIO $ readIORef r
161 setGHCiState :: GHCiState -> GHCi ()
162 setGHCiState s = GHCi $ \r -> liftIO $ writeIORef r s
164 liftGhc :: Ghc a -> GHCi a
165 liftGhc m = GHCi $ \_ -> m
167 instance MonadUtils.MonadIO GHCi where
168 liftIO = liftGhc . MonadUtils.liftIO
170 instance Trans.MonadIO Ghc where
171 liftIO = MonadUtils.liftIO
173 instance GhcMonad GHCi where
174 setSession s' = liftGhc $ setSession s'
175 getSession = liftGhc $ getSession
177 instance GhcMonad (InputT GHCi) where
178 setSession = lift . setSession
179 getSession = lift getSession
181 instance MonadUtils.MonadIO (InputT GHCi) where
182 liftIO = Trans.liftIO
184 instance WarnLogMonad (InputT GHCi) where
185 setWarnings = lift . setWarnings
186 getWarnings = lift getWarnings
188 instance ExceptionMonad GHCi where
189 gcatch m h = GHCi $ \r -> unGHCi m r `gcatch` (\e -> unGHCi (h e) r)
190 gblock (GHCi m) = GHCi $ \r -> gblock (m r)
191 gunblock (GHCi m) = GHCi $ \r -> gunblock (m r)
193 GHCi $ \s -> gmask $ \io_restore ->
195 g_restore (GHCi m) = GHCi $ \s' -> io_restore (m s')
197 unGHCi (f g_restore) s
199 instance WarnLogMonad GHCi where
200 setWarnings warns = liftGhc $ setWarnings warns
201 getWarnings = liftGhc $ getWarnings
203 instance MonadIO GHCi where
206 instance Haskeline.MonadException GHCi where
210 -- XXX when Haskeline's MonadException changes, we can drop our
211 -- deprecated block/unblock methods
213 instance ExceptionMonad (InputT GHCi) where
214 gcatch = Haskeline.catch
215 gmask f = Haskeline.block (f Haskeline.unblock) -- slightly wrong
216 gblock = Haskeline.block
217 gunblock = Haskeline.unblock
219 -- for convenience...
220 getPrelude :: GHCi Module
221 getPrelude = getGHCiState >>= return . prelude
223 getDynFlags :: GhcMonad m => m DynFlags
225 GHC.getSessionDynFlags
227 setDynFlags :: DynFlags -> GHCi [PackageId]
228 setDynFlags dflags = do
229 GHC.setSessionDynFlags dflags
231 isOptionSet :: GHCiOption -> GHCi Bool
233 = do st <- getGHCiState
234 return (opt `elem` options st)
236 setOption :: GHCiOption -> GHCi ()
238 = do st <- getGHCiState
239 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
241 unsetOption :: GHCiOption -> GHCi ()
243 = do st <- getGHCiState
244 setGHCiState (st{ options = filter (/= opt) (options st) })
247 io = MonadUtils.liftIO
249 printForUser :: GhcMonad m => SDoc -> m ()
250 printForUser doc = do
251 unqual <- GHC.getPrintUnqual
252 MonadUtils.liftIO $ Outputable.printForUser stdout unqual doc
254 printForUserPartWay :: SDoc -> GHCi ()
255 printForUserPartWay doc = do
256 unqual <- GHC.getPrintUnqual
257 io $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
259 runStmt :: String -> GHC.SingleStep -> GHCi GHC.RunResult
260 runStmt expr step = do
263 withProgName (progname st) $
266 GHC.handleSourceError (\e -> do GHC.printExceptionAndWarnings e
267 return GHC.RunFailed) $ do
268 GHC.runStmt expr step
270 resume :: (SrcSpan -> Bool) -> GHC.SingleStep -> GHCi GHC.RunResult
271 resume canLogSpan step = do
274 withProgName (progname st) $
277 GHC.resume canLogSpan step
279 -- --------------------------------------------------------------------------
280 -- timing & statistics
282 timeIt :: InputT GHCi a -> InputT GHCi a
284 = do b <- lift $ isOptionSet ShowTiming
287 else do allocs1 <- liftIO $ getAllocations
288 time1 <- liftIO $ getCPUTime
290 allocs2 <- liftIO $ getAllocations
291 time2 <- liftIO $ getCPUTime
292 liftIO $ printTimes (fromIntegral (allocs2 - allocs1))
296 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
297 -- defined in ghc/rts/Stats.c
299 printTimes :: Integer -> Integer -> IO ()
300 printTimes allocs psecs
301 = do let secs = (fromIntegral psecs / (10^(12::Integer))) :: Float
302 secs_str = showFFloat (Just 2) secs
304 parens (text (secs_str "") <+> text "secs" <> comma <+>
305 text (show allocs) <+> text "bytes")))
307 -----------------------------------------------------------------------------
310 revertCAFs :: GHCi ()
314 when (not (ghc_e s)) $ io turnOffBuffering
315 -- Have to turn off buffering again, because we just
316 -- reverted stdout, stderr & stdin to their defaults.
318 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
319 -- Make it "safe", just in case
321 -----------------------------------------------------------------------------
322 -- To flush buffers for the *interpreted* computation we need
323 -- to refer to *its* stdout/stderr handles
325 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
326 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
327 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
329 -- After various attempts, I believe this is the least bad way to do
330 -- what we want. We know look up the address of the static stdin,
331 -- stdout, and stderr closures in the loaded base package, and each
332 -- time we need to refer to them we cast the pointer to a Handle.
333 -- This avoids any problems with the CAF having been reverted, because
334 -- we'll always get the current value.
336 -- The previous attempt that didn't work was to compile an expression
337 -- like "hSetBuffering stdout NoBuffering" into an expression of type
338 -- IO () and run this expression each time we needed it, but the
339 -- problem is that evaluating the expression might cache the contents
340 -- of the Handle rather than referring to it from its static address
341 -- each time. There's no safe workaround for this.
343 initInterpBuffering :: Ghc ()
344 initInterpBuffering = do -- make sure these are linked
345 dflags <- GHC.getSessionDynFlags
349 -- ToDo: we should really look up these names properly, but
350 -- it's a fiddle and not all the bits are exposed via the GHC
352 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stdin_closure"
353 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stdout_closure"
354 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stderr_closure"
356 let f ref (Just ptr) = writeIORef ref ptr
357 f _ Nothing = panic "interactiveUI:setBuffering2"
358 zipWithM_ f [stdin_ptr,stdout_ptr,stderr_ptr]
359 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
361 flushInterpBuffers :: GHCi ()
363 = io $ do getHandle stdout_ptr >>= hFlush
364 getHandle stderr_ptr >>= hFlush
366 turnOffBuffering :: IO ()
368 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
369 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
371 getHandle :: IORef (Ptr ()) -> IO Handle
373 (Ptr addr) <- readIORef ref
374 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)