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 GhcMonad hiding (liftIO)
18 import Outputable hiding (printForUser, printForUserPartWay)
19 import qualified Outputable
20 import Panic hiding (showException)
29 import qualified MonadUtils
34 import Data.Int ( Int64 )
37 import System.Environment
39 import Control.Monad as Monad
42 import System.Console.Haskeline (CompletionFunc, InputT)
43 import qualified System.Console.Haskeline as Haskeline
44 import Control.Monad.Trans as Trans
46 -----------------------------------------------------------------------------
49 type Command = (String, String -> InputT GHCi Bool, CompletionFunc GHCi)
51 data GHCiState = GHCiState
58 options :: [GHCiOption],
59 prelude :: GHC.Module,
60 line_number :: !Int, -- input line
62 breaks :: ![(Int, BreakLocation)],
63 tickarrays :: ModuleEnv TickArray,
64 -- tickarrays caches the TickArray for loaded modules,
65 -- so that we don't rebuild it each time the user sets
67 -- ":" at the GHCi prompt repeats the last command, so we
69 last_command :: Maybe Command,
71 remembered_ctx :: [CtxtCmd],
72 -- we remember the :module commands between :loads, so that
73 -- on a :reload we can replay them. See bugs #2049,
74 -- \#1873, #1360. Previously we tried to remember modules that
75 -- were supposed to be in the context but currently had errors,
76 -- but this was complicated. Just replaying the :module commands
77 -- seems to be the right thing.
78 ghc_e :: Bool -- True if this is 'ghc -e' (or runghc)
81 data CtxtCmd -- In each case, the first [String] are the starred modules
82 -- and the second are the unstarred ones
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
94 | Multiline -- use multiline commands
99 { breakModule :: !GHC.Module
100 , breakLoc :: !SrcSpan
101 , breakTick :: {-# UNPACK #-} !Int
102 , onBreakCmd :: String
105 instance Eq BreakLocation where
106 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
107 breakTick loc1 == breakTick loc2
109 prettyLocations :: [(Int, BreakLocation)] -> SDoc
110 prettyLocations [] = text "No active breakpoints."
111 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
113 instance Outputable BreakLocation where
114 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
115 if null (onBreakCmd loc)
117 else doubleQuotes (text (onBreakCmd loc))
119 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
120 recordBreak brkLoc = do
122 let oldActiveBreaks = breaks st
123 -- don't store the same break point twice
124 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
125 (nm:_) -> return (True, nm)
127 let oldCounter = break_ctr st
128 newCounter = oldCounter + 1
129 setGHCiState $ st { break_ctr = newCounter,
130 breaks = (oldCounter, brkLoc) : oldActiveBreaks
132 return (False, oldCounter)
134 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> Ghc a }
136 reflectGHCi :: (Session, IORef GHCiState) -> GHCi a -> IO a
137 reflectGHCi (s, gs) m = unGhc (unGHCi m gs) s
139 reifyGHCi :: ((Session, IORef GHCiState) -> IO a) -> GHCi a
140 reifyGHCi f = GHCi f'
142 -- f' :: IORef GHCiState -> Ghc a
143 f' gs = reifyGhc (f'' gs)
144 -- f'' :: IORef GHCiState -> Session -> IO a
147 startGHCi :: GHCi a -> GHCiState -> Ghc a
148 startGHCi g state = do ref <- liftIO $ newIORef state; unGHCi g ref
150 instance Monad GHCi where
151 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
152 return a = GHCi $ \_ -> return a
154 instance Functor GHCi where
155 fmap f m = m >>= return . f
157 ghciHandleGhcException :: (GhcException -> GHCi a) -> GHCi a -> GHCi a
158 ghciHandleGhcException = handleGhcException
160 getGHCiState :: GHCi GHCiState
161 getGHCiState = GHCi $ \r -> liftIO $ readIORef r
162 setGHCiState :: GHCiState -> GHCi ()
163 setGHCiState s = GHCi $ \r -> liftIO $ writeIORef r s
165 liftGhc :: Ghc a -> GHCi a
166 liftGhc m = GHCi $ \_ -> m
168 instance MonadUtils.MonadIO GHCi where
169 liftIO = liftGhc . MonadUtils.liftIO
171 instance Trans.MonadIO Ghc where
172 liftIO = MonadUtils.liftIO
174 instance GhcMonad GHCi where
175 setSession s' = liftGhc $ setSession s'
176 getSession = liftGhc $ getSession
178 instance GhcMonad (InputT GHCi) where
179 setSession = lift . setSession
180 getSession = lift getSession
182 instance MonadUtils.MonadIO (InputT GHCi) where
183 liftIO = Trans.liftIO
185 instance ExceptionMonad GHCi where
186 gcatch m h = GHCi $ \r -> unGHCi m r `gcatch` (\e -> unGHCi (h e) r)
187 gblock (GHCi m) = GHCi $ \r -> gblock (m r)
188 gunblock (GHCi m) = GHCi $ \r -> gunblock (m r)
190 GHCi $ \s -> gmask $ \io_restore ->
192 g_restore (GHCi m) = GHCi $ \s' -> io_restore (m s')
194 unGHCi (f g_restore) s
196 instance MonadIO GHCi where
197 liftIO = MonadUtils.liftIO
199 instance Haskeline.MonadException GHCi where
203 -- XXX when Haskeline's MonadException changes, we can drop our
204 -- deprecated block/unblock methods
206 instance ExceptionMonad (InputT GHCi) where
207 gcatch = Haskeline.catch
208 gmask f = Haskeline.block (f Haskeline.unblock) -- slightly wrong
209 gblock = Haskeline.block
210 gunblock = Haskeline.unblock
212 -- for convenience...
213 getPrelude :: GHCi Module
214 getPrelude = getGHCiState >>= return . prelude
216 getDynFlags :: GhcMonad m => m DynFlags
218 GHC.getSessionDynFlags
220 setDynFlags :: DynFlags -> GHCi [PackageId]
221 setDynFlags dflags = do
222 GHC.setSessionDynFlags dflags
224 isOptionSet :: GHCiOption -> GHCi Bool
226 = do st <- getGHCiState
227 return (opt `elem` options st)
229 setOption :: GHCiOption -> GHCi ()
231 = do st <- getGHCiState
232 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
234 unsetOption :: GHCiOption -> GHCi ()
236 = do st <- getGHCiState
237 setGHCiState (st{ options = filter (/= opt) (options st) })
239 printForUser :: GhcMonad m => SDoc -> m ()
240 printForUser doc = do
241 unqual <- GHC.getPrintUnqual
242 MonadUtils.liftIO $ Outputable.printForUser stdout unqual doc
244 printForUserPartWay :: SDoc -> GHCi ()
245 printForUserPartWay doc = do
246 unqual <- GHC.getPrintUnqual
247 liftIO $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
249 runStmt :: String -> GHC.SingleStep -> GHCi GHC.RunResult
250 runStmt expr step = do
253 withProgName (progname st) $
256 GHC.handleSourceError (\e -> do GHC.printException e
257 return GHC.RunFailed) $ do
258 GHC.runStmtWithLocation (progname st) (line_number st) expr step
260 resume :: (SrcSpan -> Bool) -> GHC.SingleStep -> GHCi GHC.RunResult
261 resume canLogSpan step = do
264 withProgName (progname st) $
267 GHC.resume canLogSpan step
269 -- --------------------------------------------------------------------------
270 -- timing & statistics
272 timeIt :: InputT GHCi a -> InputT GHCi a
274 = do b <- lift $ isOptionSet ShowTiming
277 else do allocs1 <- liftIO $ getAllocations
278 time1 <- liftIO $ getCPUTime
280 allocs2 <- liftIO $ getAllocations
281 time2 <- liftIO $ getCPUTime
282 liftIO $ printTimes (fromIntegral (allocs2 - allocs1))
286 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
287 -- defined in ghc/rts/Stats.c
289 printTimes :: Integer -> Integer -> IO ()
290 printTimes allocs psecs
291 = do let secs = (fromIntegral psecs / (10^(12::Integer))) :: Float
292 secs_str = showFFloat (Just 2) secs
294 parens (text (secs_str "") <+> text "secs" <> comma <+>
295 text (show allocs) <+> text "bytes")))
297 -----------------------------------------------------------------------------
300 revertCAFs :: GHCi ()
302 liftIO rts_revertCAFs
304 when (not (ghc_e s)) $ liftIO turnOffBuffering
305 -- Have to turn off buffering again, because we just
306 -- reverted stdout, stderr & stdin to their defaults.
308 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
309 -- Make it "safe", just in case
311 -----------------------------------------------------------------------------
312 -- To flush buffers for the *interpreted* computation we need
313 -- to refer to *its* stdout/stderr handles
315 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
316 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
317 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
319 -- After various attempts, I believe this is the least bad way to do
320 -- what we want. We know look up the address of the static stdin,
321 -- stdout, and stderr closures in the loaded base package, and each
322 -- time we need to refer to them we cast the pointer to a Handle.
323 -- This avoids any problems with the CAF having been reverted, because
324 -- we'll always get the current value.
326 -- The previous attempt that didn't work was to compile an expression
327 -- like "hSetBuffering stdout NoBuffering" into an expression of type
328 -- IO () and run this expression each time we needed it, but the
329 -- problem is that evaluating the expression might cache the contents
330 -- of the Handle rather than referring to it from its static address
331 -- each time. There's no safe workaround for this.
333 initInterpBuffering :: Ghc ()
334 initInterpBuffering = do -- make sure these are linked
335 dflags <- GHC.getSessionDynFlags
339 -- ToDo: we should really look up these names properly, but
340 -- it's a fiddle and not all the bits are exposed via the GHC
342 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stdin_closure"
343 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stdout_closure"
344 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziIOziHandleziFD_stderr_closure"
346 let f ref (Just ptr) = writeIORef ref ptr
347 f _ Nothing = panic "interactiveUI:setBuffering2"
348 zipWithM_ f [stdin_ptr,stdout_ptr,stderr_ptr]
349 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
351 flushInterpBuffers :: GHCi ()
353 = liftIO $ do getHandle stdout_ptr >>= hFlush
354 getHandle stderr_ptr >>= hFlush
356 turnOffBuffering :: IO ()
358 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
359 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
361 getHandle :: IORef (Ptr ()) -> IO Handle
363 (Ptr addr) <- readIORef ref
364 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)