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 data GHCiState = GHCiState
56 session :: GHC.Session,
57 options :: [GHCiOption],
58 prelude :: GHC.Module,
60 breaks :: ![(Int, BreakLocation)],
61 tickarrays :: ModuleEnv TickArray,
62 -- tickarrays caches the TickArray for loaded modules,
63 -- so that we don't rebuild it each time the user sets
66 remembered_ctx :: Maybe ([Module],[Module])
67 -- modules we want to add to the context, but can't
68 -- because they currently have errors. Set by :reload.
71 type TickArray = Array Int [(BreakIndex,SrcSpan)]
74 = ShowTiming -- show time/allocs after evaluation
75 | ShowType -- show the type of expressions
76 | RevertCAFs -- revert CAFs after every evaluation
81 { breakModule :: !GHC.Module
82 , breakLoc :: !SrcSpan
83 , breakTick :: {-# UNPACK #-} !Int
84 , onBreakCmd :: String
87 instance Eq BreakLocation where
88 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
89 breakTick loc1 == breakTick loc2
91 prettyLocations :: [(Int, BreakLocation)] -> SDoc
92 prettyLocations [] = text "No active breakpoints."
93 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
95 instance Outputable BreakLocation where
96 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
97 if null (onBreakCmd loc)
99 else doubleQuotes (text (onBreakCmd loc))
101 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
102 recordBreak brkLoc = do
104 let oldActiveBreaks = breaks st
105 -- don't store the same break point twice
106 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
107 (nm:_) -> return (True, nm)
109 let oldCounter = break_ctr st
110 newCounter = oldCounter + 1
111 setGHCiState $ st { break_ctr = newCounter,
112 breaks = (oldCounter, brkLoc) : oldActiveBreaks
114 return (False, oldCounter)
116 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> IO a }
118 startGHCi :: GHCi a -> GHCiState -> IO a
119 startGHCi g state = do ref <- newIORef state; unGHCi g ref
121 instance Monad GHCi where
122 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
123 return a = GHCi $ \s -> return a
125 instance Functor GHCi where
126 fmap f m = m >>= return . f
128 ghciHandleDyn :: Typeable t => (t -> GHCi a) -> GHCi a -> GHCi a
129 ghciHandleDyn h (GHCi m) = GHCi $ \s ->
130 Exception.catchDyn (m s) (\e -> unGHCi (h e) s)
132 getGHCiState = GHCi $ \r -> readIORef r
133 setGHCiState s = GHCi $ \r -> writeIORef r s
135 -- for convenience...
136 getSession = getGHCiState >>= return . session
137 getPrelude = getGHCiState >>= return . prelude
139 GLOBAL_VAR(saved_sess, no_saved_sess, GHC.Session)
140 no_saved_sess = error "no saved_ses"
141 saveSession = getSession >>= io . writeIORef saved_sess
142 splatSavedSession = io (writeIORef saved_sess no_saved_sess)
143 restoreSession = readIORef saved_sess
147 io (GHC.getSessionDynFlags s)
148 setDynFlags dflags = do
150 io (GHC.setSessionDynFlags s dflags)
152 isOptionSet :: GHCiOption -> GHCi Bool
154 = do st <- getGHCiState
155 return (opt `elem` options st)
157 setOption :: GHCiOption -> GHCi ()
159 = do st <- getGHCiState
160 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
162 unsetOption :: GHCiOption -> GHCi ()
164 = do st <- getGHCiState
165 setGHCiState (st{ options = filter (/= opt) (options st) })
168 io m = GHCi { unGHCi = \s -> m >>= return }
170 printForUser :: SDoc -> GHCi ()
171 printForUser doc = do
172 session <- getSession
173 unqual <- io (GHC.getPrintUnqual session)
174 io $ Outputable.printForUser stdout unqual doc
176 printForUserPartWay :: SDoc -> GHCi ()
177 printForUserPartWay doc = do
178 session <- getSession
179 unqual <- io (GHC.getPrintUnqual session)
180 io $ Outputable.printForUserPartWay stdout opt_PprUserLength unqual doc
182 -- --------------------------------------------------------------------------
183 -- timing & statistics
185 timeIt :: GHCi a -> GHCi a
187 = do b <- isOptionSet ShowTiming
190 else do allocs1 <- io $ getAllocations
191 time1 <- io $ getCPUTime
193 allocs2 <- io $ getAllocations
194 time2 <- io $ getCPUTime
195 io $ printTimes (fromIntegral (allocs2 - allocs1))
199 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
200 -- defined in ghc/rts/Stats.c
202 printTimes :: Integer -> Integer -> IO ()
203 printTimes allocs psecs
204 = do let secs = (fromIntegral psecs / (10^12)) :: Float
205 secs_str = showFFloat (Just 2) secs
207 parens (text (secs_str "") <+> text "secs" <> comma <+>
208 text (show allocs) <+> text "bytes")))
210 -----------------------------------------------------------------------------
217 -- Have to turn off buffering again, because we just
218 -- reverted stdout, stderr & stdin to their defaults.
220 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
221 -- Make it "safe", just in case
223 -----------------------------------------------------------------------------
224 -- To flush buffers for the *interpreted* computation we need
225 -- to refer to *its* stdout/stderr handles
227 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
228 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
229 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
231 -- After various attempts, I believe this is the least bad way to do
232 -- what we want. We know look up the address of the static stdin,
233 -- stdout, and stderr closures in the loaded base package, and each
234 -- time we need to refer to them we cast the pointer to a Handle.
235 -- This avoids any problems with the CAF having been reverted, because
236 -- we'll always get the current value.
238 -- The previous attempt that didn't work was to compile an expression
239 -- like "hSetBuffering stdout NoBuffering" into an expression of type
240 -- IO () and run this expression each time we needed it, but the
241 -- problem is that evaluating the expression might cache the contents
242 -- of the Handle rather than referring to it from its static address
243 -- each time. There's no safe workaround for this.
245 initInterpBuffering :: GHC.Session -> IO ()
246 initInterpBuffering session
247 = do -- make sure these are linked
248 mb_hval1 <- GHC.compileExpr session "System.IO.stdout"
249 mb_hval2 <- GHC.compileExpr session "System.IO.stderr"
250 mb_hval3 <- GHC.compileExpr session "System.IO.stdin"
251 when (any isNothing [mb_hval1,mb_hval2,mb_hval3]) $
252 panic "interactiveUI:setBuffering"
254 -- ToDo: we should really look up these names properly, but
255 -- it's a fiddle and not all the bits are exposed via the GHC
257 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdin_closure"
258 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdout_closure"
259 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stderr_closure"
261 let f ref (Just ptr) = writeIORef ref ptr
262 f ref Nothing = panic "interactiveUI:setBuffering2"
263 zipWithM f [stdin_ptr,stdout_ptr,stderr_ptr]
264 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
267 flushInterpBuffers :: GHCi ()
269 = io $ do getHandle stdout_ptr >>= hFlush
270 getHandle stderr_ptr >>= hFlush
272 turnOffBuffering :: IO ()
274 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
275 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
277 getHandle :: IORef (Ptr ()) -> IO Handle
279 (Ptr addr) <- readIORef ref
280 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)