Debian Codegraph @

src-bin-861/Clash/GHCi/UI/Monad.hs

raw
1 {-# OPTIONS_GHC -Wno-name-shadowing #-}
2 {-# LANGUAGE CPP #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE UnboxedTuples #-}
5
6 {-# OPTIONS_GHC -fno-cse -fno-warn-orphans #-}
7 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
8
9 -----------------------------------------------------------------------------
10 --
11 -- Monadery code used in InteractiveUI
12 --
13 -- (c) The GHC Team 2005-2006
14 --
15 -----------------------------------------------------------------------------
16
17 module Clash.GHCi.UI.Monad (
18 GHCi(..), startGHCi,
19 GHCiState(..), setGHCiState, getGHCiState, modifyGHCiState,
20 GHCiOption(..), isOptionSet, setOption, unsetOption,
21 Command(..),
22 PromptFunction,
23 BreakLocation(..),
24 TickArray,
25 getDynFlags,
26
27 runStmt, runDecls, resume, timeIt, recordBreak, revertCAFs,
28
29 printForUserNeverQualify, printForUserModInfo,
30 printForUser, printForUserPartWay, prettyLocations,
31 initInterpBuffering,
32 turnOffBuffering, turnOffBuffering_,
33 flushInterpBuffers,
34 mkEvalWrapper
35 ) where
36
37 #include "HsVersions.h"
38
39 import Clash.GHCi.UI.Info (ModInfo)
40 import qualified GHC
41 import GhcMonad hiding (liftIO)
42 import Outputable hiding (printForUser, printForUserPartWay)
43 import qualified Outputable
44 import DynFlags
45 import FastString
46 import HscTypes
47 import SrcLoc
48 import Module
49 import GHCi
50 import GHCi.RemoteTypes
51 import HsSyn (ImportDecl, GhcPs)
52 import Util
53
54 import Exception
55 import Numeric
56 import Data.Array
57 import Data.IORef
58 import Data.Time
59 import System.Environment
60 import System.IO
61 import Control.Monad
62 import Prelude hiding ((<>))
63
64 import System.Console.Haskeline (CompletionFunc, InputT)
65 import qualified System.Console.Haskeline as Haskeline
66 import Control.Monad.Trans.Class
67 import Control.Monad.IO.Class
68 import Data.Map.Strict (Map)
69 import qualified GHC.LanguageExtensions as LangExt
70
71 -----------------------------------------------------------------------------
72 -- GHCi monad
73
74 data GHCiState = GHCiState
75 {
76 progname :: String,
77 args :: [String],
78 evalWrapper :: ForeignHValue, -- ^ of type @IO a -> IO a@
79 prompt :: PromptFunction,
80 prompt_cont :: PromptFunction,
81 editor :: String,
82 stop :: String,
83 options :: [GHCiOption],
84 line_number :: !Int, -- ^ input line
85 break_ctr :: !Int,
86 breaks :: ![(Int, BreakLocation)],
87 tickarrays :: ModuleEnv TickArray,
88 -- ^ 'tickarrays' caches the 'TickArray' for loaded modules,
89 -- so that we don't rebuild it each time the user sets
90 -- a breakpoint.
91 ghci_commands :: [Command],
92 -- ^ available ghci commands
93 ghci_macros :: [Command],
94 -- ^ user-defined macros
95 last_command :: Maybe Command,
96 -- ^ @:@ at the GHCi prompt repeats the last command, so we
97 -- remember it here
98 cmdqueue :: [String],
99
100 remembered_ctx :: [InteractiveImport],
101 -- ^ The imports that the user has asked for, via import
102 -- declarations and :module commands. This list is
103 -- persistent over :reloads (but any imports for modules
104 -- that are not loaded are temporarily ignored). After a
105 -- :load, all the home-package imports are stripped from
106 -- this list.
107 --
108 -- See bugs #2049, #1873, #1360
109
110 transient_ctx :: [InteractiveImport],
111 -- ^ An import added automatically after a :load, usually of
112 -- the most recently compiled module. May be empty if
113 -- there are no modules loaded. This list is replaced by
114 -- :load, :reload, and :add. In between it may be modified
115 -- by :module.
116
117 extra_imports :: [ImportDecl GhcPs],
118 -- ^ These are "always-on" imports, added to the
119 -- context regardless of what other imports we have.
120 -- This is useful for adding imports that are required
121 -- by setGHCiMonad. Be careful adding things here:
122 -- you can create ambiguities if these imports overlap
123 -- with other things in scope.
124 --
125 -- NB. although this is not currently used by GHCi itself,
126 -- it was added to support other front-ends that are based
127 -- on the GHCi code. Potentially we could also expose
128 -- this functionality via GHCi commands.
129
130 prelude_imports :: [ImportDecl GhcPs],
131 -- ^ These imports are added to the context when
132 -- -XImplicitPrelude is on and we don't have a *-module
133 -- in the context. They can also be overridden by another
134 -- import for the same module, e.g.
135 -- "import Prelude hiding (map)"
136
137 ghc_e :: Bool, -- ^ True if this is 'ghc -e' (or runghc)
138
139 short_help :: String,
140 -- ^ help text to display to a user
141 long_help :: String,
142 lastErrorLocations :: IORef [(FastString, Int)],
143
144 mod_infos :: !(Map ModuleName ModInfo),
145
146 flushStdHandles :: ForeignHValue,
147 -- ^ @hFlush stdout; hFlush stderr@ in the interpreter
148 noBuffering :: ForeignHValue
149 -- ^ @hSetBuffering NoBuffering@ for stdin/stdout/stderr
150 }
151
152 type TickArray = Array Int [(GHC.BreakIndex,RealSrcSpan)]
153
154 -- | A GHCi command
155 data Command
156 = Command
157 { cmdName :: String
158 -- ^ Name of GHCi command (e.g. "exit")
159 , cmdAction :: String -> InputT GHCi Bool
160 -- ^ The 'Bool' value denotes whether to exit GHCi
161 , cmdHidden :: Bool
162 -- ^ Commands which are excluded from default completion
163 -- and @:help@ summary. This is usually set for commands not
164 -- useful for interactive use but rather for IDEs.
165 , cmdCompletionFunc :: CompletionFunc GHCi
166 -- ^ 'CompletionFunc' for arguments
167 }
168
169 type PromptFunction = [String]
170 -> Int
171 -> GHCi SDoc
172
173 data GHCiOption
174 = ShowTiming -- show time/allocs after evaluation
175 | ShowType -- show the type of expressions
176 | RevertCAFs -- revert CAFs after every evaluation
177 | Multiline -- use multiline commands
178 | CollectInfo -- collect and cache information about
179 -- modules after load
180 deriving Eq
181
182 data BreakLocation
183 = BreakLocation
184 { breakModule :: !GHC.Module
185 , breakLoc :: !SrcSpan
186 , breakTick :: {-# UNPACK #-} !Int
187 , onBreakCmd :: String
188 }
189
190 instance Eq BreakLocation where
191 loc1 == loc2 = breakModule loc1 == breakModule loc2 &&
192 breakTick loc1 == breakTick loc2
193
194 prettyLocations :: [(Int, BreakLocation)] -> SDoc
195 prettyLocations [] = text "No active breakpoints."
196 prettyLocations locs = vcat $ map (\(i, loc) -> brackets (int i) <+> ppr loc) $ reverse $ locs
197
198 instance Outputable BreakLocation where
199 ppr loc = (ppr $ breakModule loc) <+> ppr (breakLoc loc) <+>
200 if null (onBreakCmd loc)
201 then Outputable.empty
202 else doubleQuotes (text (onBreakCmd loc))
203
204 recordBreak :: BreakLocation -> GHCi (Bool{- was already present -}, Int)
205 recordBreak brkLoc = do
206 st <- getGHCiState
207 let oldActiveBreaks = breaks st
208 -- don't store the same break point twice
209 case [ nm | (nm, loc) <- oldActiveBreaks, loc == brkLoc ] of
210 (nm:_) -> return (True, nm)
211 [] -> do
212 let oldCounter = break_ctr st
213 newCounter = oldCounter + 1
214 setGHCiState $ st { break_ctr = newCounter,
215 breaks = (oldCounter, brkLoc) : oldActiveBreaks
216 }
217 return (False, oldCounter)
218
219 newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> Ghc a }
220
221 reflectGHCi :: (Session, IORef GHCiState) -> GHCi a -> IO a
222 reflectGHCi (s, gs) m = unGhc (unGHCi m gs) s
223
224 reifyGHCi :: ((Session, IORef GHCiState) -> IO a) -> GHCi a
225 reifyGHCi f = GHCi f'
226 where
227 -- f' :: IORef GHCiState -> Ghc a
228 f' gs = reifyGhc (f'' gs)
229 -- f'' :: IORef GHCiState -> Session -> IO a
230 f'' gs s = f (s, gs)
231
232 startGHCi :: GHCi a -> GHCiState -> Ghc a
233 startGHCi g state = do ref <- liftIO $ newIORef state; unGHCi g ref
234
235 instance Functor GHCi where
236 fmap = liftM
237
238 instance Applicative GHCi where
239 pure a = GHCi $ \_ -> pure a
240 (<*>) = ap
241
242 instance Monad GHCi where
243 (GHCi m) >>= k = GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
244
245 class HasGhciState m where
246 getGHCiState :: m GHCiState
247 setGHCiState :: GHCiState -> m ()
248 modifyGHCiState :: (GHCiState -> GHCiState) -> m ()
249
250 instance HasGhciState GHCi where
251 getGHCiState = GHCi $ \r -> liftIO $ readIORef r
252 setGHCiState s = GHCi $ \r -> liftIO $ writeIORef r s
253 modifyGHCiState f = GHCi $ \r -> liftIO $ modifyIORef r f
254
255 instance (MonadTrans t, Monad m, HasGhciState m) => HasGhciState (t m) where
256 getGHCiState = lift getGHCiState
257 setGHCiState = lift . setGHCiState
258 modifyGHCiState = lift . modifyGHCiState
259
260 liftGhc :: Ghc a -> GHCi a
261 liftGhc m = GHCi $ \_ -> m
262
263 instance MonadIO GHCi where
264 liftIO = liftGhc . liftIO
265
266 instance HasDynFlags GHCi where
267 getDynFlags = getSessionDynFlags
268
269 instance GhcMonad GHCi where
270 setSession s' = liftGhc $ setSession s'
271 getSession = liftGhc $ getSession
272
273 instance HasDynFlags (InputT GHCi) where
274 getDynFlags = lift getDynFlags
275
276 instance GhcMonad (InputT GHCi) where
277 setSession = lift . setSession
278 getSession = lift getSession
279
280 instance ExceptionMonad GHCi where
281 gcatch m h = GHCi $ \r -> unGHCi m r `gcatch` (\e -> unGHCi (h e) r)
282 gmask f =
283 GHCi $ \s -> gmask $ \io_restore ->
284 let
285 g_restore (GHCi m) = GHCi $ \s' -> io_restore (m s')
286 in
287 unGHCi (f g_restore) s
288
289 instance Haskeline.MonadException Ghc where
290 controlIO f = Ghc $ \s -> Haskeline.controlIO $ \(Haskeline.RunIO run) -> let
291 run' = Haskeline.RunIO (fmap (Ghc . const) . run . flip unGhc s)
292 in fmap (flip unGhc s) $ f run'
293
294 instance Haskeline.MonadException GHCi where
295 controlIO f = GHCi $ \s -> Haskeline.controlIO $ \(Haskeline.RunIO run) -> let
296 run' = Haskeline.RunIO (fmap (GHCi . const) . run . flip unGHCi s)
297 in fmap (flip unGHCi s) $ f run'
298
299 instance ExceptionMonad (InputT GHCi) where
300 gcatch = Haskeline.catch
301 gmask f = Haskeline.liftIOOp gmask (f . Haskeline.liftIOOp_)
302
303 isOptionSet :: GHCiOption -> GHCi Bool
304 isOptionSet opt
305 = do st <- getGHCiState
306 return (opt `elem` options st)
307
308 setOption :: GHCiOption -> GHCi ()
309 setOption opt
310 = do st <- getGHCiState
311 setGHCiState (st{ options = opt : filter (/= opt) (options st) })
312
313 unsetOption :: GHCiOption -> GHCi ()
314 unsetOption opt
315 = do st <- getGHCiState
316 setGHCiState (st{ options = filter (/= opt) (options st) })
317
318 printForUserNeverQualify :: GhcMonad m => SDoc -> m ()
319 printForUserNeverQualify doc = do
320 dflags <- getDynFlags
321 liftIO $ Outputable.printForUser dflags stdout neverQualify doc
322
323 printForUserModInfo :: GhcMonad m => GHC.ModuleInfo -> SDoc -> m ()
324 printForUserModInfo info doc = do
325 dflags <- getDynFlags
326 mUnqual <- GHC.mkPrintUnqualifiedForModule info
327 unqual <- maybe GHC.getPrintUnqual return mUnqual
328 liftIO $ Outputable.printForUser dflags stdout unqual doc
329
330 printForUser :: GhcMonad m => SDoc -> m ()
331 printForUser doc = do
332 unqual <- GHC.getPrintUnqual
333 dflags <- getDynFlags
334 liftIO $ Outputable.printForUser dflags stdout unqual doc
335
336 printForUserPartWay :: SDoc -> GHCi ()
337 printForUserPartWay doc = do
338 unqual <- GHC.getPrintUnqual
339 dflags <- getDynFlags
340 liftIO $ Outputable.printForUserPartWay dflags stdout (pprUserLength dflags) unqual doc
341
342 -- | Run a single Haskell expression
343 runStmt :: String -> GHC.SingleStep -> GHCi (Maybe GHC.ExecResult)
344 runStmt expr step = do
345 st <- getGHCiState
346 GHC.handleSourceError (\e -> do GHC.printException e; return Nothing) $ do
347 let opts = GHC.execOptions
348 { GHC.execSourceFile = progname st
349 , GHC.execLineNumber = line_number st
350 , GHC.execSingleStep = step
351 , GHC.execWrap = \fhv -> EvalApp (EvalThis (evalWrapper st))
352 (EvalThis fhv) }
353 Just <$> GHC.execStmt expr opts
354
355 runDecls :: String -> GHCi (Maybe [GHC.Name])
356 runDecls decls = do
357 st <- getGHCiState
358 reifyGHCi $ \x ->
359 withProgName (progname st) $
360 withArgs (args st) $
361 reflectGHCi x $ do
362 GHC.handleSourceError (\e -> do GHC.printException e;
363 return Nothing) $ do
364 r <- GHC.runDeclsWithLocation (progname st) (line_number st) decls
365 return (Just r)
366
367 resume :: (SrcSpan -> Bool) -> GHC.SingleStep -> GHCi GHC.ExecResult
368 resume canLogSpan step = do
369 st <- getGHCiState
370 reifyGHCi $ \x ->
371 withProgName (progname st) $
372 withArgs (args st) $
373 reflectGHCi x $ do
374 GHC.resumeExec canLogSpan step
375
376 -- --------------------------------------------------------------------------
377 -- timing & statistics
378
379 timeIt :: (a -> Maybe Integer) -> InputT GHCi a -> InputT GHCi a
380 timeIt getAllocs action
381 = do b <- lift $ isOptionSet ShowTiming
382 if not b
383 then action
384 else do time1 <- liftIO $ getCurrentTime
385 a <- action
386 let allocs = getAllocs a
387 time2 <- liftIO $ getCurrentTime
388 dflags <- getDynFlags
389 let period = time2 `diffUTCTime` time1
390 liftIO $ printTimes dflags allocs (realToFrac period)
391 return a
392
393 printTimes :: DynFlags -> Maybe Integer -> Double -> IO ()
394 printTimes dflags mallocs secs
395 = do let secs_str = showFFloat (Just 2) secs
396 putStrLn (showSDoc dflags (
397 parens (text (secs_str "") <+> text "secs" <> comma <+>
398 case mallocs of
399 Nothing -> empty
400 Just allocs ->
401 text (separateThousands allocs) <+> text "bytes")))
402 where
403 separateThousands n = reverse . sep . reverse . show $ n
404 where sep n'
405 | n' `lengthAtMost` 3 = n'
406 | otherwise = take 3 n' ++ "," ++ sep (drop 3 n')
407
408 -----------------------------------------------------------------------------
409 -- reverting CAFs
410
411 revertCAFs :: GHCi ()
412 revertCAFs = do
413 liftIO rts_revertCAFs
414 s <- getGHCiState
415 when (not (ghc_e s)) turnOffBuffering
416 -- Have to turn off buffering again, because we just
417 -- reverted stdout, stderr & stdin to their defaults.
418
419 foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
420 -- Make it "safe", just in case
421
422 -----------------------------------------------------------------------------
423 -- To flush buffers for the *interpreted* computation we need
424 -- to refer to *its* stdout/stderr handles
425
426 -- | Compile "hFlush stdout; hFlush stderr" once, so we can use it repeatedly
427 initInterpBuffering :: Ghc (ForeignHValue, ForeignHValue)
428 initInterpBuffering = do
429 nobuf <- compileGHCiExpr $
430 "do { System.IO.hSetBuffering System.IO.stdin System.IO.NoBuffering; " ++
431 " System.IO.hSetBuffering System.IO.stdout System.IO.NoBuffering; " ++
432 " System.IO.hSetBuffering System.IO.stderr System.IO.NoBuffering }"
433 flush <- compileGHCiExpr $
434 "do { System.IO.hFlush System.IO.stdout; " ++
435 " System.IO.hFlush System.IO.stderr }"
436 return (nobuf, flush)
437
438 -- | Invoke "hFlush stdout; hFlush stderr" in the interpreter
439 flushInterpBuffers :: GHCi ()
440 flushInterpBuffers = do
441 st <- getGHCiState
442 hsc_env <- GHC.getSession
443 liftIO $ evalIO hsc_env (flushStdHandles st)
444
445 -- | Turn off buffering for stdin, stdout, and stderr in the interpreter
446 turnOffBuffering :: GHCi ()
447 turnOffBuffering = do
448 st <- getGHCiState
449 turnOffBuffering_ (noBuffering st)
450
451 turnOffBuffering_ :: GhcMonad m => ForeignHValue -> m ()
452 turnOffBuffering_ fhv = do
453 hsc_env <- getSession
454 liftIO $ evalIO hsc_env fhv
455
456 mkEvalWrapper :: GhcMonad m => String -> [String] -> m ForeignHValue
457 mkEvalWrapper progname args =
458 compileGHCiExpr $
459 "\\m -> System.Environment.withProgName " ++ show progname ++
460 "(System.Environment.withArgs " ++ show args ++ " m)"
461
462 compileGHCiExpr :: GhcMonad m => String -> m ForeignHValue
463 compileGHCiExpr expr = do
464 hsc_env <- getSession
465 let dflags = hsc_dflags hsc_env
466 -- RebindableSyntax can wreak havoc with GHCi in several ways
467 -- (see #13385 and #14342 for examples), so we take care to disable it
468 -- for the duration of running expressions that are internal to GHCi.
469 no_rb_hsc_env =
470 hsc_env { hsc_dflags = xopt_unset dflags LangExt.RebindableSyntax }
471 setSession no_rb_hsc_env
472 res <- GHC.compileExprRemote expr
473 setSession hsc_env
474 pure res