1 -----------------------------------------------------------------------------
3 -- Monadery code used in InteractiveUI
5 -- (c) The GHC Team 2005-2006
7 -----------------------------------------------------------------------------
11 #include "HsVersions.h"
14 import Outputable hiding (printForUser)
15 import qualified Outputable
16 import Panic hiding (showException)
26 import Control.Exception as Exception
29 import Data.Int ( Int64 )
35 import Control.Monad as Monad
38 -----------------------------------------------------------------------------
41 data GHCiState = GHCiState
48 session :: GHC.Session,
49 options :: [GHCiOption],
50 prelude :: GHC.Module,
52 breaks :: ![(Int, BreakLocation)],
53 tickarrays :: ModuleEnv TickArray,
54 -- tickarrays caches the TickArray for loaded modules,
55 -- so that we don't rebuild it each time the user sets
60 type TickArray = Array Int [(BreakIndex,SrcSpan)]
63 = ShowTiming -- show time/allocs after evaluation
64 | ShowType -- show the type of expressions
65 | RevertCAFs -- revert CAFs after every evaluation
70 { breakModule :: !GHC.Module
71 , breakLoc :: !SrcSpan
72 , breakTick :: {-# UNPACK #-} !Int
73 , onBreakCmd :: String
76 instance Eq BreakLocation where
77 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
78 breakTick loc1 == breakTick loc2
80 prettyLocations :: [(Int, BreakLocation)] -> SDoc
81 prettyLocations [] = text "No active breakpoints."
82 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
84 instance Outputable BreakLocation where
85 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
86 if null (onBreakCmd loc)
88 else doubleQuotes (text (onBreakCmd loc))
90 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
91 recordBreak brkLoc = do
93 let oldActiveBreaks = breaks st
94 -- don't store the same break point twice
95 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
96 (nm:_) -> return (True, nm)
98 let oldCounter = break_ctr st
99 newCounter = oldCounter + 1
100 setGHCiState $ st { break_ctr = newCounter,
101 breaks = (oldCounter, brkLoc) : oldActiveBreaks
103 return (False, oldCounter)
105 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> IO a }
107 startGHCi :: GHCi a -> GHCiState -> IO a
108 startGHCi g state = do ref <- newIORef state; unGHCi g ref
110 instance Monad GHCi where
111 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
112 return a = GHCi $ \s -> return a
114 ghciHandleDyn :: Typeable t => (t -> GHCi a) -> GHCi a -> GHCi a
115 ghciHandleDyn h (GHCi m) = GHCi $ \s ->
116 Exception.catchDyn (m s) (\e -> unGHCi (h e) s)
118 getGHCiState = GHCi $ \r -> readIORef r
119 setGHCiState s = GHCi $ \r -> writeIORef r s
121 -- for convenience...
122 getSession = getGHCiState >>= return . session
123 getPrelude = getGHCiState >>= return . prelude
125 GLOBAL_VAR(saved_sess, no_saved_sess, GHC.Session)
126 no_saved_sess = error "no saved_ses"
127 saveSession = getSession >>= io . writeIORef saved_sess
128 splatSavedSession = io (writeIORef saved_sess no_saved_sess)
129 restoreSession = readIORef saved_sess
133 io (GHC.getSessionDynFlags s)
134 setDynFlags dflags = do
136 io (GHC.setSessionDynFlags s dflags)
138 isOptionSet :: GHCiOption -> GHCi Bool
140 = do st <- getGHCiState
141 return (opt `elem` options st)
143 setOption :: GHCiOption -> GHCi ()
145 = do st <- getGHCiState
146 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
148 unsetOption :: GHCiOption -> GHCi ()
150 = do st <- getGHCiState
151 setGHCiState (st{ options = filter (/= opt) (options st) })
154 io m = GHCi { unGHCi = \s -> m >>= return }
156 printForUser :: SDoc -> GHCi ()
157 printForUser doc = do
158 session <- getSession
159 unqual <- io (GHC.getPrintUnqual session)
160 io $ Outputable.printForUser stdout unqual doc
162 -- --------------------------------------------------------------------------
163 -- timing & statistics
165 timeIt :: GHCi a -> GHCi a
167 = do b <- isOptionSet ShowTiming
170 else do allocs1 <- io $ getAllocations
171 time1 <- io $ getCPUTime
173 allocs2 <- io $ getAllocations
174 time2 <- io $ getCPUTime
175 io $ printTimes (fromIntegral (allocs2 - allocs1))
179 foreign import ccall unsafe "getAllocations" getAllocations :: IO Int64
180 -- defined in ghc/rts/Stats.c
182 printTimes :: Integer -> Integer -> IO ()
183 printTimes allocs psecs
184 = do let secs = (fromIntegral psecs / (10^12)) :: Float
185 secs_str = showFFloat (Just 2) secs
187 parens (text (secs_str "") <+> text "secs" <> comma <+>
188 text (show allocs) <+> text "bytes")))
190 -----------------------------------------------------------------------------
197 -- Have to turn off buffering again, because we just
198 -- reverted stdout, stderr & stdin to their defaults.
200 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
201 -- Make it "safe", just in case
203 -----------------------------------------------------------------------------
204 -- To flush buffers for the *interpreted* computation we need
205 -- to refer to *its* stdout/stderr handles
207 GLOBAL_VAR(stdin_ptr, error "no stdin_ptr", Ptr ())
208 GLOBAL_VAR(stdout_ptr, error "no stdout_ptr", Ptr ())
209 GLOBAL_VAR(stderr_ptr, error "no stderr_ptr", Ptr ())
211 -- After various attempts, I believe this is the least bad way to do
212 -- what we want. We know look up the address of the static stdin,
213 -- stdout, and stderr closures in the loaded base package, and each
214 -- time we need to refer to them we cast the pointer to a Handle.
215 -- This avoids any problems with the CAF having been reverted, because
216 -- we'll always get the current value.
218 -- The previous attempt that didn't work was to compile an expression
219 -- like "hSetBuffering stdout NoBuffering" into an expression of type
220 -- IO () and run this expression each time we needed it, but the
221 -- problem is that evaluating the expression might cache the contents
222 -- of the Handle rather than referring to it from its static address
223 -- each time. There's no safe workaround for this.
225 initInterpBuffering :: GHC.Session -> IO ()
226 initInterpBuffering session
227 = do -- make sure these are linked
228 mb_hval1 <- GHC.compileExpr session "System.IO.stdout"
229 mb_hval2 <- GHC.compileExpr session "System.IO.stderr"
230 mb_hval3 <- GHC.compileExpr session "System.IO.stdin"
231 when (any isNothing [mb_hval1,mb_hval2,mb_hval3]) $
232 panic "interactiveUI:setBuffering"
234 -- ToDo: we should really look up these names properly, but
235 -- it's a fiddle and not all the bits are exposed via the GHC
237 mb_stdin_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdin_closure"
238 mb_stdout_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stdout_closure"
239 mb_stderr_ptr <- ObjLink.lookupSymbol "base_GHCziHandle_stderr_closure"
241 let f ref (Just ptr) = writeIORef ref ptr
242 f ref Nothing = panic "interactiveUI:setBuffering2"
243 zipWithM f [stdin_ptr,stdout_ptr,stderr_ptr]
244 [mb_stdin_ptr,mb_stdout_ptr,mb_stderr_ptr]
247 flushInterpBuffers :: GHCi ()
249 = io $ do getHandle stdout_ptr >>= hFlush
250 getHandle stderr_ptr >>= hFlush
252 turnOffBuffering :: IO ()
254 = do hdls <- mapM getHandle [stdin_ptr,stdout_ptr,stderr_ptr]
255 mapM_ (\h -> hSetBuffering h NoBuffering) hdls
257 getHandle :: IORef (Ptr ()) -> IO Handle
259 (Ptr addr) <- readIORef ref
260 case addrToHValue# addr of (# hval #) -> return (unsafeCoerce# hval)