1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005-2007
5 -- Running statements interactively
7 -- -----------------------------------------------------------------------------
9 module InteractiveEval (
11 RunResult(..), Status(..), Resume(..), History(..),
12 runStmt, SingleStep(..),
20 setContext, getContext,
21 nameSetToGlobalRdrEnv,
31 compileExpr, dynCompileExpr,
33 Term(..), obtainTermFromId, obtainTermFromVal, reconstructType,
34 skolemiseSubst, skolemiseTy
40 #include "HsVersions.h"
42 import HscMain hiding (compileExpr)
45 import Type hiding (typeKind)
46 import TcType hiding (typeKind)
50 import Name hiding ( varName )
68 import RtClosureInspect
75 import Data.List (find)
82 import Control.Concurrent
83 import Data.List (sortBy)
84 import Foreign.StablePtr
87 -- -----------------------------------------------------------------------------
88 -- running a statement interactively
91 = RunOk [Name] -- ^ names bound by this evaluation
92 | RunFailed -- ^ statement failed compilation
93 | RunException SomeException -- ^ statement raised an exception
94 | RunBreak ThreadId [Name] (Maybe BreakInfo)
97 = Break Bool HValue BreakInfo ThreadId
98 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
99 | Complete (Either SomeException [HValue])
100 -- ^ the computation completed with either an exception or a value
104 resumeStmt :: String, -- the original statement
105 resumeThreadId :: ThreadId, -- thread running the computation
106 resumeBreakMVar :: MVar (),
107 resumeStatMVar :: MVar Status,
108 resumeBindings :: ([Id], TyVarSet),
109 resumeFinalIds :: [Id], -- [Id] to bind on completion
110 resumeApStack :: HValue, -- The object from which we can get
111 -- value of the free variables.
112 resumeBreakInfo :: Maybe BreakInfo,
113 -- the breakpoint we stopped at
114 -- (Nothing <=> exception)
115 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
116 -- to fetch the ModDetails & ModBreaks
118 resumeHistory :: [History],
119 resumeHistoryIx :: Int -- 0 <==> at the top of the history
122 getResumeContext :: GhcMonad m => m [Resume]
123 getResumeContext = withSession (return . ic_resume . hsc_IC)
130 isStep :: SingleStep -> Bool
131 isStep RunToCompletion = False
136 historyApStack :: HValue,
137 historyBreakInfo :: BreakInfo,
138 historyEnclosingDecl :: Id
139 -- ^^ A cache of the enclosing top level declaration, for convenience
142 mkHistory :: HscEnv -> HValue -> BreakInfo -> History
143 mkHistory hsc_env hval bi = let
144 h = History hval bi decl
145 decl = findEnclosingDecl hsc_env (getHistoryModule h)
146 (getHistorySpan hsc_env h)
149 getHistoryModule :: History -> Module
150 getHistoryModule = breakInfo_module . historyBreakInfo
152 getHistorySpan :: HscEnv -> History -> SrcSpan
153 getHistorySpan 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"
160 getModBreaks :: HomeModInfo -> ModBreaks
162 | Just linkable <- hm_linkable hmi,
163 [BCOs _ modBreaks] <- linkableUnlinked linkable
166 = emptyModBreaks -- probably object code
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
172 findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
173 findEnclosingDecl hsc_env mod span =
174 case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
175 Nothing -> panic "findEnclosingDecl"
177 globals = typeEnvIds (md_types (hm_details hmi))
179 find (\id -> let n = idName id in
180 nameSrcSpan n < span && isExternalName n)
181 (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
185 -- | Run a statement in the current interactive context. Statement
186 -- may bind multple values.
187 runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
190 hsc_env <- getSession
192 breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
193 statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
195 -- Turn off -fwarn-unused-bindings when running a statement, to hide
196 -- warnings about the implicit bindings we introduce.
197 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
198 hsc_env' = hsc_env{ hsc_dflags = dflags' }
200 r <- hscStmt hsc_env' expr
203 Nothing -> return RunFailed -- empty statement / comment
205 Just (ids, hval) -> do
206 -- XXX: This is the only place we can print warnings before the
207 -- result. Is this really the right thing to do? It's fine for
208 -- GHCi, but what's correct for other GHC API clients? We could
209 -- introduce a callback argument.
211 liftIO $ printBagOfWarnings dflags' warns
215 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
216 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
217 liftIO $ sandboxIO dflags' statusMVar thing_to_run
219 let ic = hsc_IC hsc_env
220 bindings = (ic_tmp_ids ic, ic_tyvars ic)
224 traceRunStatus expr bindings ids
225 breakMVar statusMVar status emptyHistory
227 handleRunStatus expr bindings ids
228 breakMVar statusMVar status emptyHistory
230 emptyHistory :: BoundedList History
231 emptyHistory = nilBL 50 -- keep a log of length 50
233 handleRunStatus :: GhcMonad m =>
234 String-> ([Id], TyVarSet) -> [Id]
235 -> MVar () -> MVar Status -> Status -> BoundedList History
237 handleRunStatus expr bindings final_ids breakMVar statusMVar status
240 -- did we hit a breakpoint or did we complete?
241 (Break is_exception apStack info tid) -> do
242 hsc_env <- getSession
243 let mb_info | is_exception = Nothing
244 | otherwise = Just info
245 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
248 resume = Resume expr tid breakMVar statusMVar
249 bindings final_ids apStack mb_info span
251 hsc_env2 = pushResume hsc_env1 resume
253 modifySession (\_ -> hsc_env2)
254 return (RunBreak tid names mb_info)
255 (Complete either_hvals) ->
257 Left e -> return (RunException e)
259 hsc_env <- getSession
260 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
261 final_ids emptyVarSet
262 -- the bound Ids never have any free TyVars
263 final_names = map idName final_ids
264 liftIO $ Linker.extendLinkEnv (zip final_names hvals)
265 hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
266 modifySession (\_ -> hsc_env')
267 return (RunOk final_names)
269 traceRunStatus :: GhcMonad m =>
270 String -> ([Id], TyVarSet) -> [Id]
271 -> MVar () -> MVar Status -> Status -> BoundedList History
273 traceRunStatus expr bindings final_ids
274 breakMVar statusMVar status history = do
275 hsc_env <- getSession
277 -- when tracing, if we hit a breakpoint that is not explicitly
278 -- enabled, then we just log the event in the history and continue.
279 (Break is_exception apStack info tid) | not is_exception -> do
280 b <- liftIO $ isBreakEnabled hsc_env info
284 let history' = mkHistory hsc_env apStack info `consBL` history
285 -- probably better make history strict here, otherwise
286 -- our BoundedList will be pointless.
287 liftIO $ evaluate history'
289 withBreakAction True (hsc_dflags hsc_env)
290 breakMVar statusMVar $ do
291 liftIO $ withInterruptsSentTo tid $ do
292 putMVar breakMVar () -- awaken the stopped thread
293 takeMVar statusMVar -- and wait for the result
294 traceRunStatus expr bindings final_ids
295 breakMVar statusMVar status history'
299 handle_normally = handleRunStatus expr bindings final_ids
300 breakMVar statusMVar status history
303 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
304 isBreakEnabled hsc_env inf =
305 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
307 w <- getBreak (modBreaks_flags (getModBreaks hmi))
308 (breakInfo_number inf)
309 case w of Just n -> return (n /= 0); _other -> return False
314 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
315 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
318 setStepFlag = poke stepFlag 1
319 resetStepFlag :: IO ()
320 resetStepFlag = poke stepFlag 0
322 -- this points to the IO action that is executed when a breakpoint is hit
323 foreign import ccall "&rts_breakpoint_io_action"
324 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
326 -- When running a computation, we redirect ^C exceptions to the running
327 -- thread. ToDo: we might want a way to continue even if the target
328 -- thread doesn't die when it receives the exception... "this thread
329 -- is not responding".
331 -- Careful here: there may be ^C exceptions flying around, so we start the new
332 -- thread blocked (forkIO inherits block from the parent, #1048), and unblock
333 -- only while we execute the user's code. We can't afford to lose the final
334 -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
335 sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
336 sandboxIO dflags statusMVar thing =
337 block $ do -- fork starts blocked
338 id <- forkIO $ do res <- Exception.try (unblock $ rethrow dflags thing)
339 putMVar statusMVar (Complete res) -- empty: can't block
340 withInterruptsSentTo id $ takeMVar statusMVar
343 -- We want to turn ^C into a break when -fbreak-on-exception is on,
344 -- but it's an async exception and we only break for sync exceptions.
345 -- Idea: if we catch and re-throw it, then the re-throw will trigger
346 -- a break. Great - but we don't want to re-throw all exceptions, because
347 -- then we'll get a double break for ordinary sync exceptions (you'd have
348 -- to :continue twice, which looks strange). So if the exception is
349 -- not "Interrupted", we unset the exception flag before throwing.
351 rethrow :: DynFlags -> IO a -> IO a
352 rethrow dflags io = Exception.catch io $ \se -> do
353 -- If -fbreak-on-error, we break unconditionally,
354 -- but with care of not breaking twice
355 if dopt Opt_BreakOnError dflags &&
356 not (dopt Opt_BreakOnException dflags)
357 then poke exceptionFlag 1
358 else case fromException se of
359 -- If it is an "Interrupted" exception, we allow
360 -- a possible break by way of -fbreak-on-exception
361 Just Interrupted -> return ()
362 -- In any other case, we don't want to break
363 _ -> poke exceptionFlag 0
367 withInterruptsSentTo :: ThreadId -> IO r -> IO r
368 withInterruptsSentTo thread get_result = do
369 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
370 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
373 -- This function sets up the interpreter for catching breakpoints, and
374 -- resets everything when the computation has stopped running. This
375 -- is a not-very-good way to ensure that only the interactive
376 -- evaluation should generate breakpoints.
377 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
378 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
379 withBreakAction step dflags breakMVar statusMVar act
380 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
383 stablePtr <- newStablePtr onBreak
384 poke breakPointIOAction stablePtr
385 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
386 when step $ setStepFlag
388 -- Breaking on exceptions is not enabled by default, since it
389 -- might be a bit surprising. The exception flag is turned off
390 -- as soon as it is hit, or in resetBreakAction below.
392 onBreak is_exception info apStack = do
394 putMVar statusMVar (Break is_exception apStack info tid)
397 resetBreakAction stablePtr = do
398 poke breakPointIOAction noBreakStablePtr
401 freeStablePtr stablePtr
403 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
404 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
406 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
407 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
408 noBreakAction True _ _ = return () -- exception: just continue
410 resume :: GhcMonad m => SingleStep -> m RunResult
413 hsc_env <- getSession
414 let ic = hsc_IC hsc_env
415 resume = ic_resume ic
418 [] -> ghcError (ProgramError "not stopped at a breakpoint")
420 -- unbind the temporary locals by restoring the TypeEnv from
421 -- before the breakpoint, and drop this Resume from the
422 -- InteractiveContext.
423 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
424 ic' = ic { ic_tmp_ids = resume_tmp_ids,
425 ic_tyvars = resume_tyvars,
427 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
429 -- remove any bindings created since the breakpoint from the
430 -- linker's environment
431 let new_names = map idName (filter (`notElem` resume_tmp_ids)
433 liftIO $ Linker.deleteFromLinkEnv new_names
435 when (isStep step) $ liftIO setStepFlag
437 Resume expr tid breakMVar statusMVar bindings
438 final_ids apStack info _ hist _ -> do
439 withBreakAction (isStep step) (hsc_dflags hsc_env)
440 breakMVar statusMVar $ do
441 status <- liftIO $ withInterruptsSentTo tid $ do
443 -- this awakens the stopped thread...
445 -- and wait for the result
448 Nothing -> fromListBL 50 hist
449 Just i -> mkHistory hsc_env apStack i `consBL`
453 traceRunStatus expr bindings final_ids
454 breakMVar statusMVar status hist'
456 handleRunStatus expr bindings final_ids
457 breakMVar statusMVar status hist'
459 back :: GhcMonad m => m ([Name], Int, SrcSpan)
462 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
463 forward = moveHist (subtract 1)
465 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
467 hsc_env <- getSession
468 case ic_resume (hsc_IC hsc_env) of
469 [] -> ghcError (ProgramError "not stopped at a breakpoint")
471 let ix = resumeHistoryIx r
472 history = resumeHistory r
475 when (new_ix > length history) $
476 ghcError (ProgramError "no more logged breakpoints")
478 ghcError (ProgramError "already at the beginning of the history")
481 update_ic apStack mb_info = do
482 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
484 let ic = hsc_IC hsc_env1
485 r' = r { resumeHistoryIx = new_ix }
486 ic' = ic { ic_resume = r':rs }
488 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
490 return (names, new_ix, span)
492 -- careful: we want apStack to be the AP_STACK itself, not a thunk
493 -- around it, hence the cases are carefully constructed below to
494 -- make this the case. ToDo: this is v. fragile, do something better.
497 Resume { resumeApStack = apStack,
498 resumeBreakInfo = mb_info } ->
499 update_ic apStack mb_info
500 else case history !! (new_ix - 1) of
501 History apStack info _ ->
502 update_ic apStack (Just info)
504 -- -----------------------------------------------------------------------------
505 -- After stopping at a breakpoint, add free variables to the environment
506 result_fs :: FastString
507 result_fs = fsLit "_result"
509 bindLocalsAtBreakpoint
513 -> IO (HscEnv, [Name], SrcSpan)
515 -- Nothing case: we stopped when an exception was raised, not at a
516 -- breakpoint. We have no location information or local variables to
517 -- bind, all we can do is bind a local variable to the exception
519 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
520 let exn_fs = fsLit "_exception"
521 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
523 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
524 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
525 exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
526 new_tyvars = unitVarSet e_tyvar
528 ictxt0 = hsc_IC hsc_env
529 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
531 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
533 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
534 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
536 -- Just case: we stopped at a breakpoint, we have information about the location
537 -- of the breakpoint and the free variables of the expression.
538 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
541 mod_name = moduleName (breakInfo_module info)
542 hmi = expectJust "bindLocalsAtBreakpoint" $
543 lookupUFM (hsc_HPT hsc_env) mod_name
544 breaks = getModBreaks hmi
545 index = breakInfo_number info
546 vars = breakInfo_vars info
547 result_ty = breakInfo_resty info
548 occs = modBreaks_vars breaks ! index
549 span = modBreaks_locs breaks ! index
551 -- filter out any unboxed ids; we can't bind these at the prompt
552 let pointers = filter (\(id,_) -> isPointer id) vars
553 isPointer id | PtrRep <- idPrimRep id = True
556 let (ids, offsets) = unzip pointers
558 -- It might be that getIdValFromApStack fails, because the AP_STACK
559 -- has been accidentally evaluated, or something else has gone wrong.
560 -- So that we don't fall over in a heap when this happens, just don't
561 -- bind any free variables instead, and we emit a warning.
562 mb_hValues <- mapM (getIdValFromApStack apStack) offsets
563 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
564 when (any isNothing mb_hValues) $
565 debugTraceMsg (hsc_dflags hsc_env) 1 $
566 text "Warning: _result has been evaluated, some bindings have been lost"
568 new_ids <- zipWithM mkNewId occs filtered_ids
569 let names = map idName new_ids
571 -- make an Id for _result. We use the Unique of the FastString "_result";
572 -- we don't care about uniqueness here, because there will only be one
573 -- _result in scope at any time.
574 let result_name = mkInternalName (getUnique result_fs)
575 (mkVarOccFS result_fs) span
576 result_id = Id.mkVanillaGlobal result_name result_ty
578 -- for each Id we're about to bind in the local envt:
579 -- - skolemise the type variables in its type, so they can't
580 -- be randomly unified with other types. These type variables
581 -- can only be resolved by type reconstruction in RtClosureInspect
582 -- - tidy the type variables
583 -- - globalise the Id (Ids are supposed to be Global, apparently).
585 let all_ids | isPointer result_id = result_id : new_ids
586 | otherwise = new_ids
587 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
588 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
589 new_tyvars = unionVarSets tyvarss
590 let final_ids = zipWith setIdType all_ids tidy_tys
591 ictxt0 = hsc_IC hsc_env
592 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
593 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
594 Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
595 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
596 return (hsc_env1, result_name:names, span)
598 mkNewId :: OccName -> Id -> IO Id
600 us <- mkSplitUniqSupply 'I'
601 -- we need a fresh Unique for each Id we bind, because the linker
602 -- state is single-threaded and otherwise we'd spam old bindings
603 -- whenever we stop at a breakpoint. The InteractveContext is properly
604 -- saved/restored, but not the linker state. See #1743, test break026.
606 uniq = uniqFromSupply us
607 loc = nameSrcSpan (idName id)
608 name = mkInternalName uniq occ loc
610 new_id = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
613 rttiEnvironment :: HscEnv -> IO HscEnv
614 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
615 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
616 incompletelyTypedIds =
619 , (occNameFS.nameOccName.idName) id /= result_fs]
620 hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
623 noSkolems = null . filter isSkolemTyVar . varSetElems . tyVarsOfType . idType
624 improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
625 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
626 Just id = find (\i -> idName i == name) tmp_ids
630 mb_new_ty <- reconstructType hsc_env 10 id
631 let old_ty = idType id
633 Nothing -> return hsc_env
635 mb_subst <- improveRTTIType hsc_env old_ty new_ty
638 WARN(True, text (":print failed to calculate the "
639 ++ "improvement for a type")) hsc_env
641 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
642 printForUser stderr alwaysQualify $
643 fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
645 let (subst', skols) = skolemiseSubst subst
646 ic' = extendInteractiveContext
647 (substInteractiveContext ic subst') [] skols
648 return hsc_env{hsc_IC=ic'}
650 skolemiseSubst :: TvSubst -> (TvSubst, TyVarSet)
651 skolemiseSubst subst = let
652 varenv = getTvSubstEnv subst
653 all_together = mapVarEnv skolemiseTy varenv
654 (varenv', skol_vars) = ( mapVarEnv fst all_together
655 , map snd (varEnvElts all_together))
656 in (subst `setTvSubstEnv` varenv', unionVarSets skol_vars)
659 skolemiseTy :: Type -> (Type, TyVarSet)
660 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
661 where env = mkVarEnv (zip tyvars new_tyvar_tys)
662 subst = mkTvSubst emptyInScopeSet env
663 tyvars = varSetElems (tyVarsOfType ty)
664 new_tyvars = map skolemiseTyVar tyvars
665 new_tyvar_tys = map mkTyVarTy new_tyvars
667 skolemiseTyVar :: TyVar -> TyVar
668 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
669 (SkolemTv RuntimeUnkSkol)
671 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
672 getIdValFromApStack apStack (I# stackDepth) = do
673 case getApStackVal# apStack (stackDepth +# 1#) of
674 -- The +1 is magic! I don't know where it comes
675 -- from, but this makes things line up. --SDM
678 0# -> return Nothing -- AP_STACK not found
679 _ -> return (Just (unsafeCoerce# result))
681 pushResume :: HscEnv -> Resume -> HscEnv
682 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
684 ictxt0 = hsc_IC hsc_env
685 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
687 -- -----------------------------------------------------------------------------
688 -- Abandoning a resume context
690 abandon :: GhcMonad m => m Bool
692 hsc_env <- getSession
693 let ic = hsc_IC hsc_env
694 resume = ic_resume ic
698 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
702 abandonAll :: GhcMonad m => m Bool
704 hsc_env <- getSession
705 let ic = hsc_IC hsc_env
706 resume = ic_resume ic
710 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
711 liftIO $ mapM_ abandon_ rs
714 -- when abandoning a computation we have to
715 -- (a) kill the thread with an async exception, so that the
716 -- computation itself is stopped, and
717 -- (b) fill in the MVar. This step is necessary because any
718 -- thunks that were under evaluation will now be updated
719 -- with the partial computation, which still ends in takeMVar,
720 -- so any attempt to evaluate one of these thunks will block
721 -- unless we fill in the MVar.
722 -- See test break010.
723 abandon_ :: Resume -> IO ()
725 killThread (resumeThreadId r)
726 putMVar (resumeBreakMVar r) ()
728 -- -----------------------------------------------------------------------------
729 -- Bounded list, optimised for repeated cons
731 data BoundedList a = BL
732 {-# UNPACK #-} !Int -- length
733 {-# UNPACK #-} !Int -- bound
735 [a] -- right, list is (left ++ reverse right)
737 nilBL :: Int -> BoundedList a
738 nilBL bound = BL 0 bound [] []
740 consBL :: a -> BoundedList a -> BoundedList a
741 consBL a (BL len bound left right)
742 | len < bound = BL (len+1) bound (a:left) right
743 | null right = BL len bound [a] $! tail (reverse left)
744 | otherwise = BL len bound (a:left) $! tail right
746 toListBL :: BoundedList a -> [a]
747 toListBL (BL _ _ left right) = left ++ reverse right
749 fromListBL :: Int -> [a] -> BoundedList a
750 fromListBL bound l = BL (length l) bound l []
752 -- lenBL (BL len _ _ _) = len
754 -- -----------------------------------------------------------------------------
755 -- | Set the interactive evaluation context.
757 -- Setting the context doesn't throw away any bindings; the bindings
758 -- we've built up in the InteractiveContext simply move to the new
759 -- module. They always shadow anything in scope in the current context.
760 setContext :: GhcMonad m =>
761 [Module] -- ^ entire top level scope of these modules
762 -> [Module] -- ^ exports only of these modules
764 setContext toplev_mods export_mods = do
765 hsc_env <- getSession
766 let old_ic = hsc_IC hsc_env
767 hpt = hsc_HPT hsc_env
769 export_env <- liftIO $ mkExportEnv hsc_env export_mods
770 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
771 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
772 modifySession $ \_ ->
773 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
774 ic_exports = export_mods,
775 ic_rn_gbl_env = all_env }}
777 -- Make a GlobalRdrEnv based on the exports of the modules only.
778 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
779 mkExportEnv hsc_env mods = do
780 stuff <- mapM (getModuleExports hsc_env) mods
782 (_msgs, mb_name_sets) = unzip stuff
783 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
784 | (Just avails, mod) <- zip mb_name_sets mods ]
786 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
788 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
789 nameSetToGlobalRdrEnv names mod =
790 mkGlobalRdrEnv [ GRE { gre_name = name, gre_par = NoParent, gre_prov = vanillaProv mod }
791 | name <- nameSetToList names ]
793 vanillaProv :: ModuleName -> Provenance
794 -- We're building a GlobalRdrEnv as if the user imported
795 -- all the specified modules into the global interactive module
796 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
798 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
800 is_dloc = srcLocSpan interactiveSrcLoc }
802 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
804 = case lookupUFM hpt (moduleName modl) of
805 Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
806 showSDoc (ppr modl)))
808 case mi_globals (hm_iface details) of
810 ghcError (ProgramError ("mkTopLevEnv: not interpreted "
811 ++ showSDoc (ppr modl)))
812 Just env -> return env
814 -- | Get the interactive evaluation context, consisting of a pair of the
815 -- set of modules from which we take the full top-level scope, and the set
816 -- of modules from which we take just the exports respectively.
817 getContext :: GhcMonad m => m ([Module],[Module])
818 getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
819 return (ic_toplev_scope ic, ic_exports ic)
821 -- | Returns @True@ if the specified module is interpreted, and hence has
822 -- its full top-level scope available.
823 moduleIsInterpreted :: GhcMonad m => Module -> m Bool
824 moduleIsInterpreted modl = withSession $ \h ->
825 if modulePackageId modl /= thisPackage (hsc_dflags h)
827 else case lookupUFM (hsc_HPT h) (moduleName modl) of
828 Just details -> return (isJust (mi_globals (hm_iface details)))
829 _not_a_home_module -> return False
831 -- | Looks up an identifier in the current interactive context (for :info)
832 -- Filter the instances by the ones whose tycons (or clases resp)
833 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
834 -- The exact choice of which ones to show, and which to hide, is a judgement call.
836 getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance]))
838 = withSession $ \hsc_env ->
839 do mb_stuff <- ioMsg $ tcRnGetInfo hsc_env name
841 Nothing -> return Nothing
842 Just (thing, fixity, ispecs) -> do
843 let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
844 return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
846 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
847 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
848 where -- A name is ok if it's in the rdr_env,
849 -- whether qualified or not
850 ok n | n == name = True -- The one we looked for in the first place!
851 | isBuiltInSyntax n = True
852 | isExternalName n = any ((== n) . gre_name)
853 (lookupGRE_Name rdr_env n)
856 -- | Returns all names in scope in the current interactive context
857 getNamesInScope :: GhcMonad m => m [Name]
858 getNamesInScope = withSession $ \hsc_env -> do
859 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
861 getRdrNamesInScope :: GhcMonad m => m [RdrName]
862 getRdrNamesInScope = withSession $ \hsc_env -> do
865 gbl_rdrenv = ic_rn_gbl_env ic
867 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
868 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
870 return (gbl_names ++ lcl_names)
873 -- ToDo: move to RdrName
874 greToRdrNames :: GlobalRdrElt -> [RdrName]
875 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
878 Imported specs -> concat (map do_spec (map is_decl specs))
880 occ = nameOccName name
883 | is_qual decl_spec = [qual]
884 | otherwise = [unqual,qual]
885 where qual = Qual (is_as decl_spec) occ
887 -- | Parses a string as an identifier, and returns the list of 'Name's that
888 -- the identifier can refer to in the current interactive context.
889 parseName :: GhcMonad m => String -> m [Name]
890 parseName str = withSession $ \hsc_env -> do
891 (L _ rdr_name) <- hscParseIdentifier (hsc_dflags hsc_env) str
892 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
894 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
895 -- entity known to GHC, including 'Name's defined using 'runStmt'.
896 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
897 lookupName name = withSession $ \hsc_env -> do
898 mb_tything <- ioMsg $ tcRnLookupName hsc_env name
900 -- XXX: calls panic in some circumstances; is that ok?
902 -- -----------------------------------------------------------------------------
903 -- Getting the type of an expression
905 -- | Get the type of an expression
906 exprType :: GhcMonad m => String -> m Type
907 exprType expr = withSession $ \hsc_env -> do
908 ty <- hscTcExpr hsc_env expr
909 return $ tidyType emptyTidyEnv ty
911 -- -----------------------------------------------------------------------------
912 -- Getting the kind of a type
914 -- | Get the kind of a type
915 typeKind :: GhcMonad m => String -> m Kind
916 typeKind str = withSession $ \hsc_env -> do
917 hscKcType hsc_env str
919 -----------------------------------------------------------------------------
920 -- cmCompileExpr: compile an expression and deliver an HValue
922 compileExpr :: GhcMonad m => String -> m HValue
923 compileExpr expr = withSession $ \hsc_env -> do
924 Just (ids, hval) <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
926 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
929 ([_],[hv]) -> return hv
930 _ -> panic "compileExpr"
932 -- -----------------------------------------------------------------------------
933 -- Compile an expression into a dynamic
935 dynCompileExpr :: GhcMonad m => String -> m Dynamic
936 dynCompileExpr expr = do
937 (full,exports) <- getContext
940 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
942 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
943 Just (ids, hvals) <- withSession (flip hscStmt stmt)
944 setContext full exports
945 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
947 (_:[], v:[]) -> return v
948 _ -> panic "dynCompileExpr"
950 -----------------------------------------------------------------------------
951 -- show a module and it's source/object filenames
953 showModule :: GhcMonad m => ModSummary -> m String
954 showModule mod_summary =
955 withSession $ \hsc_env -> do
956 interpreted <- isModuleInterpreted mod_summary
957 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
959 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
960 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
961 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
962 Nothing -> panic "missing linkable"
963 Just mod_info -> return (not obj_linkable)
965 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
967 ----------------------------------------------------------------------------
970 obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
971 obtainTermFromVal hsc_env bound force ty x =
972 cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
974 obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
975 obtainTermFromId hsc_env bound force id = do
976 hv <- Linker.getHValue hsc_env (varName id)
977 cvObtainTerm hsc_env bound force (idType id) hv
979 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
980 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
981 reconstructType hsc_env bound id = do
982 hv <- Linker.getHValue hsc_env (varName id)
983 cvReconstructType hsc_env bound (idType id) hv