root/compiler/main/InteractiveEval.hs

Revision 215c8265e72a7f2a8d57793d5a5dec4c0deed08a, 40.9 KB (checked in by Paolo Capriotti <p.capriotti@…>, 2 weeks ago)

Add a fixity environment to InteractiveContext? (#2947)

  • Property mode set to 100644
Line 
1-- -----------------------------------------------------------------------------
2--
3-- (c) The University of Glasgow, 2005-2007
4--
5-- Running statements interactively
6--
7-- -----------------------------------------------------------------------------
8
9module InteractiveEval (
10#ifdef GHCI
11        RunResult(..), Status(..), Resume(..), History(..),
12        runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
13        parseImportDecl, SingleStep(..),
14        resume,
15        abandon, abandonAll,
16        getResumeContext,
17        getHistorySpan,
18        getModBreaks,
19        getHistoryModule,
20        back, forward,
21        setContext, getContext,
22        availsToGlobalRdrEnv,
23        getNamesInScope,
24        getRdrNamesInScope,
25        moduleIsInterpreted,
26        getInfo,
27        exprType,
28        typeKind,
29        parseName,
30        showModule,
31        isModuleInterpreted,
32        compileExpr, dynCompileExpr,
33        Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
34#endif
35        ) where
36
37#ifdef GHCI
38
39#include "HsVersions.h"
40
41import GhcMonad
42import HscMain
43import HsSyn
44import HscTypes
45import InstEnv
46import Type     hiding( typeKind )
47import TcType           hiding( typeKind )
48import Var
49import Id
50import Name             hiding ( varName )
51import NameSet
52import Avail
53import RdrName
54import VarSet
55import VarEnv
56import ByteCodeInstr
57import Linker
58import DynFlags
59import Unique
60import UniqSupply
61import Module
62import Panic
63import UniqFM
64import Maybes
65import ErrUtils
66import SrcLoc
67import BreakArray
68import RtClosureInspect
69import Outputable
70import FastString
71import MonadUtils
72
73import System.Directory
74import Data.Dynamic
75import Data.List (find)
76import Control.Monad
77#if __GLASGOW_HASKELL__ >= 701
78import Foreign.Safe
79#else
80import Foreign hiding (unsafePerformIO)
81#endif
82import Foreign.C
83import GHC.Exts
84import Data.Array
85import Exception
86import Control.Concurrent
87import System.IO
88import System.IO.Unsafe
89
90-- -----------------------------------------------------------------------------
91-- running a statement interactively
92
93data RunResult
94  = RunOk [Name]                -- ^ names bound by this evaluation
95  | RunException SomeException  -- ^ statement raised an exception
96  | RunBreak ThreadId [Name] (Maybe BreakInfo)
97
98data Status
99   = Break Bool HValue BreakInfo ThreadId
100          -- ^ the computation hit a breakpoint (Bool <=> was an exception)
101   | Complete (Either SomeException [HValue])
102          -- ^ the computation completed with either an exception or a value
103
104data Resume
105   = Resume {
106       resumeStmt      :: String,       -- the original statement
107       resumeThreadId  :: ThreadId,     -- thread running the computation
108       resumeBreakMVar :: MVar (),
109       resumeStatMVar  :: MVar Status,
110       resumeBindings  :: ([TyThing], GlobalRdrEnv),
111       resumeFinalIds  :: [Id],         -- [Id] to bind on completion
112       resumeApStack   :: HValue,       -- The object from which we can get
113                                        -- value of the free variables.
114       resumeBreakInfo :: Maybe BreakInfo,
115                                        -- the breakpoint we stopped at
116                                        -- (Nothing <=> exception)
117       resumeSpan      :: SrcSpan,      -- just a cache, otherwise it's a pain
118                                        -- to fetch the ModDetails & ModBreaks
119                                        -- to get this.
120       resumeHistory   :: [History],
121       resumeHistoryIx :: Int           -- 0 <==> at the top of the history
122   }
123
124getResumeContext :: GhcMonad m => m [Resume]
125getResumeContext = withSession (return . ic_resume . hsc_IC)
126
127data SingleStep
128   = RunToCompletion
129   | SingleStep
130   | RunAndLogSteps
131
132isStep :: SingleStep -> Bool
133isStep RunToCompletion = False
134isStep _ = True
135
136data History
137   = History {
138        historyApStack   :: HValue,
139        historyBreakInfo :: BreakInfo,
140        historyEnclosingDecls :: [String]  -- declarations enclosing the breakpoint
141   }
142
143mkHistory :: HscEnv -> HValue -> BreakInfo -> History
144mkHistory hsc_env hval bi = let
145    decls = findEnclosingDecls hsc_env bi
146    in History hval bi decls
147
148
149getHistoryModule :: History -> Module
150getHistoryModule = breakInfo_module . historyBreakInfo
151
152getHistorySpan :: HscEnv -> History -> SrcSpan
153getHistorySpan hsc_env hist =
154   let inf = historyBreakInfo hist
155       num = breakInfo_number inf
156   in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
157       Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
158       _ -> panic "getHistorySpan"
159
160getModBreaks :: HomeModInfo -> ModBreaks
161getModBreaks hmi
162  | Just linkable <- hm_linkable hmi,
163    [BCOs _ modBreaks] <- linkableUnlinked linkable
164  = modBreaks
165  | otherwise
166  = emptyModBreaks -- probably object code
167
168{- | Finds the enclosing top level function name -}
169-- ToDo: a better way to do this would be to keep hold of the decl_path computed
170-- by the coverage pass, which gives the list of lexically-enclosing bindings
171-- for each tick.
172findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
173findEnclosingDecls hsc_env inf =
174   let hmi = expectJust "findEnclosingDecls" $
175             lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
176       mb = getModBreaks hmi
177   in modBreaks_decls mb ! breakInfo_number inf
178
179-- | Update fixity environment in the current interactive context.
180updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
181updateFixityEnv fix_env = do
182  hsc_env <- getSession
183  let ic = hsc_IC hsc_env
184  setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
185
186-- | Run a statement in the current interactive context.  Statement
187-- may bind multple values.
188runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
189runStmt = runStmtWithLocation "<interactive>" 1
190
191-- | Run a statement in the current interactive context.  Passing debug information
192--   Statement may bind multple values.
193runStmtWithLocation :: GhcMonad m => String -> Int ->
194                       String -> SingleStep -> m RunResult
195runStmtWithLocation source linenumber expr step =
196  do
197    hsc_env <- getSession
198
199    breakMVar  <- liftIO $ newEmptyMVar  -- wait on this when we hit a breakpoint
200    statusMVar <- liftIO $ newEmptyMVar  -- wait on this when a computation is running
201
202    -- Turn off -fwarn-unused-bindings when running a statement, to hide
203    -- warnings about the implicit bindings we introduce.
204    let ic       = hsc_IC hsc_env -- use the interactive dflags
205        idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedBinds
206        hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
207
208    -- compile to value (IO [HValue]), don't run
209    r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
210
211    case r of
212      -- empty statement / comment
213      Nothing -> return (RunOk [])
214
215      Just (tyThings, hval, fix_env) -> do
216        updateFixityEnv fix_env
217
218        status <-
219          withVirtualCWD $
220            withBreakAction (isStep step) idflags' breakMVar statusMVar $ do
221                liftIO $ sandboxIO idflags' statusMVar hval
222
223        let ic = hsc_IC hsc_env
224            bindings = (ic_tythings ic, ic_rn_gbl_env ic)
225
226        case step of
227          RunAndLogSteps ->
228              traceRunStatus expr bindings tyThings
229                             breakMVar statusMVar status emptyHistory
230          _other ->
231              handleRunStatus expr bindings tyThings
232                               breakMVar statusMVar status emptyHistory
233
234runDecls :: GhcMonad m => String -> m [Name]
235runDecls = runDeclsWithLocation "<interactive>" 1
236
237runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
238runDeclsWithLocation source linenumber expr =
239  do
240    hsc_env <- getSession
241    (tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
242
243    setSession $ hsc_env { hsc_IC = ic }
244    hsc_env <- getSession
245    hsc_env' <- liftIO $ rttiEnvironment hsc_env
246    modifySession (\_ -> hsc_env')
247    return (map getName tyThings)
248
249
250withVirtualCWD :: GhcMonad m => m a -> m a
251withVirtualCWD m = do
252  hsc_env <- getSession
253  let ic = hsc_IC hsc_env
254
255  let set_cwd = do
256        dir <- liftIO $ getCurrentDirectory
257        case ic_cwd ic of
258           Just dir -> liftIO $ setCurrentDirectory dir
259           Nothing  -> return ()
260        return dir
261
262      reset_cwd orig_dir = do
263        virt_dir <- liftIO $ getCurrentDirectory
264        hsc_env <- getSession
265        let old_IC = hsc_IC hsc_env
266        setSession hsc_env{  hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
267        liftIO $ setCurrentDirectory orig_dir
268
269  gbracket set_cwd reset_cwd $ \_ -> m
270
271parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
272parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
273
274emptyHistory :: BoundedList History
275emptyHistory = nilBL 50 -- keep a log of length 50
276
277handleRunStatus :: GhcMonad m =>
278                   String-> ([TyThing],GlobalRdrEnv) -> [Id]
279                -> MVar () -> MVar Status -> Status -> BoundedList History
280                -> m RunResult
281handleRunStatus expr bindings final_ids breakMVar statusMVar status
282                history =
283   case status of
284      -- did we hit a breakpoint or did we complete?
285      (Break is_exception apStack info tid) -> do
286        hsc_env <- getSession
287        let mb_info | is_exception = Nothing
288                    | otherwise    = Just info
289        (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
290                                                               mb_info
291        let
292            resume = Resume { resumeStmt = expr, resumeThreadId = tid
293                            , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
294                            , resumeBindings = bindings, resumeFinalIds = final_ids
295                            , resumeApStack = apStack, resumeBreakInfo = mb_info
296                            , resumeSpan = span, resumeHistory = toListBL history
297                            , resumeHistoryIx = 0 }
298            hsc_env2 = pushResume hsc_env1 resume
299        --
300        modifySession (\_ -> hsc_env2)
301        return (RunBreak tid names mb_info)
302      (Complete either_hvals) ->
303        case either_hvals of
304            Left e -> return (RunException e)
305            Right hvals -> do
306                hsc_env <- getSession
307                let final_ic = extendInteractiveContext (hsc_IC hsc_env)
308                                                        (map AnId final_ids)
309                    final_names = map getName final_ids
310                liftIO $ Linker.extendLinkEnv (zip final_names hvals)
311                hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
312                modifySession (\_ -> hsc_env')
313                return (RunOk final_names)
314
315traceRunStatus :: GhcMonad m =>
316                  String -> ([TyThing], GlobalRdrEnv) -> [Id]
317               -> MVar () -> MVar Status -> Status -> BoundedList History
318               -> m RunResult
319traceRunStatus expr bindings final_ids
320               breakMVar statusMVar status history = do
321  hsc_env <- getSession
322  case status of
323     -- when tracing, if we hit a breakpoint that is not explicitly
324     -- enabled, then we just log the event in the history and continue.
325     (Break is_exception apStack info tid) | not is_exception -> do
326        b <- liftIO $ isBreakEnabled hsc_env info
327        if b
328           then handle_normally
329           else do
330             let history' = mkHistory hsc_env apStack info `consBL` history
331                -- probably better make history strict here, otherwise
332                -- our BoundedList will be pointless.
333             _ <- liftIO $ evaluate history'
334             status <-
335                 withBreakAction True (hsc_dflags hsc_env)
336                                      breakMVar statusMVar $ do
337                   liftIO $ withInterruptsSentTo tid $ do
338                       putMVar breakMVar ()  -- awaken the stopped thread
339                       takeMVar statusMVar   -- and wait for the result
340             traceRunStatus expr bindings final_ids
341                            breakMVar statusMVar status history'
342     _other ->
343        handle_normally
344  where
345        handle_normally = handleRunStatus expr bindings final_ids
346                                          breakMVar statusMVar status history
347
348
349isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
350isBreakEnabled hsc_env inf =
351   case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
352       Just hmi -> do
353         w <- getBreak (modBreaks_flags (getModBreaks hmi))
354                       (breakInfo_number inf)
355         case w of Just n -> return (n /= 0); _other -> return False
356       _ ->
357         return False
358
359
360foreign import ccall "&rts_stop_next_breakpoint" stepFlag      :: Ptr CInt
361foreign import ccall "&rts_stop_on_exception"    exceptionFlag :: Ptr CInt
362
363setStepFlag :: IO ()
364setStepFlag = poke stepFlag 1
365resetStepFlag :: IO ()
366resetStepFlag = poke stepFlag 0
367
368-- this points to the IO action that is executed when a breakpoint is hit
369foreign import ccall "&rts_breakpoint_io_action"
370   breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
371
372-- When running a computation, we redirect ^C exceptions to the running
373-- thread.  ToDo: we might want a way to continue even if the target
374-- thread doesn't die when it receives the exception... "this thread
375-- is not responding".
376--
377-- Careful here: there may be ^C exceptions flying around, so we start the new
378-- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
379-- only while we execute the user's code.  We can't afford to lose the final
380-- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
381sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
382sandboxIO dflags statusMVar thing =
383   mask $ \restore -> -- fork starts blocked
384     let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
385     in if dopt Opt_GhciSandbox dflags
386        then do tid <- forkIO $ do res <- runIt
387                                   putMVar statusMVar res -- empty: can't block
388                withInterruptsSentTo tid $ takeMVar statusMVar
389        else -- GLUT on OS X needs to run on the main thread. If you
390             -- try to use it from another thread then you just get a
391             -- white rectangle rendered. For this, or anything else
392             -- with such restrictions, you can turn the GHCi sandbox off
393             -- and things will be run in the main thread.
394             runIt
395
396-- We want to turn ^C into a break when -fbreak-on-exception is on,
397-- but it's an async exception and we only break for sync exceptions.
398-- Idea: if we catch and re-throw it, then the re-throw will trigger
399-- a break.  Great - but we don't want to re-throw all exceptions, because
400-- then we'll get a double break for ordinary sync exceptions (you'd have
401-- to :continue twice, which looks strange).  So if the exception is
402-- not "Interrupted", we unset the exception flag before throwing.
403--
404rethrow :: DynFlags -> IO a -> IO a
405rethrow dflags io = Exception.catch io $ \se -> do
406                   -- If -fbreak-on-error, we break unconditionally,
407                   --  but with care of not breaking twice
408                if dopt Opt_BreakOnError dflags &&
409                   not (dopt Opt_BreakOnException dflags)
410                    then poke exceptionFlag 1
411                    else case fromException se of
412                         -- If it is a "UserInterrupt" exception, we allow
413                         --  a possible break by way of -fbreak-on-exception
414                         Just UserInterrupt -> return ()
415                         -- In any other case, we don't want to break
416                         _ -> poke exceptionFlag 0
417
418                Exception.throwIO se
419
420withInterruptsSentTo :: ThreadId -> IO r -> IO r
421withInterruptsSentTo thread get_result = do
422  bracket (pushInterruptTargetThread thread)
423          (\_ -> popInterruptTargetThread)
424          (\_ -> get_result)
425
426-- This function sets up the interpreter for catching breakpoints, and
427-- resets everything when the computation has stopped running.  This
428-- is a not-very-good way to ensure that only the interactive
429-- evaluation should generate breakpoints.
430withBreakAction :: (ExceptionMonad m, MonadIO m) =>
431                   Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
432withBreakAction step dflags breakMVar statusMVar act
433 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
434 where
435   setBreakAction = do
436     stablePtr <- newStablePtr onBreak
437     poke breakPointIOAction stablePtr
438     when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
439     when step $ setStepFlag
440     return stablePtr
441        -- Breaking on exceptions is not enabled by default, since it
442        -- might be a bit surprising.  The exception flag is turned off
443        -- as soon as it is hit, or in resetBreakAction below.
444
445   onBreak is_exception info apStack = do
446     tid <- myThreadId
447     putMVar statusMVar (Break is_exception apStack info tid)
448     takeMVar breakMVar
449
450   resetBreakAction stablePtr = do
451     poke breakPointIOAction noBreakStablePtr
452     poke exceptionFlag 0
453     resetStepFlag
454     freeStablePtr stablePtr
455
456noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
457noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
458
459noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
460noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
461noBreakAction True  _ _ = return () -- exception: just continue
462
463resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
464resume canLogSpan step
465 = do
466   hsc_env <- getSession
467   let ic = hsc_IC hsc_env
468       resume = ic_resume ic
469
470   case resume of
471     [] -> ghcError (ProgramError "not stopped at a breakpoint")
472     (r:rs) -> do
473        -- unbind the temporary locals by restoring the TypeEnv from
474        -- before the breakpoint, and drop this Resume from the
475        -- InteractiveContext.
476        let (resume_tmp_te,resume_rdr_env) = resumeBindings r
477            ic' = ic { ic_tythings = resume_tmp_te,
478                       ic_rn_gbl_env = resume_rdr_env,
479                       ic_resume   = rs }
480        modifySession (\_ -> hsc_env{ hsc_IC = ic' })
481
482        -- remove any bindings created since the breakpoint from the
483        -- linker's environment
484        let new_names = map getName (filter (`notElem` resume_tmp_te)
485                                           (ic_tythings ic))
486        liftIO $ Linker.deleteFromLinkEnv new_names
487
488        when (isStep step) $ liftIO setStepFlag
489        case r of
490          Resume { resumeStmt = expr, resumeThreadId = tid
491                 , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
492                 , resumeBindings = bindings, resumeFinalIds = final_ids
493                 , resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
494                 , resumeHistory = hist } -> do
495               withVirtualCWD $ do
496                withBreakAction (isStep step) (hsc_dflags hsc_env)
497                                        breakMVar statusMVar $ do
498                status <- liftIO $ withInterruptsSentTo tid $ do
499                             putMVar breakMVar ()
500                                      -- this awakens the stopped thread...
501                             takeMVar statusMVar
502                                      -- and wait for the result
503                let prevHistoryLst = fromListBL 50 hist
504                    hist' = case info of
505                       Nothing -> prevHistoryLst
506                       Just i
507                         | not $canLogSpan span -> prevHistoryLst
508                         | otherwise -> mkHistory hsc_env apStack i `consBL`
509                                                        fromListBL 50 hist
510                case step of
511                  RunAndLogSteps ->
512                        traceRunStatus expr bindings final_ids
513                                       breakMVar statusMVar status hist'
514                  _other ->
515                        handleRunStatus expr bindings final_ids
516                                        breakMVar statusMVar status hist'
517
518back :: GhcMonad m => m ([Name], Int, SrcSpan)
519back  = moveHist (+1)
520
521forward :: GhcMonad m => m ([Name], Int, SrcSpan)
522forward  = moveHist (subtract 1)
523
524moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
525moveHist fn = do
526  hsc_env <- getSession
527  case ic_resume (hsc_IC hsc_env) of
528     [] -> ghcError (ProgramError "not stopped at a breakpoint")
529     (r:rs) -> do
530        let ix = resumeHistoryIx r
531            history = resumeHistory r
532            new_ix = fn ix
533        --
534        when (new_ix > length history) $
535           ghcError (ProgramError "no more logged breakpoints")
536        when (new_ix < 0) $
537           ghcError (ProgramError "already at the beginning of the history")
538
539        let
540          update_ic apStack mb_info = do
541            (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
542                                                apStack mb_info
543            let ic = hsc_IC hsc_env1
544                r' = r { resumeHistoryIx = new_ix }
545                ic' = ic { ic_resume = r':rs }
546
547            modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
548
549            return (names, new_ix, span)
550
551        -- careful: we want apStack to be the AP_STACK itself, not a thunk
552        -- around it, hence the cases are carefully constructed below to
553        -- make this the case.  ToDo: this is v. fragile, do something better.
554        if new_ix == 0
555           then case r of
556                   Resume { resumeApStack = apStack,
557                            resumeBreakInfo = mb_info } ->
558                          update_ic apStack mb_info
559           else case history !! (new_ix - 1) of
560                   History apStack info _ ->
561                          update_ic apStack (Just info)
562
563-- -----------------------------------------------------------------------------
564-- After stopping at a breakpoint, add free variables to the environment
565result_fs :: FastString
566result_fs = fsLit "_result"
567
568bindLocalsAtBreakpoint
569        :: HscEnv
570        -> HValue
571        -> Maybe BreakInfo
572        -> IO (HscEnv, [Name], SrcSpan)
573
574-- Nothing case: we stopped when an exception was raised, not at a
575-- breakpoint.  We have no location information or local variables to
576-- bind, all we can do is bind a local variable to the exception
577-- value.
578bindLocalsAtBreakpoint hsc_env apStack Nothing = do
579   let exn_fs    = fsLit "_exception"
580       exn_name  = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
581       e_fs      = fsLit "e"
582       e_name    = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
583       e_tyvar   = mkRuntimeUnkTyVar e_name liftedTypeKind
584       exn_id    = AnId $ Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
585
586       ictxt0 = hsc_IC hsc_env
587       ictxt1 = extendInteractiveContext ictxt0 [exn_id]
588
589       span = mkGeneralSrcSpan (fsLit "<exception thrown>")
590   --
591   Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
592   return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
593
594-- Just case: we stopped at a breakpoint, we have information about the location
595-- of the breakpoint and the free variables of the expression.
596bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
597
598   let
599       mod_name  = moduleName (breakInfo_module info)
600       hmi       = expectJust "bindLocalsAtBreakpoint" $
601                        lookupUFM (hsc_HPT hsc_env) mod_name
602       breaks    = getModBreaks hmi
603       index     = breakInfo_number info
604       vars      = breakInfo_vars info
605       result_ty = breakInfo_resty info
606       occs      = modBreaks_vars breaks ! index
607       span      = modBreaks_locs breaks ! index
608
609           -- Filter out any unboxed ids;
610           -- we can't bind these at the prompt
611       pointers = filter (\(id,_) -> isPointer id) vars
612       isPointer id | PtrRep <- idPrimRep id = True
613                    | otherwise              = False
614
615       (ids, offsets) = unzip pointers
616
617       free_tvs = foldr (unionVarSet . tyVarsOfType . idType)
618                        (tyVarsOfType result_ty) ids
619
620   -- It might be that getIdValFromApStack fails, because the AP_STACK
621   -- has been accidentally evaluated, or something else has gone wrong.
622   -- So that we don't fall over in a heap when this happens, just don't
623   -- bind any free variables instead, and we emit a warning.
624   mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
625   let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
626   when (any isNothing mb_hValues) $
627      debugTraceMsg (hsc_dflags hsc_env) 1 $
628          text "Warning: _result has been evaluated, some bindings have been lost"
629
630   us <- mkSplitUniqSupply 'I'
631   let (us1, us2) = splitUniqSupply us
632       tv_subst   = newTyVars us1 free_tvs
633       new_ids    = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
634       names      = map idName new_ids
635
636   -- make an Id for _result.  We use the Unique of the FastString "_result";
637   -- we don't care about uniqueness here, because there will only be one
638   -- _result in scope at any time.
639   let result_name = mkInternalName (getUnique result_fs)
640                          (mkVarOccFS result_fs) span
641       result_id   = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
642
643   -- for each Id we're about to bind in the local envt:
644   --    - tidy the type variables
645   --    - globalise the Id (Ids are supposed to be Global, apparently).
646   --
647   let result_ok = isPointer result_id
648                    && not (isUnboxedTupleType (idType result_id))
649
650       all_ids | result_ok = result_id : new_ids
651               | otherwise = new_ids
652       id_tys = map idType all_ids
653       (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
654       final_ids = zipWith setIdType all_ids tidy_tys
655       ictxt0 = hsc_IC hsc_env
656       ictxt1 = extendInteractiveContext ictxt0 (map AnId final_ids)
657
658   Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
659   when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
660   hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
661   return (hsc_env1, if result_ok then result_name:names else names, span)
662  where
663        -- We need a fresh Unique for each Id we bind, because the linker
664        -- state is single-threaded and otherwise we'd spam old bindings
665        -- whenever we stop at a breakpoint.  The InteractveContext is properly
666        -- saved/restored, but not the linker state.  See #1743, test break026.
667   mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
668   mkNewId tv_subst occ id uniq
669     = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
670     where
671         loc    = nameSrcSpan (idName id)
672         name   = mkInternalName uniq occ loc
673         ty     = substTy tv_subst (idType id)
674
675   newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
676     -- Similarly, clone the type variables mentioned in the types
677     -- we have here, *and* make them all RuntimeUnk tyars
678   newTyVars us tvs
679     = mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
680                    | (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
681                    , let name = setNameUnique (tyVarName tv) uniq ]
682
683rttiEnvironment :: HscEnv -> IO HscEnv
684rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
685   let tmp_ids = [id | AnId id <- ic_tythings ic]
686       incompletelyTypedIds =
687           [id | id <- tmp_ids
688               , not $ noSkolems id
689               , (occNameFS.nameOccName.idName) id /= result_fs]
690   hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
691   return hsc_env'
692    where
693     noSkolems = isEmptyVarSet . tyVarsOfType . idType
694     improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
695      let tmp_ids = [id | AnId id <- ic_tythings ic]
696          Just id = find (\i -> idName i == name) tmp_ids
697      if noSkolems id
698         then return hsc_env
699         else do
700           mb_new_ty <- reconstructType hsc_env 10 id
701           let old_ty = idType id
702           case mb_new_ty of
703             Nothing -> return hsc_env
704             Just new_ty -> do
705              case improveRTTIType hsc_env old_ty new_ty of
706               Nothing -> return $
707                        WARN(True, text (":print failed to calculate the "
708                                           ++ "improvement for a type")) hsc_env
709               Just subst -> do
710                 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
711                      printForUser stderr alwaysQualify $
712                      fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
713
714                 let ic' = extendInteractiveContext
715                               (substInteractiveContext ic subst) []
716                 return hsc_env{hsc_IC=ic'}
717
718getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
719getIdValFromApStack apStack (I# stackDepth) = do
720   case getApStackVal# apStack (stackDepth +# 1#) of
721                                -- The +1 is magic!  I don't know where it comes
722                                -- from, but this makes things line up.  --SDM
723        (# ok, result #) ->
724            case ok of
725              0# -> return Nothing -- AP_STACK not found
726              _  -> return (Just (unsafeCoerce# result))
727
728pushResume :: HscEnv -> Resume -> HscEnv
729pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
730  where
731        ictxt0 = hsc_IC hsc_env
732        ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
733
734-- -----------------------------------------------------------------------------
735-- Abandoning a resume context
736
737abandon :: GhcMonad m => m Bool
738abandon = do
739   hsc_env <- getSession
740   let ic = hsc_IC hsc_env
741       resume = ic_resume ic
742   case resume of
743      []    -> return False
744      r:rs  -> do
745         modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
746         liftIO $ abandon_ r
747         return True
748
749abandonAll :: GhcMonad m => m Bool
750abandonAll = do
751   hsc_env <- getSession
752   let ic = hsc_IC hsc_env
753       resume = ic_resume ic
754   case resume of
755      []  -> return False
756      rs  -> do
757         modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
758         liftIO $ mapM_ abandon_ rs
759         return True
760
761-- when abandoning a computation we have to
762--      (a) kill the thread with an async exception, so that the
763--          computation itself is stopped, and
764--      (b) fill in the MVar.  This step is necessary because any
765--          thunks that were under evaluation will now be updated
766--          with the partial computation, which still ends in takeMVar,
767--          so any attempt to evaluate one of these thunks will block
768--          unless we fill in the MVar.
769--      (c) wait for the thread to terminate by taking its status MVar.  This
770--          step is necessary to prevent race conditions with
771--          -fbreak-on-exception (see #5975).
772--  See test break010.
773abandon_ :: Resume -> IO ()
774abandon_ r = do
775  killThread (resumeThreadId r)
776  putMVar (resumeBreakMVar r) ()
777  _ <- takeMVar (resumeStatMVar r)
778  return ()
779
780-- -----------------------------------------------------------------------------
781-- Bounded list, optimised for repeated cons
782
783data BoundedList a = BL
784                        {-# UNPACK #-} !Int  -- length
785                        {-# UNPACK #-} !Int  -- bound
786                        [a] -- left
787                        [a] -- right,  list is (left ++ reverse right)
788
789nilBL :: Int -> BoundedList a
790nilBL bound = BL 0 bound [] []
791
792consBL :: a -> BoundedList a -> BoundedList a
793consBL a (BL len bound left right)
794  | len < bound = BL (len+1) bound (a:left) right
795  | null right  = BL len     bound [a]      $! tail (reverse left)
796  | otherwise   = BL len     bound (a:left) $! tail right
797
798toListBL :: BoundedList a -> [a]
799toListBL (BL _ _ left right) = left ++ reverse right
800
801fromListBL :: Int -> [a] -> BoundedList a
802fromListBL bound l = BL (length l) bound l []
803
804-- lenBL (BL len _ _ _) = len
805
806-- -----------------------------------------------------------------------------
807-- | Set the interactive evaluation context.
808--
809-- Setting the context doesn't throw away any bindings; the bindings
810-- we've built up in the InteractiveContext simply move to the new
811-- module.  They always shadow anything in scope in the current context.
812setContext :: GhcMonad m => [InteractiveImport] -> m ()
813setContext imports
814  = do { hsc_env <- getSession
815       ; all_env <- liftIO $ findGlobalRdrEnv hsc_env imports
816       ; let old_ic        = hsc_IC hsc_env
817             final_rdr_env = ic_tythings old_ic `icPlusGblRdrEnv` all_env
818       ; modifySession $ \_ ->
819         hsc_env{ hsc_IC = old_ic { ic_imports    = imports
820                                  , ic_rn_gbl_env = final_rdr_env }}}
821
822findGlobalRdrEnv :: HscEnv -> [InteractiveImport] -> IO GlobalRdrEnv
823-- Compute the GlobalRdrEnv for the interactive context
824findGlobalRdrEnv hsc_env imports
825  = do { idecls_env <- hscRnImportDecls hsc_env idecls
826                    -- This call also loads any orphan modules
827       ; imods_env  <- mapM (mkTopLevEnv (hsc_HPT hsc_env)) imods
828       ; return (foldr plusGlobalRdrEnv idecls_env imods_env) }
829  where
830    idecls :: [LImportDecl RdrName]
831    idecls = [noLoc d | IIDecl d <- imports]
832
833    imods :: [ModuleName]
834    imods = [m | IIModule m <- imports]
835
836availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
837availsToGlobalRdrEnv mod_name avails
838  = mkGlobalRdrEnv (gresFromAvails imp_prov avails)
839  where
840      -- We're building a GlobalRdrEnv as if the user imported
841      -- all the specified modules into the global interactive module
842    imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
843    decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
844                         is_qual = False,
845                         is_dloc = srcLocSpan interactiveSrcLoc }
846
847mkTopLevEnv :: HomePackageTable -> ModuleName -> IO GlobalRdrEnv
848mkTopLevEnv hpt modl
849  = case lookupUFM hpt modl of
850      Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
851                                                showSDoc (ppr modl)))
852      Just details ->
853         case mi_globals (hm_iface details) of
854                Nothing  ->
855                   ghcError (ProgramError ("mkTopLevEnv: not interpreted "
856                                                ++ showSDoc (ppr modl)))
857                Just env -> return env
858
859-- | Get the interactive evaluation context, consisting of a pair of the
860-- set of modules from which we take the full top-level scope, and the set
861-- of modules from which we take just the exports respectively.
862getContext :: GhcMonad m => m [InteractiveImport]
863getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
864             return (ic_imports ic)
865
866-- | Returns @True@ if the specified module is interpreted, and hence has
867-- its full top-level scope available.
868moduleIsInterpreted :: GhcMonad m => Module -> m Bool
869moduleIsInterpreted modl = withSession $ \h ->
870 if modulePackageId modl /= thisPackage (hsc_dflags h)
871        then return False
872        else case lookupUFM (hsc_HPT h) (moduleName modl) of
873                Just details       -> return (isJust (mi_globals (hm_iface details)))
874                _not_a_home_module -> return False
875
876-- | Looks up an identifier in the current interactive context (for :info)
877-- Filter the instances by the ones whose tycons (or clases resp)
878-- are in scope (qualified or otherwise).  Otherwise we list a whole lot too many!
879-- The exact choice of which ones to show, and which to hide, is a judgement call.
880--      (see Trac #1581)
881getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[ClsInst]))
882getInfo name
883  = withSession $ \hsc_env ->
884    do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
885       case mb_stuff of
886         Nothing -> return Nothing
887         Just (thing, fixity, ispecs) -> do
888           let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
889           return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
890  where
891    plausible rdr_env ispec     -- Dfun involving only names that are in ic_rn_glb_env
892        = all ok $ nameSetToList $ orphNamesOfType $ idType $ instanceDFunId ispec
893        where   -- A name is ok if it's in the rdr_env,
894                -- whether qualified or not
895          ok n | n == name         = True       -- The one we looked for in the first place!
896               | isBuiltInSyntax n = True
897               | isExternalName n  = any ((== n) . gre_name)
898                                         (lookupGRE_Name rdr_env n)
899               | otherwise         = True
900
901-- | Returns all names in scope in the current interactive context
902getNamesInScope :: GhcMonad m => m [Name]
903getNamesInScope = withSession $ \hsc_env -> do
904  return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
905
906getRdrNamesInScope :: GhcMonad m => m [RdrName]
907getRdrNamesInScope = withSession $ \hsc_env -> do
908  let
909      ic = hsc_IC hsc_env
910      gbl_rdrenv = ic_rn_gbl_env ic
911      gbl_names = concatMap greToRdrNames $ globalRdrEnvElts gbl_rdrenv
912  return gbl_names
913
914
915-- ToDo: move to RdrName
916greToRdrNames :: GlobalRdrElt -> [RdrName]
917greToRdrNames GRE{ gre_name = name, gre_prov = prov }
918  = case prov of
919     LocalDef -> [unqual]
920     Imported specs -> concat (map do_spec (map is_decl specs))
921  where
922    occ = nameOccName name
923    unqual = Unqual occ
924    do_spec decl_spec
925        | is_qual decl_spec = [qual]
926        | otherwise         = [unqual,qual]
927        where qual = Qual (is_as decl_spec) occ
928
929-- | Parses a string as an identifier, and returns the list of 'Name's that
930-- the identifier can refer to in the current interactive context.
931parseName :: GhcMonad m => String -> m [Name]
932parseName str = withSession $ \hsc_env -> do
933   (L _ rdr_name) <- liftIO $ hscParseIdentifier hsc_env str
934   liftIO $ hscTcRnLookupRdrName hsc_env rdr_name
935
936-- -----------------------------------------------------------------------------
937-- Getting the type of an expression
938
939-- | Get the type of an expression
940exprType :: GhcMonad m => String -> m Type
941exprType expr = withSession $ \hsc_env -> do
942   ty <- liftIO $ hscTcExpr hsc_env expr
943   return $ tidyType emptyTidyEnv ty
944
945-- -----------------------------------------------------------------------------
946-- Getting the kind of a type
947
948-- | Get the kind of a  type
949typeKind  :: GhcMonad m => Bool -> String -> m (Type, Kind)
950typeKind normalise str = withSession $ \hsc_env -> do
951   liftIO $ hscKcType hsc_env normalise str
952
953-----------------------------------------------------------------------------
954-- Compile an expression, run it and deliver the resulting HValue
955
956compileExpr :: GhcMonad m => String -> m HValue
957compileExpr expr = withSession $ \hsc_env -> do
958  Just (ids, hval, fix_env) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
959  updateFixityEnv fix_env
960  hvals <- liftIO hval
961  case (ids,hvals) of
962    ([_],[hv]) -> return hv
963    _          -> panic "compileExpr"
964
965-- -----------------------------------------------------------------------------
966-- Compile an expression, run it and return the result as a dynamic
967
968dynCompileExpr :: GhcMonad m => String -> m Dynamic
969dynCompileExpr expr = do
970    iis <- getContext
971    let importDecl = ImportDecl {
972                         ideclName = noLoc (mkModuleName "Data.Dynamic"),
973                         ideclPkgQual = Nothing,
974                         ideclSource = False,
975                         ideclSafe = False,
976                         ideclQualified = True,
977                         ideclImplicit = False,
978                         ideclAs = Nothing,
979                         ideclHiding = Nothing
980                     }
981    setContext (IIDecl importDecl : iis)
982    let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
983    Just (ids, hvals, fix_env) <- withSession $ \hsc_env ->
984                           liftIO $ hscStmt hsc_env stmt
985    setContext iis
986    updateFixityEnv fix_env
987
988    vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
989    case (ids,vals) of
990        (_:[], v:[]) -> return v
991        _            -> panic "dynCompileExpr"
992
993-----------------------------------------------------------------------------
994-- show a module and it's source/object filenames
995
996showModule :: GhcMonad m => ModSummary -> m String
997showModule mod_summary =
998    withSession $ \hsc_env -> do
999        interpreted <- isModuleInterpreted mod_summary
1000        return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
1001
1002isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
1003isModuleInterpreted mod_summary = withSession $ \hsc_env ->
1004  case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
1005        Nothing       -> panic "missing linkable"
1006        Just mod_info -> return (not obj_linkable)
1007                      where
1008                         obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
1009
1010----------------------------------------------------------------------------
1011-- RTTI primitives
1012
1013obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
1014obtainTermFromVal hsc_env bound force ty x =
1015              cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
1016
1017obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
1018obtainTermFromId hsc_env bound force id =  do
1019              hv <- Linker.getHValue hsc_env (varName id)
1020              cvObtainTerm hsc_env bound force (idType id) hv
1021
1022-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
1023reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
1024reconstructType hsc_env bound id = do
1025              hv <- Linker.getHValue hsc_env (varName id)
1026              cvReconstructType hsc_env bound (idType id) hv
1027
1028mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
1029mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
1030#endif /* GHCI */
Note: See TracBrowser for help on using the browser.