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)
31 import Control.Exception as Exception
34 import Data.Int ( Int64 )
39 import System.Directory
40 import System.Environment
42 import Control.Monad as Monad
45 -----------------------------------------------------------------------------
48 type Command = (String, String -> GHCi Bool, Maybe String, String -> IO [String])
50 data GHCiState = GHCiState
57 session :: GHC.Session,
58 options :: [GHCiOption],
59 prelude :: GHC.Module,
61 breaks :: ![(Int, BreakLocation)],
62 tickarrays :: ModuleEnv TickArray,
63 -- tickarrays caches the TickArray for loaded modules,
64 -- so that we don't rebuild it each time the user sets
66 -- ":" at the GHCi prompt repeats the last command, so we
68 last_command :: Maybe Command,
70 remembered_ctx :: [(CtxtCmd, [String], [String])],
71 -- we remember the :module commands between :loads, so that
72 -- on a :reload we can replay them. See bugs #2049,
73 -- #1873, #1360. Previously we tried to remember modules that
74 -- were supposed to be in the context but currently had errors,
75 -- but this was complicated. Just replaying the :module commands
76 -- seems to be the right thing.
77 virtual_path :: FilePath,
78 ghc_e :: Bool -- True if this is 'ghc -e' (or runghc)
86 type TickArray = Array Int [(BreakIndex,SrcSpan)]
89 = ShowTiming -- show time/allocs after evaluation
90 | ShowType -- show the type of expressions
91 | RevertCAFs -- revert CAFs after every evaluation
96 { breakModule :: !GHC.Module
97 , breakLoc :: !SrcSpan
98 , breakTick :: {-# UNPACK #-} !Int
99 , onBreakCmd :: String
102 instance Eq BreakLocation where
103 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
104 breakTick loc1 == breakTick loc2
106 prettyLocations :: [(Int, BreakLocation)] -> SDoc
107 prettyLocations [] = text "No active breakpoints."
108 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
110 instance Outputable BreakLocation where
111 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
112 if null (onBreakCmd loc)
114 else doubleQuotes (text (onBreakCmd loc))
116 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
117 recordBreak brkLoc = do
119 let oldActiveBreaks = breaks st
120 -- don't store the same break point twice
121 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
122 (nm:_) -> return (True, nm)
124 let oldCounter = break_ctr st
125 newCounter = oldCounter + 1
126 setGHCiState $ st { break_ctr = newCounter,
127 breaks = (oldCounter, brkLoc) : oldActiveBreaks
129 return (False, oldCounter)
131 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> IO a }
133 startGHCi :: GHCi a -> GHCiState -> IO a
134 startGHCi g state = do ref <- newIORef state; unGHCi g ref
136 instance Monad GHCi where
137 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
138 return a = GHCi $ \_ -> return a
140 instance Functor GHCi where
141 fmap f m = m >>= return . f
143 ghciHandleDyn :: Typeable t => (t -> GHCi a) -> GHCi a -> GHCi a
144 ghciHandleDyn h (GHCi m) = GHCi $ \s ->
145 Exception.catchDyn (m s) (\e -> unGHCi (h e) s)
147 getGHCiState :: GHCi GHCiState
148 getGHCiState = GHCi $ \r -> readIORef r
149 setGHCiState :: GHCiState -> GHCi ()
150 setGHCiState s = GHCi $ \r -> writeIORef r s
152 -- for convenience...
153 getSession :: GHCi Session
154 getSession = getGHCiState >>= return . session
155 getPrelude :: GHCi Module
156 getPrelude = getGHCiState >>= return . prelude
158 GLOBAL_VAR(saved_sess, no_saved_sess, GHC.Session)
160 no_saved_sess :: Session
161 no_saved_sess = error "no saved_ses"
163 saveSession :: GHCi ()
164 saveSession = getSession >>= io . writeIORef saved_sess
166 splatSavedSession :: GHCi ()
167 splatSavedSession = io (writeIORef saved_sess no_saved_sess)
169 restoreSession :: IO Session
170 restoreSession = readIORef saved_sess
172 getDynFlags :: GHCi DynFlags
175 io (GHC.getSessionDynFlags s)
176 setDynFlags :: DynFlags -> GHCi [PackageId]
177 setDynFlags dflags = do
179 io (GHC.setSessionDynFlags s dflags)
181 isOptionSet :: GHCiOption -> GHCi Bool
183 = do st <- getGHCiState
184 return (opt `elem` options st)
186 setOption :: GHCiOption -> GHCi ()
188 = do st <- getGHCiState
189 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
191 unsetOption :: GHCiOption -> GHCi ()
193 = do st <- getGHCiState
194 setGHCiState (st{ options = filter (/= opt) (options st) })
197 io m = GHCi (\_ -> m)
199 printForUser :: SDoc -> GHCi ()
200 printForUser doc = do
201 session <- getSession
202 unqual <- io (GHC.getPrintUnqual session)
203 io $ Outputable.printForUser stdout unqual doc
205 printForUserPartWay :: SDoc -> GHCi ()
206 printForUserPartWay doc = do
207 session <- getSession
208 unqual <- io (GHC.getPrintUnqual session)
209 io $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
211 withVirtualPath :: GHCi a -> GHCi a
212 withVirtualPath m = do
213 ghci_wd <- io getCurrentDirectory -- Store the cwd of GHCi
215 io$ setCurrentDirectory (virtual_path st)
216 result <- m -- Evaluate in the virtual wd..
217 vwd <- io getCurrentDirectory
218 setGHCiState (st{ virtual_path = vwd}) -- Update the virtual path
219 io$ setCurrentDirectory ghci_wd -- ..and restore GHCi wd
222 runStmt :: String -> GHC.SingleStep -> GHCi GHC.RunResult
223 runStmt expr step = withVirtualPath$ do
224 session <- getSession
226 io$ withProgName (progname st) $ withArgs (args st) $
227 GHC.runStmt session expr step
229 resume :: GHC.SingleStep -> GHCi GHC.RunResult
230 resume step = withVirtualPath$ do
231 session <- getSession
232 io$ GHC.resume session step
235 -- --------------------------------------------------------------------------
236 -- timing & statistics
238 timeIt :: GHCi a -> GHCi a
240 = do b <- isOptionSet ShowTiming
243 else do allocs1 <- io $ getAllocations
244 time1 <- io $ getCPUTime
246 allocs2 <- io $ getAllocations
247 time2 <- io $ getCPUTime
248 io $ printTimes (fromIntegral (allocs2 - allocs1))
252 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
253 -- defined in ghc/rts/Stats.c
255 printTimes :: Integer -> Integer -> IO ()
256 printTimes allocs psecs
257 = do let secs = (fromIntegral psecs / (10^12)) :: Float
258 secs_str = showFFloat (Just 2) secs
260 parens (text (secs_str "") <+> text "secs" <> comma <+>
261 text (show allocs) <+> text "bytes")))
263 -----------------------------------------------------------------------------
266 revertCAFs :: GHCi ()
270 when (not (ghc_e s)) $ io turnOffBuffering
271 -- Have to turn off buffering again, because we just
272 -- reverted stdout, stderr & stdin to their defaults.
274 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
275 -- Make it "safe", just in case
277 -----------------------------------------------------------------------------
278 -- To flush buffers for the *interpreted* computation we need
279 -- to refer to *its* stdout/stderr handles
281 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
282 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
283 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
285 -- After various attempts, I believe this is the least bad way to do
286 -- what we want. We know look up the address of the static stdin,
287 -- stdout, and stderr closures in the loaded base package, and each
288 -- time we need to refer to them we cast the pointer to a Handle.
289 -- This avoids any problems with the CAF having been reverted, because
290 -- we'll always get the current value.
292 -- The previous attempt that didn't work was to compile an expression
293 -- like "hSetBuffering stdout NoBuffering" into an expression of type
294 -- IO () and run this expression each time we needed it, but the
295 -- problem is that evaluating the expression might cache the contents
296 -- of the Handle rather than referring to it from its static address
297 -- each time. There's no safe workaround for this.
299 initInterpBuffering :: GHC.Session -> IO ()
300 initInterpBuffering session
301 = do -- make sure these are linked
302 dflags <- GHC.getSessionDynFlags session
305 -- ToDo: we should really look up these names properly, but
306 -- it's a fiddle and not all the bits are exposed via the GHC
308 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdin_closure"
309 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdout_closure"
310 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stderr_closure"
312 let f ref (Just ptr) = writeIORef ref ptr
313 f _ Nothing = panic "interactiveUI:setBuffering2"
314 zipWithM f [stdin_ptr,stdout_ptr,stderr_ptr]
315 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
318 flushInterpBuffers :: GHCi ()
320 = io $ do getHandle stdout_ptr >>= hFlush
321 getHandle stderr_ptr >>= hFlush
323 turnOffBuffering :: IO ()
325 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
326 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
328 getHandle :: IORef (Ptr ()) -> IO Handle
330 (Ptr addr) <- readIORef ref
331 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)