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)
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
88 -- -----------------------------------------------------------------------------
89 -- running a statement interactively
92 = RunOk [Name] -- ^ names bound by this evaluation
93 | RunFailed -- ^ statement failed compilation
94 | RunException SomeException -- ^ statement raised an exception
95 | RunBreak ThreadId [Name] (Maybe BreakInfo)
98 = Break Bool HValue BreakInfo ThreadId
99 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
100 | Complete (Either SomeException [HValue])
101 -- ^ the computation completed with either an exception or a value
105 resumeStmt :: String, -- the original statement
106 resumeThreadId :: ThreadId, -- thread running the computation
107 resumeBreakMVar :: MVar (),
108 resumeStatMVar :: MVar Status,
109 resumeBindings :: ([Id], TyVarSet),
110 resumeFinalIds :: [Id], -- [Id] to bind on completion
111 resumeApStack :: HValue, -- The object from which we can get
112 -- value of the free variables.
113 resumeBreakInfo :: Maybe BreakInfo,
114 -- the breakpoint we stopped at
115 -- (Nothing <=> exception)
116 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
117 -- to fetch the ModDetails & ModBreaks
119 resumeHistory :: [History],
120 resumeHistoryIx :: Int -- 0 <==> at the top of the history
123 getResumeContext :: GhcMonad m => m [Resume]
124 getResumeContext = withSession (return . ic_resume . hsc_IC)
131 isStep :: SingleStep -> Bool
132 isStep RunToCompletion = False
137 historyApStack :: HValue,
138 historyBreakInfo :: BreakInfo,
139 historyEnclosingDecl :: Id
140 -- ^^ A cache of the enclosing top level declaration, for convenience
143 mkHistory :: HscEnv -> HValue -> BreakInfo -> History
144 mkHistory hsc_env hval bi = let
145 h = History hval bi decl
146 decl = findEnclosingDecl hsc_env (getHistoryModule h)
147 (getHistorySpan hsc_env h)
150 getHistoryModule :: History -> Module
151 getHistoryModule = breakInfo_module . historyBreakInfo
153 getHistorySpan :: HscEnv -> History -> SrcSpan
154 getHistorySpan hsc_env hist =
155 let inf = historyBreakInfo hist
156 num = breakInfo_number inf
157 in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
158 Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
159 _ -> panic "getHistorySpan"
161 getModBreaks :: HomeModInfo -> ModBreaks
163 | Just linkable <- hm_linkable hmi,
164 [BCOs _ modBreaks] <- linkableUnlinked linkable
167 = emptyModBreaks -- probably object code
169 {- | Finds the enclosing top level function name -}
170 -- ToDo: a better way to do this would be to keep hold of the decl_path computed
171 -- by the coverage pass, which gives the list of lexically-enclosing bindings
173 findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
174 findEnclosingDecl hsc_env mod span =
175 case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
176 Nothing -> panic "findEnclosingDecl"
178 globals = typeEnvIds (md_types (hm_details hmi))
180 find (\id -> let n = idName id in
181 nameSrcSpan n < span && isExternalName n)
182 (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
186 -- | Run a statement in the current interactive context. Statement
187 -- may bind multple values.
188 runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
191 hsc_env <- getSession
193 breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
194 statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
196 -- Turn off -fwarn-unused-bindings when running a statement, to hide
197 -- warnings about the implicit bindings we introduce.
198 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
199 hsc_env' = hsc_env{ hsc_dflags = dflags' }
201 r <- hscStmt hsc_env' expr
204 Nothing -> return RunFailed -- empty statement / comment
206 Just (ids, hval) -> do
207 -- XXX: This is the only place we can print warnings before the
208 -- result. Is this really the right thing to do? It's fine for
209 -- GHCi, but what's correct for other GHC API clients? We could
210 -- introduce a callback argument.
212 liftIO $ printBagOfWarnings dflags' warns
216 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
217 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
218 liftIO $ sandboxIO dflags' statusMVar thing_to_run
220 let ic = hsc_IC hsc_env
221 bindings = (ic_tmp_ids ic, ic_tyvars ic)
225 traceRunStatus expr bindings ids
226 breakMVar statusMVar status emptyHistory
228 handleRunStatus expr bindings ids
229 breakMVar statusMVar status emptyHistory
231 emptyHistory :: BoundedList History
232 emptyHistory = nilBL 50 -- keep a log of length 50
234 handleRunStatus :: GhcMonad m =>
235 String-> ([Id], TyVarSet) -> [Id]
236 -> MVar () -> MVar Status -> Status -> BoundedList History
238 handleRunStatus expr bindings final_ids breakMVar statusMVar status
241 -- did we hit a breakpoint or did we complete?
242 (Break is_exception apStack info tid) -> do
243 hsc_env <- getSession
244 let mb_info | is_exception = Nothing
245 | otherwise = Just info
246 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
249 resume = Resume expr tid breakMVar statusMVar
250 bindings final_ids apStack mb_info span
252 hsc_env2 = pushResume hsc_env1 resume
254 modifySession (\_ -> hsc_env2)
255 return (RunBreak tid names mb_info)
256 (Complete either_hvals) ->
258 Left e -> return (RunException e)
260 hsc_env <- getSession
261 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
262 final_ids emptyVarSet
263 -- the bound Ids never have any free TyVars
264 final_names = map idName final_ids
265 liftIO $ Linker.extendLinkEnv (zip final_names hvals)
266 hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
267 modifySession (\_ -> hsc_env')
268 return (RunOk final_names)
270 traceRunStatus :: GhcMonad m =>
271 String -> ([Id], TyVarSet) -> [Id]
272 -> MVar () -> MVar Status -> Status -> BoundedList History
274 traceRunStatus expr bindings final_ids
275 breakMVar statusMVar status history = do
276 hsc_env <- getSession
278 -- when tracing, if we hit a breakpoint that is not explicitly
279 -- enabled, then we just log the event in the history and continue.
280 (Break is_exception apStack info tid) | not is_exception -> do
281 b <- liftIO $ isBreakEnabled hsc_env info
285 let history' = mkHistory hsc_env apStack info `consBL` history
286 -- probably better make history strict here, otherwise
287 -- our BoundedList will be pointless.
288 liftIO $ evaluate history'
290 withBreakAction True (hsc_dflags hsc_env)
291 breakMVar statusMVar $ do
292 liftIO $ withInterruptsSentTo tid $ do
293 putMVar breakMVar () -- awaken the stopped thread
294 takeMVar statusMVar -- and wait for the result
295 traceRunStatus expr bindings final_ids
296 breakMVar statusMVar status history'
300 handle_normally = handleRunStatus expr bindings final_ids
301 breakMVar statusMVar status history
304 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
305 isBreakEnabled hsc_env inf =
306 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
308 w <- getBreak (modBreaks_flags (getModBreaks hmi))
309 (breakInfo_number inf)
310 case w of Just n -> return (n /= 0); _other -> return False
315 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
316 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
319 setStepFlag = poke stepFlag 1
320 resetStepFlag :: IO ()
321 resetStepFlag = poke stepFlag 0
323 -- this points to the IO action that is executed when a breakpoint is hit
324 foreign import ccall "&rts_breakpoint_io_action"
325 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
327 -- When running a computation, we redirect ^C exceptions to the running
328 -- thread. ToDo: we might want a way to continue even if the target
329 -- thread doesn't die when it receives the exception... "this thread
330 -- is not responding".
332 -- Careful here: there may be ^C exceptions flying around, so we start the new
333 -- thread blocked (forkIO inherits block from the parent, #1048), and unblock
334 -- only while we execute the user's code. We can't afford to lose the final
335 -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
336 sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
337 sandboxIO dflags statusMVar thing =
338 block $ do -- fork starts blocked
339 id <- forkIO $ do res <- Exception.try (unblock $ rethrow dflags thing)
340 putMVar statusMVar (Complete res) -- empty: can't block
341 withInterruptsSentTo id $ takeMVar statusMVar
344 -- We want to turn ^C into a break when -fbreak-on-exception is on,
345 -- but it's an async exception and we only break for sync exceptions.
346 -- Idea: if we catch and re-throw it, then the re-throw will trigger
347 -- a break. Great - but we don't want to re-throw all exceptions, because
348 -- then we'll get a double break for ordinary sync exceptions (you'd have
349 -- to :continue twice, which looks strange). So if the exception is
350 -- not "Interrupted", we unset the exception flag before throwing.
352 rethrow :: DynFlags -> IO a -> IO a
353 #if __GLASGOW_HASKELL__ < 609
354 rethrow dflags io = Exception.catch io $ \e -> do -- NB. not catchDyn
356 -- If -fbreak-on-error, we break unconditionally,
357 -- but with care of not breaking twice
358 _ | dopt Opt_BreakOnError dflags &&
359 not(dopt Opt_BreakOnException dflags)
360 -> poke exceptionFlag 1
362 -- If it is an "Interrupted" exception, we allow
363 -- a possible break by way of -fbreak-on-exception
364 DynException d | Just Interrupted <- fromDynamic d
367 -- In any other case, we don't want to break
368 _ -> poke exceptionFlag 0
372 rethrow dflags io = Exception.catch io $ \se@(SomeException e) -> do
373 -- If -fbreak-on-error, we break unconditionally,
374 -- but with care of not breaking twice
375 if dopt Opt_BreakOnError dflags &&
376 not (dopt Opt_BreakOnException dflags)
377 then poke exceptionFlag 1
379 -- If it is an "Interrupted" exception, we allow
380 -- a possible break by way of -fbreak-on-exception
381 Just Interrupted -> return ()
382 -- In any other case, we don't want to break
383 _ -> poke exceptionFlag 0
388 withInterruptsSentTo :: ThreadId -> IO r -> IO r
389 withInterruptsSentTo thread get_result = do
390 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
391 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
394 -- This function sets up the interpreter for catching breakpoints, and
395 -- resets everything when the computation has stopped running. This
396 -- is a not-very-good way to ensure that only the interactive
397 -- evaluation should generate breakpoints.
398 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
399 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
400 withBreakAction step dflags breakMVar statusMVar act
401 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
404 stablePtr <- newStablePtr onBreak
405 poke breakPointIOAction stablePtr
406 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
407 when step $ setStepFlag
409 -- Breaking on exceptions is not enabled by default, since it
410 -- might be a bit surprising. The exception flag is turned off
411 -- as soon as it is hit, or in resetBreakAction below.
413 onBreak is_exception info apStack = do
415 putMVar statusMVar (Break is_exception apStack info tid)
418 resetBreakAction stablePtr = do
419 poke breakPointIOAction noBreakStablePtr
422 freeStablePtr stablePtr
424 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
425 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
427 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
428 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
429 noBreakAction True _ _ = return () -- exception: just continue
431 resume :: GhcMonad m => SingleStep -> m RunResult
434 hsc_env <- getSession
435 let ic = hsc_IC hsc_env
436 resume = ic_resume ic
439 [] -> ghcError (ProgramError "not stopped at a breakpoint")
441 -- unbind the temporary locals by restoring the TypeEnv from
442 -- before the breakpoint, and drop this Resume from the
443 -- InteractiveContext.
444 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
445 ic' = ic { ic_tmp_ids = resume_tmp_ids,
446 ic_tyvars = resume_tyvars,
448 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
450 -- remove any bindings created since the breakpoint from the
451 -- linker's environment
452 let new_names = map idName (filter (`notElem` resume_tmp_ids)
454 liftIO $ Linker.deleteFromLinkEnv new_names
456 when (isStep step) $ liftIO setStepFlag
458 Resume expr tid breakMVar statusMVar bindings
459 final_ids apStack info _ hist _ -> do
460 withBreakAction (isStep step) (hsc_dflags hsc_env)
461 breakMVar statusMVar $ do
462 status <- liftIO $ withInterruptsSentTo tid $ do
464 -- this awakens the stopped thread...
466 -- and wait for the result
469 Nothing -> fromListBL 50 hist
470 Just i -> mkHistory hsc_env apStack i `consBL`
474 traceRunStatus expr bindings final_ids
475 breakMVar statusMVar status hist'
477 handleRunStatus expr bindings final_ids
478 breakMVar statusMVar status hist'
480 back :: GhcMonad m => m ([Name], Int, SrcSpan)
483 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
484 forward = moveHist (subtract 1)
486 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
488 hsc_env <- getSession
489 case ic_resume (hsc_IC hsc_env) of
490 [] -> ghcError (ProgramError "not stopped at a breakpoint")
492 let ix = resumeHistoryIx r
493 history = resumeHistory r
496 when (new_ix > length history) $
497 ghcError (ProgramError "no more logged breakpoints")
499 ghcError (ProgramError "already at the beginning of the history")
502 update_ic apStack mb_info = do
503 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
505 let ic = hsc_IC hsc_env1
506 r' = r { resumeHistoryIx = new_ix }
507 ic' = ic { ic_resume = r':rs }
509 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
511 return (names, new_ix, span)
513 -- careful: we want apStack to be the AP_STACK itself, not a thunk
514 -- around it, hence the cases are carefully constructed below to
515 -- make this the case. ToDo: this is v. fragile, do something better.
518 Resume { resumeApStack = apStack,
519 resumeBreakInfo = mb_info } ->
520 update_ic apStack mb_info
521 else case history !! (new_ix - 1) of
522 History apStack info _ ->
523 update_ic apStack (Just info)
525 -- -----------------------------------------------------------------------------
526 -- After stopping at a breakpoint, add free variables to the environment
527 result_fs :: FastString
528 result_fs = fsLit "_result"
530 bindLocalsAtBreakpoint
534 -> IO (HscEnv, [Name], SrcSpan)
536 -- Nothing case: we stopped when an exception was raised, not at a
537 -- breakpoint. We have no location information or local variables to
538 -- bind, all we can do is bind a local variable to the exception
540 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
541 let exn_fs = fsLit "_exception"
542 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
544 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
545 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
546 exn_id = Id.mkGlobalId VanillaGlobal exn_name (mkTyVarTy e_tyvar)
548 new_tyvars = unitVarSet e_tyvar
550 ictxt0 = hsc_IC hsc_env
551 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
553 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
555 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
556 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
558 -- Just case: we stopped at a breakpoint, we have information about the location
559 -- of the breakpoint and the free variables of the expression.
560 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
563 mod_name = moduleName (breakInfo_module info)
564 hmi = expectJust "bindLocalsAtBreakpoint" $
565 lookupUFM (hsc_HPT hsc_env) mod_name
566 breaks = getModBreaks hmi
567 index = breakInfo_number info
568 vars = breakInfo_vars info
569 result_ty = breakInfo_resty info
570 occs = modBreaks_vars breaks ! index
571 span = modBreaks_locs breaks ! index
573 -- filter out any unboxed ids; we can't bind these at the prompt
574 let pointers = filter (\(id,_) -> isPointer id) vars
575 isPointer id | PtrRep <- idPrimRep id = True
578 let (ids, offsets) = unzip pointers
580 -- It might be that getIdValFromApStack fails, because the AP_STACK
581 -- has been accidentally evaluated, or something else has gone wrong.
582 -- So that we don't fall over in a heap when this happens, just don't
583 -- bind any free variables instead, and we emit a warning.
584 mb_hValues <- mapM (getIdValFromApStack apStack) offsets
585 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
586 when (any isNothing mb_hValues) $
587 debugTraceMsg (hsc_dflags hsc_env) 1 $
588 text "Warning: _result has been evaluated, some bindings have been lost"
590 new_ids <- zipWithM mkNewId occs filtered_ids
591 let names = map idName new_ids
593 -- make an Id for _result. We use the Unique of the FastString "_result";
594 -- we don't care about uniqueness here, because there will only be one
595 -- _result in scope at any time.
596 let result_name = mkInternalName (getUnique result_fs)
597 (mkVarOccFS result_fs) span
598 result_id = Id.mkGlobalId VanillaGlobal result_name result_ty
601 -- for each Id we're about to bind in the local envt:
602 -- - skolemise the type variables in its type, so they can't
603 -- be randomly unified with other types. These type variables
604 -- can only be resolved by type reconstruction in RtClosureInspect
605 -- - tidy the type variables
606 -- - globalise the Id (Ids are supposed to be Global, apparently).
608 let all_ids | isPointer result_id = result_id : new_ids
609 | otherwise = new_ids
610 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
611 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
612 new_tyvars = unionVarSets tyvarss
613 let final_ids = zipWith setIdType all_ids tidy_tys
614 ictxt0 = hsc_IC hsc_env
615 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
616 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
617 Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
618 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
619 return (hsc_env1, result_name:names, span)
621 mkNewId :: OccName -> Id -> IO Id
623 us <- mkSplitUniqSupply 'I'
624 -- we need a fresh Unique for each Id we bind, because the linker
625 -- state is single-threaded and otherwise we'd spam old bindings
626 -- whenever we stop at a breakpoint. The InteractveContext is properly
627 -- saved/restored, but not the linker state. See #1743, test break026.
629 uniq = uniqFromSupply us
630 loc = nameSrcSpan (idName id)
631 name = mkInternalName uniq occ loc
633 new_id = Id.mkGlobalId VanillaGlobal name ty (idInfo id)
636 rttiEnvironment :: HscEnv -> IO HscEnv
637 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
638 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
639 incompletelyTypedIds =
642 , (occNameFS.nameOccName.idName) id /= result_fs]
643 hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
646 noSkolems = null . filter isSkolemTyVar . varSetElems . tyVarsOfType . idType
647 improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
648 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
649 Just id = find (\i -> idName i == name) tmp_ids
653 mb_new_ty <- reconstructType hsc_env 10 id
654 let old_ty = idType id
656 Nothing -> return hsc_env
658 mb_subst <- improveRTTIType hsc_env old_ty new_ty
661 WARN(True, text (":print failed to calculate the "
662 ++ "improvement for a type")) hsc_env
664 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
665 printForUser stderr alwaysQualify $
666 fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
668 let (subst', skols) = skolemiseSubst subst
669 ic' = extendInteractiveContext
670 (substInteractiveContext ic subst') [] skols
671 return hsc_env{hsc_IC=ic'}
673 skolemiseSubst :: TvSubst -> (TvSubst, TyVarSet)
674 skolemiseSubst subst = let
675 varenv = getTvSubstEnv subst
676 all_together = mapVarEnv skolemiseTy varenv
677 (varenv', skol_vars) = ( mapVarEnv fst all_together
678 , map snd (varEnvElts all_together))
679 in (subst `setTvSubstEnv` varenv', unionVarSets skol_vars)
682 skolemiseTy :: Type -> (Type, TyVarSet)
683 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
684 where env = mkVarEnv (zip tyvars new_tyvar_tys)
685 subst = mkTvSubst emptyInScopeSet env
686 tyvars = varSetElems (tyVarsOfType ty)
687 new_tyvars = map skolemiseTyVar tyvars
688 new_tyvar_tys = map mkTyVarTy new_tyvars
690 skolemiseTyVar :: TyVar -> TyVar
691 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
692 (SkolemTv RuntimeUnkSkol)
694 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
695 getIdValFromApStack apStack (I# stackDepth) = do
696 case getApStackVal# apStack (stackDepth +# 1#) of
697 -- The +1 is magic! I don't know where it comes
698 -- from, but this makes things line up. --SDM
701 0# -> return Nothing -- AP_STACK not found
702 _ -> return (Just (unsafeCoerce# result))
704 pushResume :: HscEnv -> Resume -> HscEnv
705 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
707 ictxt0 = hsc_IC hsc_env
708 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
710 -- -----------------------------------------------------------------------------
711 -- Abandoning a resume context
713 abandon :: GhcMonad m => m Bool
715 hsc_env <- getSession
716 let ic = hsc_IC hsc_env
717 resume = ic_resume ic
721 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
725 abandonAll :: GhcMonad m => m Bool
727 hsc_env <- getSession
728 let ic = hsc_IC hsc_env
729 resume = ic_resume ic
733 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
734 liftIO $ mapM_ abandon_ rs
737 -- when abandoning a computation we have to
738 -- (a) kill the thread with an async exception, so that the
739 -- computation itself is stopped, and
740 -- (b) fill in the MVar. This step is necessary because any
741 -- thunks that were under evaluation will now be updated
742 -- with the partial computation, which still ends in takeMVar,
743 -- so any attempt to evaluate one of these thunks will block
744 -- unless we fill in the MVar.
745 -- See test break010.
746 abandon_ :: Resume -> IO ()
748 killThread (resumeThreadId r)
749 putMVar (resumeBreakMVar r) ()
751 -- -----------------------------------------------------------------------------
752 -- Bounded list, optimised for repeated cons
754 data BoundedList a = BL
755 {-# UNPACK #-} !Int -- length
756 {-# UNPACK #-} !Int -- bound
758 [a] -- right, list is (left ++ reverse right)
760 nilBL :: Int -> BoundedList a
761 nilBL bound = BL 0 bound [] []
763 consBL :: a -> BoundedList a -> BoundedList a
764 consBL a (BL len bound left right)
765 | len < bound = BL (len+1) bound (a:left) right
766 | null right = BL len bound [a] $! tail (reverse left)
767 | otherwise = BL len bound (a:left) $! tail right
769 toListBL :: BoundedList a -> [a]
770 toListBL (BL _ _ left right) = left ++ reverse right
772 fromListBL :: Int -> [a] -> BoundedList a
773 fromListBL bound l = BL (length l) bound l []
775 -- lenBL (BL len _ _ _) = len
777 -- -----------------------------------------------------------------------------
778 -- | Set the interactive evaluation context.
780 -- Setting the context doesn't throw away any bindings; the bindings
781 -- we've built up in the InteractiveContext simply move to the new
782 -- module. They always shadow anything in scope in the current context.
783 setContext :: GhcMonad m =>
784 [Module] -- ^ entire top level scope of these modules
785 -> [Module] -- ^ exports only of these modules
787 setContext toplev_mods export_mods = do
788 hsc_env <- getSession
789 let old_ic = hsc_IC hsc_env
790 hpt = hsc_HPT hsc_env
792 export_env <- liftIO $ mkExportEnv hsc_env export_mods
793 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
794 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
795 modifySession $ \_ ->
796 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
797 ic_exports = export_mods,
798 ic_rn_gbl_env = all_env }}
800 -- Make a GlobalRdrEnv based on the exports of the modules only.
801 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
802 mkExportEnv hsc_env mods = do
803 stuff <- mapM (getModuleExports hsc_env) mods
805 (_msgs, mb_name_sets) = unzip stuff
806 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
807 | (Just avails, mod) <- zip mb_name_sets mods ]
809 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
811 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
812 nameSetToGlobalRdrEnv names mod =
813 mkGlobalRdrEnv [ GRE { gre_name = name, gre_par = NoParent, gre_prov = vanillaProv mod }
814 | name <- nameSetToList names ]
816 vanillaProv :: ModuleName -> Provenance
817 -- We're building a GlobalRdrEnv as if the user imported
818 -- all the specified modules into the global interactive module
819 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
821 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
823 is_dloc = srcLocSpan interactiveSrcLoc }
825 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
827 = case lookupUFM hpt (moduleName modl) of
828 Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
829 showSDoc (ppr modl)))
831 case mi_globals (hm_iface details) of
833 ghcError (ProgramError ("mkTopLevEnv: not interpreted "
834 ++ showSDoc (ppr modl)))
835 Just env -> return env
837 -- | Get the interactive evaluation context, consisting of a pair of the
838 -- set of modules from which we take the full top-level scope, and the set
839 -- of modules from which we take just the exports respectively.
840 getContext :: GhcMonad m => m ([Module],[Module])
841 getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
842 return (ic_toplev_scope ic, ic_exports ic)
844 -- | Returns @True@ if the specified module is interpreted, and hence has
845 -- its full top-level scope available.
846 moduleIsInterpreted :: GhcMonad m => Module -> m Bool
847 moduleIsInterpreted modl = withSession $ \h ->
848 if modulePackageId modl /= thisPackage (hsc_dflags h)
850 else case lookupUFM (hsc_HPT h) (moduleName modl) of
851 Just details -> return (isJust (mi_globals (hm_iface details)))
852 _not_a_home_module -> return False
854 -- | Looks up an identifier in the current interactive context (for :info)
855 -- Filter the instances by the ones whose tycons (or clases resp)
856 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
857 -- The exact choice of which ones to show, and which to hide, is a judgement call.
859 getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance]))
861 = withSession $ \hsc_env ->
862 do mb_stuff <- ioMsg $ tcRnGetInfo hsc_env name
864 Nothing -> return Nothing
865 Just (thing, fixity, ispecs) -> do
866 let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
867 return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
869 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
870 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
871 where -- A name is ok if it's in the rdr_env,
872 -- whether qualified or not
873 ok n | n == name = True -- The one we looked for in the first place!
874 | isBuiltInSyntax n = True
875 | isExternalName n = any ((== n) . gre_name)
876 (lookupGRE_Name rdr_env n)
879 -- | Returns all names in scope in the current interactive context
880 getNamesInScope :: GhcMonad m => m [Name]
881 getNamesInScope = withSession $ \hsc_env -> do
882 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
884 getRdrNamesInScope :: GhcMonad m => m [RdrName]
885 getRdrNamesInScope = withSession $ \hsc_env -> do
888 gbl_rdrenv = ic_rn_gbl_env ic
890 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
891 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
893 return (gbl_names ++ lcl_names)
896 -- ToDo: move to RdrName
897 greToRdrNames :: GlobalRdrElt -> [RdrName]
898 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
901 Imported specs -> concat (map do_spec (map is_decl specs))
903 occ = nameOccName name
906 | is_qual decl_spec = [qual]
907 | otherwise = [unqual,qual]
908 where qual = Qual (is_as decl_spec) occ
910 -- | Parses a string as an identifier, and returns the list of 'Name's that
911 -- the identifier can refer to in the current interactive context.
912 parseName :: GhcMonad m => String -> m [Name]
913 parseName str = withSession $ \hsc_env -> do
914 (L _ rdr_name) <- hscParseIdentifier (hsc_dflags hsc_env) str
915 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
917 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
918 -- entity known to GHC, including 'Name's defined using 'runStmt'.
919 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
920 lookupName name = withSession $ \hsc_env -> do
921 mb_tything <- ioMsg $ tcRnLookupName hsc_env name
923 -- XXX: calls panic in some circumstances; is that ok?
925 -- -----------------------------------------------------------------------------
926 -- Getting the type of an expression
928 -- | Get the type of an expression
929 exprType :: GhcMonad m => String -> m Type
930 exprType expr = withSession $ \hsc_env -> do
931 ty <- hscTcExpr hsc_env expr
932 return $ tidyType emptyTidyEnv ty
934 -- -----------------------------------------------------------------------------
935 -- Getting the kind of a type
937 -- | Get the kind of a type
938 typeKind :: GhcMonad m => String -> m Kind
939 typeKind str = withSession $ \hsc_env -> do
940 hscKcType hsc_env str
942 -----------------------------------------------------------------------------
943 -- cmCompileExpr: compile an expression and deliver an HValue
945 compileExpr :: GhcMonad m => String -> m HValue
946 compileExpr expr = withSession $ \hsc_env -> do
947 Just (ids, hval) <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
949 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
952 ([_],[hv]) -> return hv
953 _ -> panic "compileExpr"
955 -- -----------------------------------------------------------------------------
956 -- Compile an expression into a dynamic
958 dynCompileExpr :: GhcMonad m => String -> m Dynamic
959 dynCompileExpr expr = do
960 (full,exports) <- getContext
963 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
965 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
966 Just (ids, hvals) <- withSession (flip hscStmt stmt)
967 setContext full exports
968 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
970 (_:[], v:[]) -> return v
971 _ -> panic "dynCompileExpr"
973 -----------------------------------------------------------------------------
974 -- show a module and it's source/object filenames
976 showModule :: GhcMonad m => ModSummary -> m String
977 showModule mod_summary =
978 withSession $ \hsc_env -> do
979 interpreted <- isModuleInterpreted mod_summary
980 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
982 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
983 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
984 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
985 Nothing -> panic "missing linkable"
986 Just mod_info -> return (not obj_linkable)
988 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
990 ----------------------------------------------------------------------------
993 obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
994 obtainTermFromVal hsc_env bound force ty x =
995 cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
997 obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
998 obtainTermFromId hsc_env bound force id = do
999 hv <- Linker.getHValue hsc_env (varName id)
1000 cvObtainTerm hsc_env bound force (idType id) hv
1002 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
1003 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
1004 reconstructType hsc_env bound id = do
1005 hv <- Linker.getHValue hsc_env (varName id)
1006 cvReconstructType hsc_env bound (idType id) hv