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(..), obtainTerm, obtainTerm1, obtainTermB, reconstructType,
34 skolemiseSubst, skolemiseTy
40 #include "HsVersions.h"
42 import HscMain hiding (compileExpr)
45 import Type hiding (typeKind)
46 import TcType hiding (typeKind)
51 import Name hiding ( varName )
69 import RtClosureInspect
76 import Data.List (find)
83 import Control.Concurrent
84 import Data.List (sortBy)
85 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 #if __GLASGOW_HASKELL__ < 609
353 rethrow dflags io = Exception.catch io $ \e -> do -- NB. not catchDyn
355 -- If -fbreak-on-error, we break unconditionally,
356 -- but with care of not breaking twice
357 _ | dopt Opt_BreakOnError dflags &&
358 not(dopt Opt_BreakOnException dflags)
359 -> poke exceptionFlag 1
361 -- If it is an "Interrupted" exception, we allow
362 -- a possible break by way of -fbreak-on-exception
363 DynException d | Just Interrupted <- fromDynamic d
366 -- In any other case, we don't want to break
367 _ -> poke exceptionFlag 0
371 rethrow dflags io = Exception.catch io $ \se@(SomeException e) -> do
372 -- If -fbreak-on-error, we break unconditionally,
373 -- but with care of not breaking twice
374 if dopt Opt_BreakOnError dflags &&
375 not (dopt Opt_BreakOnException dflags)
376 then poke exceptionFlag 1
378 -- If it is an "Interrupted" exception, we allow
379 -- a possible break by way of -fbreak-on-exception
380 Just Interrupted -> return ()
381 -- In any other case, we don't want to break
382 _ -> poke exceptionFlag 0
387 withInterruptsSentTo :: ThreadId -> IO r -> IO r
388 withInterruptsSentTo thread get_result = do
389 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
390 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
393 -- This function sets up the interpreter for catching breakpoints, and
394 -- resets everything when the computation has stopped running. This
395 -- is a not-very-good way to ensure that only the interactive
396 -- evaluation should generate breakpoints.
397 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
398 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
399 withBreakAction step dflags breakMVar statusMVar act
400 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
403 stablePtr <- newStablePtr onBreak
404 poke breakPointIOAction stablePtr
405 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
406 when step $ setStepFlag
408 -- Breaking on exceptions is not enabled by default, since it
409 -- might be a bit surprising. The exception flag is turned off
410 -- as soon as it is hit, or in resetBreakAction below.
412 onBreak is_exception info apStack = do
414 putMVar statusMVar (Break is_exception apStack info tid)
417 resetBreakAction stablePtr = do
418 poke breakPointIOAction noBreakStablePtr
421 freeStablePtr stablePtr
423 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
424 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
426 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
427 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
428 noBreakAction True _ _ = return () -- exception: just continue
430 resume :: GhcMonad m => SingleStep -> m RunResult
433 hsc_env <- getSession
434 let ic = hsc_IC hsc_env
435 resume = ic_resume ic
438 [] -> ghcError (ProgramError "not stopped at a breakpoint")
440 -- unbind the temporary locals by restoring the TypeEnv from
441 -- before the breakpoint, and drop this Resume from the
442 -- InteractiveContext.
443 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
444 ic' = ic { ic_tmp_ids = resume_tmp_ids,
445 ic_tyvars = resume_tyvars,
447 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
449 -- remove any bindings created since the breakpoint from the
450 -- linker's environment
451 let new_names = map idName (filter (`notElem` resume_tmp_ids)
453 liftIO $ Linker.deleteFromLinkEnv new_names
455 when (isStep step) $ liftIO setStepFlag
457 Resume expr tid breakMVar statusMVar bindings
458 final_ids apStack info _ hist _ -> do
459 withBreakAction (isStep step) (hsc_dflags hsc_env)
460 breakMVar statusMVar $ do
461 status <- liftIO $ withInterruptsSentTo tid $ do
463 -- this awakens the stopped thread...
465 -- and wait for the result
468 Nothing -> fromListBL 50 hist
469 Just i -> mkHistory hsc_env apStack i `consBL`
473 traceRunStatus expr bindings final_ids
474 breakMVar statusMVar status hist'
476 handleRunStatus expr bindings final_ids
477 breakMVar statusMVar status hist'
479 back :: GhcMonad m => m ([Name], Int, SrcSpan)
482 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
483 forward = moveHist (subtract 1)
485 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
487 hsc_env <- getSession
488 case ic_resume (hsc_IC hsc_env) of
489 [] -> ghcError (ProgramError "not stopped at a breakpoint")
491 let ix = resumeHistoryIx r
492 history = resumeHistory r
495 when (new_ix > length history) $
496 ghcError (ProgramError "no more logged breakpoints")
498 ghcError (ProgramError "already at the beginning of the history")
501 update_ic apStack mb_info = do
502 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
504 let ic = hsc_IC hsc_env1
505 r' = r { resumeHistoryIx = new_ix }
506 ic' = ic { ic_resume = r':rs }
508 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
510 return (names, new_ix, span)
512 -- careful: we want apStack to be the AP_STACK itself, not a thunk
513 -- around it, hence the cases are carefully constructed below to
514 -- make this the case. ToDo: this is v. fragile, do something better.
517 Resume { resumeApStack = apStack,
518 resumeBreakInfo = mb_info } ->
519 update_ic apStack mb_info
520 else case history !! (new_ix - 1) of
521 History apStack info _ ->
522 update_ic apStack (Just info)
524 -- -----------------------------------------------------------------------------
525 -- After stopping at a breakpoint, add free variables to the environment
526 result_fs :: FastString
527 result_fs = fsLit "_result"
529 bindLocalsAtBreakpoint
533 -> IO (HscEnv, [Name], SrcSpan)
535 -- Nothing case: we stopped when an exception was raised, not at a
536 -- breakpoint. We have no location information or local variables to
537 -- bind, all we can do is bind a local variable to the exception
539 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
540 let exn_fs = fsLit "_exception"
541 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
543 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
544 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
545 exn_id = Id.mkGlobalId VanillaGlobal exn_name (mkTyVarTy e_tyvar)
547 new_tyvars = unitVarSet e_tyvar
549 ictxt0 = hsc_IC hsc_env
550 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
552 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
554 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
555 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
557 -- Just case: we stopped at a breakpoint, we have information about the location
558 -- of the breakpoint and the free variables of the expression.
559 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
562 mod_name = moduleName (breakInfo_module info)
563 hmi = expectJust "bindLocalsAtBreakpoint" $
564 lookupUFM (hsc_HPT hsc_env) mod_name
565 breaks = getModBreaks hmi
566 index = breakInfo_number info
567 vars = breakInfo_vars info
568 result_ty = breakInfo_resty info
569 occs = modBreaks_vars breaks ! index
570 span = modBreaks_locs breaks ! index
572 -- filter out any unboxed ids; we can't bind these at the prompt
573 let pointers = filter (\(id,_) -> isPointer id) vars
574 isPointer id | PtrRep <- idPrimRep id = True
577 let (ids, offsets) = unzip pointers
579 -- It might be that getIdValFromApStack fails, because the AP_STACK
580 -- has been accidentally evaluated, or something else has gone wrong.
581 -- So that we don't fall over in a heap when this happens, just don't
582 -- bind any free variables instead, and we emit a warning.
583 mb_hValues <- mapM (getIdValFromApStack apStack) offsets
584 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
585 when (any isNothing mb_hValues) $
586 debugTraceMsg (hsc_dflags hsc_env) 1 $
587 text "Warning: _result has been evaluated, some bindings have been lost"
589 new_ids <- zipWithM mkNewId occs filtered_ids
590 let names = map idName new_ids
592 -- make an Id for _result. We use the Unique of the FastString "_result";
593 -- we don't care about uniqueness here, because there will only be one
594 -- _result in scope at any time.
595 let result_name = mkInternalName (getUnique result_fs)
596 (mkVarOccFS result_fs) span
597 result_id = Id.mkGlobalId VanillaGlobal result_name result_ty
600 -- for each Id we're about to bind in the local envt:
601 -- - skolemise the type variables in its type, so they can't
602 -- be randomly unified with other types. These type variables
603 -- can only be resolved by type reconstruction in RtClosureInspect
604 -- - tidy the type variables
605 -- - globalise the Id (Ids are supposed to be Global, apparently).
607 let all_ids | isPointer result_id = result_id : new_ids
608 | otherwise = new_ids
609 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
610 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
611 new_tyvars = unionVarSets tyvarss
612 let final_ids = zipWith setIdType all_ids tidy_tys
613 ictxt0 = hsc_IC hsc_env
614 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
615 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
616 Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
617 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
618 return (hsc_env1, result_name:names, span)
620 mkNewId :: OccName -> Id -> IO Id
622 us <- mkSplitUniqSupply 'I'
623 -- we need a fresh Unique for each Id we bind, because the linker
624 -- state is single-threaded and otherwise we'd spam old bindings
625 -- whenever we stop at a breakpoint. The InteractveContext is properly
626 -- saved/restored, but not the linker state. See #1743, test break026.
628 uniq = uniqFromSupply us
629 loc = nameSrcSpan (idName id)
630 name = mkInternalName uniq occ loc
632 new_id = Id.mkGlobalId VanillaGlobal name ty (idInfo id)
635 rttiEnvironment :: HscEnv -> IO HscEnv
636 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
637 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
638 incompletelyTypedIds =
640 , not $ null [v | v <- varSetElems$ tyVarsOfType (idType id)
642 , (occNameFS.nameOccName.idName) id /= result_fs]
643 tys <- reconstructType hsc_env 10 `mapM` incompletelyTypedIds
644 -- map termType `fmap` (obtainTerm hsc_env False `mapM` incompletelyTypedIds)
646 improvs <- sequence [improveRTTIType hsc_env ty ty'
647 | (ty, Just ty') <- zip (map idType incompletelyTypedIds) tys]
648 let ic' = foldr (\mb_subst ic' ->
649 maybe (WARN(True, text ("RTTI failed to calculate the "
650 ++ "improvement for a type")) ic')
651 (substInteractiveContext ic' . skolemiseSubst)
655 return hsc_env{hsc_IC=ic'}
657 skolemiseSubst :: TvSubst -> TvSubst
658 skolemiseSubst subst = subst `setTvSubstEnv`
659 mapVarEnv (fst.skolemiseTy) (getTvSubstEnv subst)
661 skolemiseTy :: Type -> (Type, TyVarSet)
662 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
663 where env = mkVarEnv (zip tyvars new_tyvar_tys)
664 subst = mkTvSubst emptyInScopeSet env
665 tyvars = varSetElems (tyVarsOfType ty)
666 new_tyvars = map skolemiseTyVar tyvars
667 new_tyvar_tys = map mkTyVarTy new_tyvars
669 skolemiseTyVar :: TyVar -> TyVar
670 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
671 (SkolemTv RuntimeUnkSkol)
673 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
674 getIdValFromApStack apStack (I# stackDepth) = do
675 case getApStackVal# apStack (stackDepth +# 1#) of
676 -- The +1 is magic! I don't know where it comes
677 -- from, but this makes things line up. --SDM
680 0# -> return Nothing -- AP_STACK not found
681 _ -> return (Just (unsafeCoerce# result))
683 pushResume :: HscEnv -> Resume -> HscEnv
684 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
686 ictxt0 = hsc_IC hsc_env
687 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
689 -- -----------------------------------------------------------------------------
690 -- Abandoning a resume context
692 abandon :: GhcMonad m => m Bool
694 hsc_env <- getSession
695 let ic = hsc_IC hsc_env
696 resume = ic_resume ic
700 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
704 abandonAll :: GhcMonad m => m Bool
706 hsc_env <- getSession
707 let ic = hsc_IC hsc_env
708 resume = ic_resume ic
712 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
713 liftIO $ mapM_ abandon_ rs
716 -- when abandoning a computation we have to
717 -- (a) kill the thread with an async exception, so that the
718 -- computation itself is stopped, and
719 -- (b) fill in the MVar. This step is necessary because any
720 -- thunks that were under evaluation will now be updated
721 -- with the partial computation, which still ends in takeMVar,
722 -- so any attempt to evaluate one of these thunks will block
723 -- unless we fill in the MVar.
724 -- See test break010.
725 abandon_ :: Resume -> IO ()
727 killThread (resumeThreadId r)
728 putMVar (resumeBreakMVar r) ()
730 -- -----------------------------------------------------------------------------
731 -- Bounded list, optimised for repeated cons
733 data BoundedList a = BL
734 {-# UNPACK #-} !Int -- length
735 {-# UNPACK #-} !Int -- bound
737 [a] -- right, list is (left ++ reverse right)
739 nilBL :: Int -> BoundedList a
740 nilBL bound = BL 0 bound [] []
742 consBL :: a -> BoundedList a -> BoundedList a
743 consBL a (BL len bound left right)
744 | len < bound = BL (len+1) bound (a:left) right
745 | null right = BL len bound [a] $! tail (reverse left)
746 | otherwise = BL len bound (a:left) $! tail right
748 toListBL :: BoundedList a -> [a]
749 toListBL (BL _ _ left right) = left ++ reverse right
751 fromListBL :: Int -> [a] -> BoundedList a
752 fromListBL bound l = BL (length l) bound l []
754 -- lenBL (BL len _ _ _) = len
756 -- -----------------------------------------------------------------------------
757 -- | Set the interactive evaluation context.
759 -- Setting the context doesn't throw away any bindings; the bindings
760 -- we've built up in the InteractiveContext simply move to the new
761 -- module. They always shadow anything in scope in the current context.
762 setContext :: GhcMonad m =>
763 [Module] -- ^ entire top level scope of these modules
764 -> [Module] -- ^ exports only of these modules
766 setContext toplev_mods export_mods = do
767 hsc_env <- getSession
768 let old_ic = hsc_IC hsc_env
769 hpt = hsc_HPT hsc_env
771 export_env <- liftIO $ mkExportEnv hsc_env export_mods
772 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
773 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
774 modifySession $ \_ ->
775 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
776 ic_exports = export_mods,
777 ic_rn_gbl_env = all_env }}
779 -- Make a GlobalRdrEnv based on the exports of the modules only.
780 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
781 mkExportEnv hsc_env mods = do
782 stuff <- mapM (getModuleExports hsc_env) mods
784 (_msgs, mb_name_sets) = unzip stuff
785 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
786 | (Just avails, mod) <- zip mb_name_sets mods ]
788 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
790 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
791 nameSetToGlobalRdrEnv names mod =
792 mkGlobalRdrEnv [ GRE { gre_name = name, gre_par = NoParent, gre_prov = vanillaProv mod }
793 | name <- nameSetToList names ]
795 vanillaProv :: ModuleName -> Provenance
796 -- We're building a GlobalRdrEnv as if the user imported
797 -- all the specified modules into the global interactive module
798 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
800 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
802 is_dloc = srcLocSpan interactiveSrcLoc }
804 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
806 = case lookupUFM hpt (moduleName modl) of
807 Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
808 showSDoc (ppr modl)))
810 case mi_globals (hm_iface details) of
812 ghcError (ProgramError ("mkTopLevEnv: not interpreted "
813 ++ showSDoc (ppr modl)))
814 Just env -> return env
816 -- | Get the interactive evaluation context, consisting of a pair of the
817 -- set of modules from which we take the full top-level scope, and the set
818 -- of modules from which we take just the exports respectively.
819 getContext :: GhcMonad m => m ([Module],[Module])
820 getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
821 return (ic_toplev_scope ic, ic_exports ic)
823 -- | Returns @True@ if the specified module is interpreted, and hence has
824 -- its full top-level scope available.
825 moduleIsInterpreted :: GhcMonad m => Module -> m Bool
826 moduleIsInterpreted modl = withSession $ \h ->
827 if modulePackageId modl /= thisPackage (hsc_dflags h)
829 else case lookupUFM (hsc_HPT h) (moduleName modl) of
830 Just details -> return (isJust (mi_globals (hm_iface details)))
831 _not_a_home_module -> return False
833 -- | Looks up an identifier in the current interactive context (for :info)
834 -- Filter the instances by the ones whose tycons (or clases resp)
835 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
836 -- The exact choice of which ones to show, and which to hide, is a judgement call.
838 getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance]))
840 = withSession $ \hsc_env ->
841 do mb_stuff <- ioMsg $ tcRnGetInfo hsc_env name
843 Nothing -> return Nothing
844 Just (thing, fixity, ispecs) -> do
845 let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
846 return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
848 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
849 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
850 where -- A name is ok if it's in the rdr_env,
851 -- whether qualified or not
852 ok n | n == name = True -- The one we looked for in the first place!
853 | isBuiltInSyntax n = True
854 | isExternalName n = any ((== n) . gre_name)
855 (lookupGRE_Name rdr_env n)
858 -- | Returns all names in scope in the current interactive context
859 getNamesInScope :: GhcMonad m => m [Name]
860 getNamesInScope = withSession $ \hsc_env -> do
861 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
863 getRdrNamesInScope :: GhcMonad m => m [RdrName]
864 getRdrNamesInScope = withSession $ \hsc_env -> do
867 gbl_rdrenv = ic_rn_gbl_env ic
869 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
870 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
872 return (gbl_names ++ lcl_names)
875 -- ToDo: move to RdrName
876 greToRdrNames :: GlobalRdrElt -> [RdrName]
877 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
880 Imported specs -> concat (map do_spec (map is_decl specs))
882 occ = nameOccName name
885 | is_qual decl_spec = [qual]
886 | otherwise = [unqual,qual]
887 where qual = Qual (is_as decl_spec) occ
889 -- | Parses a string as an identifier, and returns the list of 'Name's that
890 -- the identifier can refer to in the current interactive context.
891 parseName :: GhcMonad m => String -> m [Name]
892 parseName str = withSession $ \hsc_env -> do
893 (L _ rdr_name) <- hscParseIdentifier (hsc_dflags hsc_env) str
894 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
896 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
897 -- entity known to GHC, including 'Name's defined using 'runStmt'.
898 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
899 lookupName name = withSession $ \hsc_env -> do
900 mb_tything <- ioMsg $ tcRnLookupName hsc_env name
902 -- XXX: calls panic in some circumstances; is that ok?
904 -- -----------------------------------------------------------------------------
905 -- Getting the type of an expression
907 -- | Get the type of an expression
908 exprType :: GhcMonad m => String -> m Type
909 exprType expr = withSession $ \hsc_env -> do
910 ty <- hscTcExpr hsc_env expr
911 return $ tidyType emptyTidyEnv ty
913 -- -----------------------------------------------------------------------------
914 -- Getting the kind of a type
916 -- | Get the kind of a type
917 typeKind :: GhcMonad m => String -> m Kind
918 typeKind str = withSession $ \hsc_env -> do
919 hscKcType hsc_env str
921 -----------------------------------------------------------------------------
922 -- cmCompileExpr: compile an expression and deliver an HValue
924 compileExpr :: GhcMonad m => String -> m HValue
925 compileExpr expr = withSession $ \hsc_env -> do
926 Just (ids, hval) <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
928 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
931 ([_],[hv]) -> return hv
932 _ -> panic "compileExpr"
934 -- -----------------------------------------------------------------------------
935 -- Compile an expression into a dynamic
937 dynCompileExpr :: GhcMonad m => String -> m Dynamic
938 dynCompileExpr expr = do
939 (full,exports) <- getContext
942 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
944 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
945 Just (ids, hvals) <- withSession (flip hscStmt stmt)
946 setContext full exports
947 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
949 (_:[], v:[]) -> return v
950 _ -> panic "dynCompileExpr"
952 -----------------------------------------------------------------------------
953 -- show a module and it's source/object filenames
955 showModule :: GhcMonad m => ModSummary -> m String
956 showModule mod_summary =
957 withSession $ \hsc_env -> do
958 interpreted <- isModuleInterpreted mod_summary
959 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
961 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
962 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
963 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
964 Nothing -> panic "missing linkable"
965 Just mod_info -> return (not obj_linkable)
967 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
969 ----------------------------------------------------------------------------
972 obtainTerm1 :: HscEnv -> Bool -> Maybe Type -> a -> IO Term
973 obtainTerm1 hsc_env force mb_ty x =
974 cvObtainTerm hsc_env maxBound force mb_ty (unsafeCoerce# x)
976 obtainTermB :: HscEnv -> Int -> Bool -> Id -> IO Term
977 obtainTermB hsc_env bound force id = do
978 hv <- Linker.getHValue hsc_env (varName id)
979 cvObtainTerm hsc_env bound force (Just$ idType id) hv
981 obtainTerm :: HscEnv -> Bool -> Id -> IO Term
982 obtainTerm hsc_env force id = do
983 hv <- Linker.getHValue hsc_env (varName id)
984 cvObtainTerm hsc_env maxBound force (Just$ idType id) hv
986 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
987 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
988 reconstructType hsc_env bound id = do
989 hv <- Linker.getHValue hsc_env (varName id)
990 cvReconstructType hsc_env bound (Just$ idType id) hv