1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005-2007
5 -- Running statements interactively
7 -- -----------------------------------------------------------------------------
9 module InteractiveEval (
11 RunResult(..), Status(..), Resume(..), History(..),
12 runStmt, runStmtWithLocation,
13 parseImportDecl, SingleStep(..),
21 setContext, getContext,
32 compileExpr, dynCompileExpr,
33 Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
39 #include "HsVersions.h"
43 import HsSyn (ImportDecl)
46 import RnNames (gresFromAvails)
49 import TcType hiding( typeKind )
52 import Name hiding ( varName )
55 import PrelNames (pRELUDE)
70 import RtClosureInspect
76 import System.Directory
78 import Data.List (find, partition)
80 import Foreign hiding (unsafePerformIO)
85 import Control.Concurrent
86 -- import Foreign.StablePtr
88 import System.IO.Unsafe
90 -- -----------------------------------------------------------------------------
91 -- running a statement interactively
94 = RunOk [Name] -- ^ names bound by this evaluation
95 | RunFailed -- ^ statement failed compilation
96 | RunException SomeException -- ^ statement raised an exception
97 | RunBreak ThreadId [Name] (Maybe BreakInfo)
100 = Break Bool HValue BreakInfo ThreadId
101 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
102 | Complete (Either SomeException [HValue])
103 -- ^ the computation completed with either an exception or a value
107 resumeStmt :: String, -- the original statement
108 resumeThreadId :: ThreadId, -- thread running the computation
109 resumeBreakMVar :: MVar (),
110 resumeStatMVar :: MVar Status,
111 resumeBindings :: [Id],
112 resumeFinalIds :: [Id], -- [Id] to bind on completion
113 resumeApStack :: HValue, -- The object from which we can get
114 -- value of the free variables.
115 resumeBreakInfo :: Maybe BreakInfo,
116 -- the breakpoint we stopped at
117 -- (Nothing <=> exception)
118 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
119 -- to fetch the ModDetails & ModBreaks
121 resumeHistory :: [History],
122 resumeHistoryIx :: Int -- 0 <==> at the top of the history
125 getResumeContext :: GhcMonad m => m [Resume]
126 getResumeContext = withSession (return . ic_resume . hsc_IC)
133 isStep :: SingleStep -> Bool
134 isStep RunToCompletion = False
139 historyApStack :: HValue,
140 historyBreakInfo :: BreakInfo,
141 historyEnclosingDecls :: [String] -- declarations enclosing the breakpoint
144 mkHistory :: HscEnv -> HValue -> BreakInfo -> History
145 mkHistory hsc_env hval bi = let
146 decls = findEnclosingDecls hsc_env bi
147 in History hval bi decls
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 findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
174 findEnclosingDecls hsc_env inf =
175 let hmi = expectJust "findEnclosingDecls" $
176 lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
177 mb = getModBreaks hmi
178 in modBreaks_decls mb ! breakInfo_number inf
181 -- | Run a statement in the current interactive context. Statement
182 -- may bind multple values.
183 runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
184 runStmt = runStmtWithLocation "<interactive>" 1
186 -- | Run a statement in the current interactive context. Passing debug information
187 -- Statement may bind multple values.
188 runStmtWithLocation :: GhcMonad m => String -> Int ->
189 String -> SingleStep -> m RunResult
190 runStmtWithLocation source linenumber expr step =
192 hsc_env <- getSession
194 breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
195 statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
197 -- Turn off -fwarn-unused-bindings when running a statement, to hide
198 -- warnings about the implicit bindings we introduce.
199 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
200 hsc_env' = hsc_env{ hsc_dflags = dflags' }
202 r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
205 Nothing -> return RunFailed -- empty statement / comment
207 Just (ids, hval) -> do
210 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
211 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
212 liftIO $ sandboxIO dflags' statusMVar thing_to_run
214 let ic = hsc_IC hsc_env
215 bindings = ic_tmp_ids ic
219 traceRunStatus expr bindings ids
220 breakMVar statusMVar status emptyHistory
222 handleRunStatus expr bindings ids
223 breakMVar statusMVar status emptyHistory
225 withVirtualCWD :: GhcMonad m => m a -> m a
226 withVirtualCWD m = do
227 hsc_env <- getSession
228 let ic = hsc_IC hsc_env
231 dir <- liftIO $ getCurrentDirectory
233 Just dir -> liftIO $ setCurrentDirectory dir
237 reset_cwd orig_dir = do
238 virt_dir <- liftIO $ getCurrentDirectory
239 hsc_env <- getSession
240 let old_IC = hsc_IC hsc_env
241 setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
242 liftIO $ setCurrentDirectory orig_dir
244 gbracket set_cwd reset_cwd $ \_ -> m
246 parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
247 parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
249 emptyHistory :: BoundedList History
250 emptyHistory = nilBL 50 -- keep a log of length 50
252 handleRunStatus :: GhcMonad m =>
253 String-> [Id] -> [Id]
254 -> MVar () -> MVar Status -> Status -> BoundedList History
256 handleRunStatus expr bindings final_ids breakMVar statusMVar status
259 -- did we hit a breakpoint or did we complete?
260 (Break is_exception apStack info tid) -> do
261 hsc_env <- getSession
262 let mb_info | is_exception = Nothing
263 | otherwise = Just info
264 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
267 resume = Resume { resumeStmt = expr, resumeThreadId = tid
268 , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
269 , resumeBindings = bindings, resumeFinalIds = final_ids
270 , resumeApStack = apStack, resumeBreakInfo = mb_info
271 , resumeSpan = span, resumeHistory = toListBL history
272 , resumeHistoryIx = 0 }
273 hsc_env2 = pushResume hsc_env1 resume
275 modifySession (\_ -> hsc_env2)
276 return (RunBreak tid names mb_info)
277 (Complete either_hvals) ->
279 Left e -> return (RunException e)
281 hsc_env <- getSession
282 let final_ic = extendInteractiveContext (hsc_IC hsc_env) final_ids
283 final_names = map idName final_ids
284 liftIO $ Linker.extendLinkEnv (zip final_names hvals)
285 hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
286 modifySession (\_ -> hsc_env')
287 return (RunOk final_names)
289 traceRunStatus :: GhcMonad m =>
290 String -> [Id] -> [Id]
291 -> MVar () -> MVar Status -> Status -> BoundedList History
293 traceRunStatus expr bindings final_ids
294 breakMVar statusMVar status history = do
295 hsc_env <- getSession
297 -- when tracing, if we hit a breakpoint that is not explicitly
298 -- enabled, then we just log the event in the history and continue.
299 (Break is_exception apStack info tid) | not is_exception -> do
300 b <- liftIO $ isBreakEnabled hsc_env info
304 let history' = mkHistory hsc_env apStack info `consBL` history
305 -- probably better make history strict here, otherwise
306 -- our BoundedList will be pointless.
307 _ <- liftIO $ evaluate history'
309 withBreakAction True (hsc_dflags hsc_env)
310 breakMVar statusMVar $ do
311 liftIO $ withInterruptsSentTo tid $ do
312 putMVar breakMVar () -- awaken the stopped thread
313 takeMVar statusMVar -- and wait for the result
314 traceRunStatus expr bindings final_ids
315 breakMVar statusMVar status history'
319 handle_normally = handleRunStatus expr bindings final_ids
320 breakMVar statusMVar status history
323 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
324 isBreakEnabled hsc_env inf =
325 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
327 w <- getBreak (modBreaks_flags (getModBreaks hmi))
328 (breakInfo_number inf)
329 case w of Just n -> return (n /= 0); _other -> return False
334 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
335 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
338 setStepFlag = poke stepFlag 1
339 resetStepFlag :: IO ()
340 resetStepFlag = poke stepFlag 0
342 -- this points to the IO action that is executed when a breakpoint is hit
343 foreign import ccall "&rts_breakpoint_io_action"
344 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
346 -- When running a computation, we redirect ^C exceptions to the running
347 -- thread. ToDo: we might want a way to continue even if the target
348 -- thread doesn't die when it receives the exception... "this thread
349 -- is not responding".
351 -- Careful here: there may be ^C exceptions flying around, so we start the new
352 -- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
353 -- only while we execute the user's code. We can't afford to lose the final
354 -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
355 sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
356 sandboxIO dflags statusMVar thing =
357 mask $ \restore -> -- fork starts blocked
358 let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
359 in if dopt Opt_GhciSandbox dflags
360 then do tid <- forkIO $ do res <- runIt
361 putMVar statusMVar res -- empty: can't block
362 withInterruptsSentTo tid $ takeMVar statusMVar
363 else -- GLUT on OS X needs to run on the main thread. If you
364 -- try to use it from another thread then you just get a
365 -- white rectangle rendered. For this, or anything else
366 -- with such restrictions, you can turn the GHCi sandbox off
367 -- and things will be run in the main thread.
370 -- We want to turn ^C into a break when -fbreak-on-exception is on,
371 -- but it's an async exception and we only break for sync exceptions.
372 -- Idea: if we catch and re-throw it, then the re-throw will trigger
373 -- a break. Great - but we don't want to re-throw all exceptions, because
374 -- then we'll get a double break for ordinary sync exceptions (you'd have
375 -- to :continue twice, which looks strange). So if the exception is
376 -- not "Interrupted", we unset the exception flag before throwing.
378 rethrow :: DynFlags -> IO a -> IO a
379 rethrow dflags io = Exception.catch io $ \se -> do
380 -- If -fbreak-on-error, we break unconditionally,
381 -- but with care of not breaking twice
382 if dopt Opt_BreakOnError dflags &&
383 not (dopt Opt_BreakOnException dflags)
384 then poke exceptionFlag 1
385 else case fromException se of
386 -- If it is a "UserInterrupt" exception, we allow
387 -- a possible break by way of -fbreak-on-exception
388 Just UserInterrupt -> return ()
389 -- In any other case, we don't want to break
390 _ -> poke exceptionFlag 0
394 withInterruptsSentTo :: ThreadId -> IO r -> IO r
395 withInterruptsSentTo thread get_result = do
396 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
397 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
400 -- This function sets up the interpreter for catching breakpoints, and
401 -- resets everything when the computation has stopped running. This
402 -- is a not-very-good way to ensure that only the interactive
403 -- evaluation should generate breakpoints.
404 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
405 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
406 withBreakAction step dflags breakMVar statusMVar act
407 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
410 stablePtr <- newStablePtr onBreak
411 poke breakPointIOAction stablePtr
412 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
413 when step $ setStepFlag
415 -- Breaking on exceptions is not enabled by default, since it
416 -- might be a bit surprising. The exception flag is turned off
417 -- as soon as it is hit, or in resetBreakAction below.
419 onBreak is_exception info apStack = do
421 putMVar statusMVar (Break is_exception apStack info tid)
424 resetBreakAction stablePtr = do
425 poke breakPointIOAction noBreakStablePtr
428 freeStablePtr stablePtr
430 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
431 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
433 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
434 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
435 noBreakAction True _ _ = return () -- exception: just continue
437 resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
438 resume canLogSpan step
440 hsc_env <- getSession
441 let ic = hsc_IC hsc_env
442 resume = ic_resume ic
445 [] -> ghcError (ProgramError "not stopped at a breakpoint")
447 -- unbind the temporary locals by restoring the TypeEnv from
448 -- before the breakpoint, and drop this Resume from the
449 -- InteractiveContext.
450 let resume_tmp_ids = resumeBindings r
451 ic' = ic { ic_tmp_ids = resume_tmp_ids,
453 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
455 -- remove any bindings created since the breakpoint from the
456 -- linker's environment
457 let new_names = map idName (filter (`notElem` resume_tmp_ids)
459 liftIO $ Linker.deleteFromLinkEnv new_names
461 when (isStep step) $ liftIO setStepFlag
463 Resume { resumeStmt = expr, resumeThreadId = tid
464 , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
465 , resumeBindings = bindings, resumeFinalIds = final_ids
466 , resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
467 , resumeHistory = hist } -> do
469 withBreakAction (isStep step) (hsc_dflags hsc_env)
470 breakMVar statusMVar $ do
471 status <- liftIO $ withInterruptsSentTo tid $ do
473 -- this awakens the stopped thread...
475 -- and wait for the result
476 let prevHistoryLst = fromListBL 50 hist
478 Nothing -> prevHistoryLst
480 | not $canLogSpan span -> prevHistoryLst
481 | otherwise -> mkHistory hsc_env apStack i `consBL`
485 traceRunStatus expr bindings final_ids
486 breakMVar statusMVar status hist'
488 handleRunStatus expr bindings final_ids
489 breakMVar statusMVar status hist'
491 back :: GhcMonad m => m ([Name], Int, SrcSpan)
494 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
495 forward = moveHist (subtract 1)
497 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
499 hsc_env <- getSession
500 case ic_resume (hsc_IC hsc_env) of
501 [] -> ghcError (ProgramError "not stopped at a breakpoint")
503 let ix = resumeHistoryIx r
504 history = resumeHistory r
507 when (new_ix > length history) $
508 ghcError (ProgramError "no more logged breakpoints")
510 ghcError (ProgramError "already at the beginning of the history")
513 update_ic apStack mb_info = do
514 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
516 let ic = hsc_IC hsc_env1
517 r' = r { resumeHistoryIx = new_ix }
518 ic' = ic { ic_resume = r':rs }
520 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
522 return (names, new_ix, span)
524 -- careful: we want apStack to be the AP_STACK itself, not a thunk
525 -- around it, hence the cases are carefully constructed below to
526 -- make this the case. ToDo: this is v. fragile, do something better.
529 Resume { resumeApStack = apStack,
530 resumeBreakInfo = mb_info } ->
531 update_ic apStack mb_info
532 else case history !! (new_ix - 1) of
533 History apStack info _ ->
534 update_ic apStack (Just info)
536 -- -----------------------------------------------------------------------------
537 -- After stopping at a breakpoint, add free variables to the environment
538 result_fs :: FastString
539 result_fs = fsLit "_result"
541 bindLocalsAtBreakpoint
545 -> IO (HscEnv, [Name], SrcSpan)
547 -- Nothing case: we stopped when an exception was raised, not at a
548 -- breakpoint. We have no location information or local variables to
549 -- bind, all we can do is bind a local variable to the exception
551 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
552 let exn_fs = fsLit "_exception"
553 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
555 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
556 e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
557 exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
559 ictxt0 = hsc_IC hsc_env
560 ictxt1 = extendInteractiveContext ictxt0 [exn_id]
562 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
564 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
565 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
567 -- Just case: we stopped at a breakpoint, we have information about the location
568 -- of the breakpoint and the free variables of the expression.
569 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
572 mod_name = moduleName (breakInfo_module info)
573 hmi = expectJust "bindLocalsAtBreakpoint" $
574 lookupUFM (hsc_HPT hsc_env) mod_name
575 breaks = getModBreaks hmi
576 index = breakInfo_number info
577 vars = breakInfo_vars info
578 result_ty = breakInfo_resty info
579 occs = modBreaks_vars breaks ! index
580 span = modBreaks_locs breaks ! index
582 -- Filter out any unboxed ids;
583 -- we can't bind these at the prompt
584 pointers = filter (\(id,_) -> isPointer id) vars
585 isPointer id | PtrRep <- idPrimRep id = True
588 (ids, offsets) = unzip pointers
590 free_tvs = foldr (unionVarSet . tyVarsOfType . idType)
591 (tyVarsOfType result_ty) ids
593 -- It might be that getIdValFromApStack fails, because the AP_STACK
594 -- has been accidentally evaluated, or something else has gone wrong.
595 -- So that we don't fall over in a heap when this happens, just don't
596 -- bind any free variables instead, and we emit a warning.
597 mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
598 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
599 when (any isNothing mb_hValues) $
600 debugTraceMsg (hsc_dflags hsc_env) 1 $
601 text "Warning: _result has been evaluated, some bindings have been lost"
603 us <- mkSplitUniqSupply 'I'
604 let (us1, us2) = splitUniqSupply us
605 tv_subst = newTyVars us1 free_tvs
606 new_ids = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
607 names = map idName new_ids
609 -- make an Id for _result. We use the Unique of the FastString "_result";
610 -- we don't care about uniqueness here, because there will only be one
611 -- _result in scope at any time.
612 let result_name = mkInternalName (getUnique result_fs)
613 (mkVarOccFS result_fs) span
614 result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
616 -- for each Id we're about to bind in the local envt:
617 -- - tidy the type variables
618 -- - globalise the Id (Ids are supposed to be Global, apparently).
620 let result_ok = isPointer result_id
621 && not (isUnboxedTupleType (idType result_id))
623 all_ids | result_ok = result_id : new_ids
624 | otherwise = new_ids
625 id_tys = map idType all_ids
626 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
627 final_ids = zipWith setIdType all_ids tidy_tys
628 ictxt0 = hsc_IC hsc_env
629 ictxt1 = extendInteractiveContext ictxt0 final_ids
631 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
632 when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
633 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
634 return (hsc_env1, if result_ok then result_name:names else names, span)
636 -- We need a fresh Unique for each Id we bind, because the linker
637 -- state is single-threaded and otherwise we'd spam old bindings
638 -- whenever we stop at a breakpoint. The InteractveContext is properly
639 -- saved/restored, but not the linker state. See #1743, test break026.
640 mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
641 mkNewId tv_subst occ id uniq
642 = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
644 loc = nameSrcSpan (idName id)
645 name = mkInternalName uniq occ loc
646 ty = substTy tv_subst (idType id)
648 newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
649 -- Similarly, clone the type variables mentioned in the types
650 -- we have here, *and* make them all RuntimeUnk tyars
652 = mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
653 | (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
654 , let name = setNameUnique (tyVarName tv) uniq ]
656 rttiEnvironment :: HscEnv -> IO HscEnv
657 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
658 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
659 incompletelyTypedIds =
662 , (occNameFS.nameOccName.idName) id /= result_fs]
663 hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
666 noSkolems = isEmptyVarSet . tyVarsOfType . idType
667 improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
668 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
669 Just id = find (\i -> idName i == name) tmp_ids
673 mb_new_ty <- reconstructType hsc_env 10 id
674 let old_ty = idType id
676 Nothing -> return hsc_env
678 case improveRTTIType hsc_env old_ty new_ty of
680 WARN(True, text (":print failed to calculate the "
681 ++ "improvement for a type")) hsc_env
683 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
684 printForUser stderr alwaysQualify $
685 fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
687 let ic' = extendInteractiveContext
688 (substInteractiveContext ic subst) []
689 return hsc_env{hsc_IC=ic'}
691 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
692 getIdValFromApStack apStack (I# stackDepth) = do
693 case getApStackVal# apStack (stackDepth +# 1#) of
694 -- The +1 is magic! I don't know where it comes
695 -- from, but this makes things line up. --SDM
698 0# -> return Nothing -- AP_STACK not found
699 _ -> return (Just (unsafeCoerce# result))
701 pushResume :: HscEnv -> Resume -> HscEnv
702 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
704 ictxt0 = hsc_IC hsc_env
705 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
707 -- -----------------------------------------------------------------------------
708 -- Abandoning a resume context
710 abandon :: GhcMonad m => m Bool
712 hsc_env <- getSession
713 let ic = hsc_IC hsc_env
714 resume = ic_resume ic
718 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
722 abandonAll :: GhcMonad m => m Bool
724 hsc_env <- getSession
725 let ic = hsc_IC hsc_env
726 resume = ic_resume ic
730 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
731 liftIO $ mapM_ abandon_ rs
734 -- when abandoning a computation we have to
735 -- (a) kill the thread with an async exception, so that the
736 -- computation itself is stopped, and
737 -- (b) fill in the MVar. This step is necessary because any
738 -- thunks that were under evaluation will now be updated
739 -- with the partial computation, which still ends in takeMVar,
740 -- so any attempt to evaluate one of these thunks will block
741 -- unless we fill in the MVar.
742 -- See test break010.
743 abandon_ :: Resume -> IO ()
745 killThread (resumeThreadId r)
746 putMVar (resumeBreakMVar r) ()
748 -- -----------------------------------------------------------------------------
749 -- Bounded list, optimised for repeated cons
751 data BoundedList a = BL
752 {-# UNPACK #-} !Int -- length
753 {-# UNPACK #-} !Int -- bound
755 [a] -- right, list is (left ++ reverse right)
757 nilBL :: Int -> BoundedList a
758 nilBL bound = BL 0 bound [] []
760 consBL :: a -> BoundedList a -> BoundedList a
761 consBL a (BL len bound left right)
762 | len < bound = BL (len+1) bound (a:left) right
763 | null right = BL len bound [a] $! tail (reverse left)
764 | otherwise = BL len bound (a:left) $! tail right
766 toListBL :: BoundedList a -> [a]
767 toListBL (BL _ _ left right) = left ++ reverse right
769 fromListBL :: Int -> [a] -> BoundedList a
770 fromListBL bound l = BL (length l) bound l []
772 -- lenBL (BL len _ _ _) = len
774 -- -----------------------------------------------------------------------------
775 -- | Set the interactive evaluation context.
777 -- Setting the context doesn't throw away any bindings; the bindings
778 -- we've built up in the InteractiveContext simply move to the new
779 -- module. They always shadow anything in scope in the current context.
780 setContext :: GhcMonad m =>
781 [Module] -- ^ entire top level scope of these modules
782 -> [(Module, Maybe (ImportDecl RdrName))] -- ^ exports of these modules
784 setContext toplev_mods other_mods = do
785 hsc_env <- getSession
786 let old_ic = hsc_IC hsc_env
787 hpt = hsc_HPT hsc_env
788 (decls,mods) = partition (isJust . snd) other_mods -- time for tracing
789 export_mods = map fst mods
790 imprt_decls = map noLoc (catMaybes (map snd decls))
792 export_env <- liftIO $ mkExportEnv hsc_env export_mods
794 if null imprt_decls then return emptyGlobalRdrEnv else do
795 let this_mod | null toplev_mods = pRELUDE
796 | otherwise = head toplev_mods
797 liftIO $ hscRnImportDecls hsc_env this_mod imprt_decls
798 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
799 let all_env = foldr plusGlobalRdrEnv (plusGlobalRdrEnv export_env import_env) toplev_envs
800 modifySession $ \_ ->
801 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
802 ic_exports = other_mods,
803 ic_rn_gbl_env = all_env }}
805 -- Make a GlobalRdrEnv based on the exports of the modules only.
806 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
807 mkExportEnv hsc_env mods
808 = do { stuff <- mapM (getModuleExports hsc_env) mods
809 ; let (_msgs, mb_name_sets) = unzip stuff
810 envs = [ availsToGlobalRdrEnv (moduleName mod) avails
811 | (Just avails, mod) <- zip mb_name_sets mods ]
812 ; return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv envs }
814 availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
815 availsToGlobalRdrEnv mod_name avails
816 = mkGlobalRdrEnv (gresFromAvails imp_prov avails)
818 -- We're building a GlobalRdrEnv as if the user imported
819 -- all the specified modules into the global interactive module
820 imp_prov = 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, Maybe (ImportDecl RdrName))])
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 <- liftIO $ hscTcRnGetInfo 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 $ orphNamesOfType $ 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) <- liftIO $ hscParseIdentifier hsc_env str
915 liftIO $ hscTcRnLookupRdrName hsc_env rdr_name
917 -- -----------------------------------------------------------------------------
918 -- Getting the type of an expression
920 -- | Get the type of an expression
921 exprType :: GhcMonad m => String -> m Type
922 exprType expr = withSession $ \hsc_env -> do
923 ty <- liftIO $ hscTcExpr hsc_env expr
924 return $ tidyType emptyTidyEnv ty
926 -- -----------------------------------------------------------------------------
927 -- Getting the kind of a type
929 -- | Get the kind of a type
930 typeKind :: GhcMonad m => String -> m Kind
931 typeKind str = withSession $ \hsc_env -> do
932 liftIO $ hscKcType hsc_env str
934 -----------------------------------------------------------------------------
935 -- cmCompileExpr: compile an expression and deliver an HValue
937 compileExpr :: GhcMonad m => String -> m HValue
938 compileExpr expr = withSession $ \hsc_env -> do
939 Just (ids, hval) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
941 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
944 ([_],[hv]) -> return hv
945 _ -> panic "compileExpr"
947 -- -----------------------------------------------------------------------------
948 -- Compile an expression into a dynamic
950 dynCompileExpr :: GhcMonad m => String -> m Dynamic
951 dynCompileExpr expr = do
952 (full,exports) <- getContext
955 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
957 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
958 Just (ids, hvals) <- withSession $ \hsc_env ->
959 liftIO $ hscStmt hsc_env stmt
960 setContext full exports
961 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
963 (_:[], v:[]) -> return v
964 _ -> panic "dynCompileExpr"
966 -----------------------------------------------------------------------------
967 -- show a module and it's source/object filenames
969 showModule :: GhcMonad m => ModSummary -> m String
970 showModule mod_summary =
971 withSession $ \hsc_env -> do
972 interpreted <- isModuleInterpreted mod_summary
973 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
975 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
976 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
977 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
978 Nothing -> panic "missing linkable"
979 Just mod_info -> return (not obj_linkable)
981 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
983 ----------------------------------------------------------------------------
986 obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
987 obtainTermFromVal hsc_env bound force ty x =
988 cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
990 obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
991 obtainTermFromId hsc_env bound force id = do
992 hv <- Linker.getHValue hsc_env (varName id)
993 cvObtainTerm hsc_env bound force (idType id) hv
995 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
996 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
997 reconstructType hsc_env bound id = do
998 hv <- Linker.getHValue hsc_env (varName id)
999 cvReconstructType hsc_env bound (idType id) hv
1001 mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
1002 mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk