1 -----------------------------------------------------------------------------
3 -- Monadery code used in InteractiveUI
5 -- (c) The GHC Team 2005-2006
7 -----------------------------------------------------------------------------
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module GhciMonad where
18 #include "HsVersions.h"
21 import Outputable hiding (printForUser, printForUserPartWay)
22 import qualified Outputable
23 import Panic hiding (showException)
34 import Control.Exception as Exception
37 import Data.Int ( Int64 )
43 import Control.Monad as Monad
46 -----------------------------------------------------------------------------
49 type Command = (String, String -> GHCi Bool, Maybe String, String -> IO [String])
51 data GHCiState = GHCiState
58 session :: GHC.Session,
59 options :: [GHCiOption],
60 prelude :: GHC.Module,
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, [String], [String])]
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.
85 type TickArray = Array Int [(BreakIndex,SrcSpan)]
88 = ShowTiming -- show time/allocs after evaluation
89 | ShowType -- show the type of expressions
90 | RevertCAFs -- revert CAFs after every evaluation
95 { breakModule :: !GHC.Module
96 , breakLoc :: !SrcSpan
97 , breakTick :: {-# UNPACK #-} !Int
98 , onBreakCmd :: String
101 instance Eq BreakLocation where
102 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
103 breakTick loc1 == breakTick loc2
105 prettyLocations :: [(Int, BreakLocation)] -> SDoc
106 prettyLocations [] = text "No active breakpoints."
107 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
109 instance Outputable BreakLocation where
110 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
111 if null (onBreakCmd loc)
113 else doubleQuotes (text (onBreakCmd loc))
115 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
116 recordBreak brkLoc = do
118 let oldActiveBreaks = breaks st
119 -- don't store the same break point twice
120 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
121 (nm:_) -> return (True, nm)
123 let oldCounter = break_ctr st
124 newCounter = oldCounter + 1
125 setGHCiState $ st { break_ctr = newCounter,
126 breaks = (oldCounter, brkLoc) : oldActiveBreaks
128 return (False, oldCounter)
130 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> IO a }
132 startGHCi :: GHCi a -> GHCiState -> IO a
133 startGHCi g state = do ref <- newIORef state; unGHCi g ref
135 instance Monad GHCi where
136 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
137 return a = GHCi $ \s -> return a
139 instance Functor GHCi where
140 fmap f m = m >>= return . f
142 ghciHandleDyn :: Typeable t => (t -> GHCi a) -> GHCi a -> GHCi a
143 ghciHandleDyn h (GHCi m) = GHCi $ \s ->
144 Exception.catchDyn (m s) (\e -> unGHCi (h e) s)
146 getGHCiState = GHCi $ \r -> readIORef r
147 setGHCiState s = GHCi $ \r -> writeIORef r s
149 -- for convenience...
150 getSession = getGHCiState >>= return . session
151 getPrelude = getGHCiState >>= return . prelude
153 GLOBAL_VAR(saved_sess, no_saved_sess, GHC.Session)
154 no_saved_sess = error "no saved_ses"
155 saveSession = getSession >>= io . writeIORef saved_sess
156 splatSavedSession = io (writeIORef saved_sess no_saved_sess)
157 restoreSession = readIORef saved_sess
161 io (GHC.getSessionDynFlags s)
162 setDynFlags dflags = do
164 io (GHC.setSessionDynFlags s dflags)
166 isOptionSet :: GHCiOption -> GHCi Bool
168 = do st <- getGHCiState
169 return (opt `elem` options st)
171 setOption :: GHCiOption -> GHCi ()
173 = do st <- getGHCiState
174 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
176 unsetOption :: GHCiOption -> GHCi ()
178 = do st <- getGHCiState
179 setGHCiState (st{ options = filter (/= opt) (options st) })
182 io m = GHCi { unGHCi = \s -> m >>= return }
184 printForUser :: SDoc -> GHCi ()
185 printForUser doc = do
186 session <- getSession
187 unqual <- io (GHC.getPrintUnqual session)
188 io $ Outputable.printForUser stdout unqual doc
190 printForUserPartWay :: SDoc -> GHCi ()
191 printForUserPartWay doc = do
192 session <- getSession
193 unqual <- io (GHC.getPrintUnqual session)
194 io $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
196 -- --------------------------------------------------------------------------
197 -- timing & statistics
199 timeIt :: GHCi a -> GHCi a
201 = do b <- isOptionSet ShowTiming
204 else do allocs1 <- io $ getAllocations
205 time1 <- io $ getCPUTime
207 allocs2 <- io $ getAllocations
208 time2 <- io $ getCPUTime
209 io $ printTimes (fromIntegral (allocs2 - allocs1))
213 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
214 -- defined in ghc/rts/Stats.c
216 printTimes :: Integer -> Integer -> IO ()
217 printTimes allocs psecs
218 = do let secs = (fromIntegral psecs / (10^12)) :: Float
219 secs_str = showFFloat (Just 2) secs
221 parens (text (secs_str "") <+> text "secs" <> comma <+>
222 text (show allocs) <+> text "bytes")))
224 -----------------------------------------------------------------------------
231 -- Have to turn off buffering again, because we just
232 -- reverted stdout, stderr & stdin to their defaults.
234 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
235 -- Make it "safe", just in case
237 -----------------------------------------------------------------------------
238 -- To flush buffers for the *interpreted* computation we need
239 -- to refer to *its* stdout/stderr handles
241 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
242 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
243 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
245 -- After various attempts, I believe this is the least bad way to do
246 -- what we want. We know look up the address of the static stdin,
247 -- stdout, and stderr closures in the loaded base package, and each
248 -- time we need to refer to them we cast the pointer to a Handle.
249 -- This avoids any problems with the CAF having been reverted, because
250 -- we'll always get the current value.
252 -- The previous attempt that didn't work was to compile an expression
253 -- like "hSetBuffering stdout NoBuffering" into an expression of type
254 -- IO () and run this expression each time we needed it, but the
255 -- problem is that evaluating the expression might cache the contents
256 -- of the Handle rather than referring to it from its static address
257 -- each time. There's no safe workaround for this.
259 initInterpBuffering :: GHC.Session -> IO ()
260 initInterpBuffering session
261 = do -- make sure these are linked
262 mb_hval1 <- GHC.compileExpr session "System.IO.stdout"
263 mb_hval2 <- GHC.compileExpr session "System.IO.stderr"
264 mb_hval3 <- GHC.compileExpr session "System.IO.stdin"
265 when (any isNothing [mb_hval1,mb_hval2,mb_hval3]) $
266 panic "interactiveUI:setBuffering"
268 -- ToDo: we should really look up these names properly, but
269 -- it's a fiddle and not all the bits are exposed via the GHC
271 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdin_closure"
272 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdout_closure"
273 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stderr_closure"
275 let f ref (Just ptr) = writeIORef ref ptr
276 f ref Nothing = panic "interactiveUI:setBuffering2"
277 zipWithM f [stdin_ptr,stdout_ptr,stderr_ptr]
278 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
281 flushInterpBuffers :: GHCi ()
283 = io $ do getHandle stdout_ptr >>= hFlush
284 getHandle stderr_ptr >>= hFlush
286 turnOffBuffering :: IO ()
288 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
289 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
291 getHandle :: IORef (Ptr ()) -> IO Handle
293 (Ptr addr) <- readIORef ref
294 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)