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,
31 compileExpr, dynCompileExpr,
33 Term(..), obtainTermFromId, obtainTermFromVal, reconstructType,
34 skolemiseSubst, skolemiseTy
40 #include "HsVersions.h"
42 import HscMain hiding (compileExpr)
45 import RnNames ( gresFromAvails )
48 import TcType hiding( typeKind )
51 import Name hiding ( varName )
69 import RtClosureInspect
75 import System.Directory
77 import Data.List (find)
84 import Control.Concurrent
85 import Data.List (sortBy)
86 -- import Foreign.StablePtr
89 -- -----------------------------------------------------------------------------
90 -- running a statement interactively
93 = RunOk [Name] -- ^ names bound by this evaluation
94 | RunFailed -- ^ statement failed compilation
95 | RunException SomeException -- ^ statement raised an exception
96 | RunBreak ThreadId [Name] (Maybe BreakInfo)
99 = Break Bool HValue BreakInfo ThreadId
100 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
101 | Complete (Either SomeException [HValue])
102 -- ^ the computation completed with either an exception or a value
106 resumeStmt :: String, -- the original statement
107 resumeThreadId :: ThreadId, -- thread running the computation
108 resumeBreakMVar :: MVar (),
109 resumeStatMVar :: MVar Status,
110 resumeBindings :: ([Id], TyVarSet),
111 resumeFinalIds :: [Id], -- [Id] to bind on completion
112 resumeApStack :: HValue, -- The object from which we can get
113 -- value of the free variables.
114 resumeBreakInfo :: Maybe BreakInfo,
115 -- the breakpoint we stopped at
116 -- (Nothing <=> exception)
117 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
118 -- to fetch the ModDetails & ModBreaks
120 resumeHistory :: [History],
121 resumeHistoryIx :: Int -- 0 <==> at the top of the history
124 getResumeContext :: GhcMonad m => m [Resume]
125 getResumeContext = withSession (return . ic_resume . hsc_IC)
132 isStep :: SingleStep -> Bool
133 isStep RunToCompletion = False
138 historyApStack :: HValue,
139 historyBreakInfo :: BreakInfo,
140 historyEnclosingDecl :: Id
141 -- ^^ A cache of the enclosing top level declaration, for convenience
144 mkHistory :: HscEnv -> HValue -> BreakInfo -> History
145 mkHistory hsc_env hval bi = let
146 h = History hval bi decl
147 decl = findEnclosingDecl hsc_env (getHistoryModule h)
148 (getHistorySpan hsc_env h)
151 getHistoryModule :: History -> Module
152 getHistoryModule = breakInfo_module . historyBreakInfo
154 getHistorySpan :: HscEnv -> History -> SrcSpan
155 getHistorySpan hsc_env hist =
156 let inf = historyBreakInfo hist
157 num = breakInfo_number inf
158 in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
159 Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
160 _ -> panic "getHistorySpan"
162 getModBreaks :: HomeModInfo -> ModBreaks
164 | Just linkable <- hm_linkable hmi,
165 [BCOs _ modBreaks] <- linkableUnlinked linkable
168 = emptyModBreaks -- probably object code
170 {- | Finds the enclosing top level function name -}
171 -- ToDo: a better way to do this would be to keep hold of the decl_path computed
172 -- by the coverage pass, which gives the list of lexically-enclosing bindings
174 findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
175 findEnclosingDecl hsc_env mod span =
176 case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
177 Nothing -> panic "findEnclosingDecl"
179 globals = typeEnvIds (md_types (hm_details hmi))
181 find (\id -> let n = idName id in
182 nameSrcSpan n < span && isExternalName n)
183 (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
187 -- | Run a statement in the current interactive context. Statement
188 -- may bind multple values.
189 runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
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 <- hscStmt hsc_env' expr
205 Nothing -> return RunFailed -- empty statement / comment
207 Just (ids, hval) -> do
208 -- XXX: This is the only place we can print warnings before the
209 -- result. Is this really the right thing to do? It's fine for
210 -- GHCi, but what's correct for other GHC API clients? We could
211 -- introduce a callback argument.
213 liftIO $ printBagOfWarnings dflags' warns
218 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
219 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
220 liftIO $ sandboxIO dflags' statusMVar thing_to_run
222 let ic = hsc_IC hsc_env
223 bindings = (ic_tmp_ids ic, ic_tyvars ic)
227 traceRunStatus expr bindings ids
228 breakMVar statusMVar status emptyHistory
230 handleRunStatus expr bindings ids
231 breakMVar statusMVar status emptyHistory
233 withVirtualCWD :: GhcMonad m => m a -> m a
234 withVirtualCWD m = do
235 hsc_env <- getSession
236 let ic = hsc_IC hsc_env
239 dir <- liftIO $ getCurrentDirectory
241 Just dir -> liftIO $ setCurrentDirectory dir
245 reset_cwd orig_dir = do
246 virt_dir <- liftIO $ getCurrentDirectory
247 hsc_env <- getSession
248 let old_IC = hsc_IC hsc_env
249 setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
250 liftIO $ setCurrentDirectory orig_dir
252 gbracket set_cwd reset_cwd $ \_ -> m
255 emptyHistory :: BoundedList History
256 emptyHistory = nilBL 50 -- keep a log of length 50
258 handleRunStatus :: GhcMonad m =>
259 String-> ([Id], TyVarSet) -> [Id]
260 -> MVar () -> MVar Status -> Status -> BoundedList History
262 handleRunStatus expr bindings final_ids breakMVar statusMVar status
265 -- did we hit a breakpoint or did we complete?
266 (Break is_exception apStack info tid) -> do
267 hsc_env <- getSession
268 let mb_info | is_exception = Nothing
269 | otherwise = Just info
270 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
273 resume = Resume expr tid breakMVar statusMVar
274 bindings final_ids apStack mb_info span
276 hsc_env2 = pushResume hsc_env1 resume
278 modifySession (\_ -> hsc_env2)
279 return (RunBreak tid names mb_info)
280 (Complete either_hvals) ->
282 Left e -> return (RunException e)
284 hsc_env <- getSession
285 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
286 final_ids emptyVarSet
287 -- the bound Ids never have any free TyVars
288 final_names = map idName final_ids
289 liftIO $ Linker.extendLinkEnv (zip final_names hvals)
290 hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
291 modifySession (\_ -> hsc_env')
292 return (RunOk final_names)
294 traceRunStatus :: GhcMonad m =>
295 String -> ([Id], TyVarSet) -> [Id]
296 -> MVar () -> MVar Status -> Status -> BoundedList History
298 traceRunStatus expr bindings final_ids
299 breakMVar statusMVar status history = do
300 hsc_env <- getSession
302 -- when tracing, if we hit a breakpoint that is not explicitly
303 -- enabled, then we just log the event in the history and continue.
304 (Break is_exception apStack info tid) | not is_exception -> do
305 b <- liftIO $ isBreakEnabled hsc_env info
309 let history' = mkHistory hsc_env apStack info `consBL` history
310 -- probably better make history strict here, otherwise
311 -- our BoundedList will be pointless.
312 _ <- liftIO $ evaluate history'
314 withBreakAction True (hsc_dflags hsc_env)
315 breakMVar statusMVar $ do
316 liftIO $ withInterruptsSentTo tid $ do
317 putMVar breakMVar () -- awaken the stopped thread
318 takeMVar statusMVar -- and wait for the result
319 traceRunStatus expr bindings final_ids
320 breakMVar statusMVar status history'
324 handle_normally = handleRunStatus expr bindings final_ids
325 breakMVar statusMVar status history
328 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
329 isBreakEnabled hsc_env inf =
330 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
332 w <- getBreak (modBreaks_flags (getModBreaks hmi))
333 (breakInfo_number inf)
334 case w of Just n -> return (n /= 0); _other -> return False
339 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
340 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
343 setStepFlag = poke stepFlag 1
344 resetStepFlag :: IO ()
345 resetStepFlag = poke stepFlag 0
347 -- this points to the IO action that is executed when a breakpoint is hit
348 foreign import ccall "&rts_breakpoint_io_action"
349 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
351 -- When running a computation, we redirect ^C exceptions to the running
352 -- thread. ToDo: we might want a way to continue even if the target
353 -- thread doesn't die when it receives the exception... "this thread
354 -- is not responding".
356 -- Careful here: there may be ^C exceptions flying around, so we start the new
357 -- thread blocked (forkIO inherits block from the parent, #1048), and unblock
358 -- only while we execute the user's code. We can't afford to lose the final
359 -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
360 sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
361 sandboxIO dflags statusMVar thing =
362 block $ do -- fork starts blocked
363 id <- forkIO $ do res <- Exception.try (unblock $ rethrow dflags thing)
364 putMVar statusMVar (Complete res) -- empty: can't block
365 withInterruptsSentTo id $ takeMVar statusMVar
368 -- We want to turn ^C into a break when -fbreak-on-exception is on,
369 -- but it's an async exception and we only break for sync exceptions.
370 -- Idea: if we catch and re-throw it, then the re-throw will trigger
371 -- a break. Great - but we don't want to re-throw all exceptions, because
372 -- then we'll get a double break for ordinary sync exceptions (you'd have
373 -- to :continue twice, which looks strange). So if the exception is
374 -- not "Interrupted", we unset the exception flag before throwing.
376 rethrow :: DynFlags -> IO a -> IO a
377 rethrow dflags io = Exception.catch io $ \se -> do
378 -- If -fbreak-on-error, we break unconditionally,
379 -- but with care of not breaking twice
380 if dopt Opt_BreakOnError dflags &&
381 not (dopt Opt_BreakOnException dflags)
382 then poke exceptionFlag 1
383 else case fromException se of
384 -- If it is a "UserInterrupt" exception, we allow
385 -- a possible break by way of -fbreak-on-exception
386 Just UserInterrupt -> return ()
387 -- In any other case, we don't want to break
388 _ -> poke exceptionFlag 0
392 withInterruptsSentTo :: ThreadId -> IO r -> IO r
393 withInterruptsSentTo thread get_result = do
394 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
395 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
398 -- This function sets up the interpreter for catching breakpoints, and
399 -- resets everything when the computation has stopped running. This
400 -- is a not-very-good way to ensure that only the interactive
401 -- evaluation should generate breakpoints.
402 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
403 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
404 withBreakAction step dflags breakMVar statusMVar act
405 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
408 stablePtr <- newStablePtr onBreak
409 poke breakPointIOAction stablePtr
410 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
411 when step $ setStepFlag
413 -- Breaking on exceptions is not enabled by default, since it
414 -- might be a bit surprising. The exception flag is turned off
415 -- as soon as it is hit, or in resetBreakAction below.
417 onBreak is_exception info apStack = do
419 putMVar statusMVar (Break is_exception apStack info tid)
422 resetBreakAction stablePtr = do
423 poke breakPointIOAction noBreakStablePtr
426 freeStablePtr stablePtr
428 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
429 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
431 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
432 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
433 noBreakAction True _ _ = return () -- exception: just continue
435 resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
436 resume canLogSpan step
438 hsc_env <- getSession
439 let ic = hsc_IC hsc_env
440 resume = ic_resume ic
443 [] -> ghcError (ProgramError "not stopped at a breakpoint")
445 -- unbind the temporary locals by restoring the TypeEnv from
446 -- before the breakpoint, and drop this Resume from the
447 -- InteractiveContext.
448 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
449 ic' = ic { ic_tmp_ids = resume_tmp_ids,
450 ic_tyvars = resume_tyvars,
452 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
454 -- remove any bindings created since the breakpoint from the
455 -- linker's environment
456 let new_names = map idName (filter (`notElem` resume_tmp_ids)
458 liftIO $ Linker.deleteFromLinkEnv new_names
460 when (isStep step) $ liftIO setStepFlag
462 Resume expr tid breakMVar statusMVar bindings
463 final_ids apStack info span hist _ -> do
465 withBreakAction (isStep step) (hsc_dflags hsc_env)
466 breakMVar statusMVar $ do
467 status <- liftIO $ withInterruptsSentTo tid $ do
469 -- this awakens the stopped thread...
471 -- and wait for the result
472 let prevHistoryLst = fromListBL 50 hist
474 Nothing -> prevHistoryLst
476 | not $canLogSpan span -> prevHistoryLst
477 | otherwise -> mkHistory hsc_env apStack i `consBL`
481 traceRunStatus expr bindings final_ids
482 breakMVar statusMVar status hist'
484 handleRunStatus expr bindings final_ids
485 breakMVar statusMVar status hist'
487 back :: GhcMonad m => m ([Name], Int, SrcSpan)
490 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
491 forward = moveHist (subtract 1)
493 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
495 hsc_env <- getSession
496 case ic_resume (hsc_IC hsc_env) of
497 [] -> ghcError (ProgramError "not stopped at a breakpoint")
499 let ix = resumeHistoryIx r
500 history = resumeHistory r
503 when (new_ix > length history) $
504 ghcError (ProgramError "no more logged breakpoints")
506 ghcError (ProgramError "already at the beginning of the history")
509 update_ic apStack mb_info = do
510 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
512 let ic = hsc_IC hsc_env1
513 r' = r { resumeHistoryIx = new_ix }
514 ic' = ic { ic_resume = r':rs }
516 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
518 return (names, new_ix, span)
520 -- careful: we want apStack to be the AP_STACK itself, not a thunk
521 -- around it, hence the cases are carefully constructed below to
522 -- make this the case. ToDo: this is v. fragile, do something better.
525 Resume { resumeApStack = apStack,
526 resumeBreakInfo = mb_info } ->
527 update_ic apStack mb_info
528 else case history !! (new_ix - 1) of
529 History apStack info _ ->
530 update_ic apStack (Just info)
532 -- -----------------------------------------------------------------------------
533 -- After stopping at a breakpoint, add free variables to the environment
534 result_fs :: FastString
535 result_fs = fsLit "_result"
537 bindLocalsAtBreakpoint
541 -> IO (HscEnv, [Name], SrcSpan)
543 -- Nothing case: we stopped when an exception was raised, not at a
544 -- breakpoint. We have no location information or local variables to
545 -- bind, all we can do is bind a local variable to the exception
547 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
548 let exn_fs = fsLit "_exception"
549 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
551 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
552 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
553 exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
554 new_tyvars = unitVarSet e_tyvar
556 ictxt0 = hsc_IC hsc_env
557 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
559 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
561 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
562 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
564 -- Just case: we stopped at a breakpoint, we have information about the location
565 -- of the breakpoint and the free variables of the expression.
566 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
569 mod_name = moduleName (breakInfo_module info)
570 hmi = expectJust "bindLocalsAtBreakpoint" $
571 lookupUFM (hsc_HPT hsc_env) mod_name
572 breaks = getModBreaks hmi
573 index = breakInfo_number info
574 vars = breakInfo_vars info
575 result_ty = breakInfo_resty info
576 occs = modBreaks_vars breaks ! index
577 span = modBreaks_locs breaks ! index
579 -- filter out any unboxed ids; we can't bind these at the prompt
580 let pointers = filter (\(id,_) -> isPointer id) vars
581 isPointer id | PtrRep <- idPrimRep id = True
584 let (ids, offsets) = unzip pointers
586 -- It might be that getIdValFromApStack fails, because the AP_STACK
587 -- has been accidentally evaluated, or something else has gone wrong.
588 -- So that we don't fall over in a heap when this happens, just don't
589 -- bind any free variables instead, and we emit a warning.
590 mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
591 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
592 when (any isNothing mb_hValues) $
593 debugTraceMsg (hsc_dflags hsc_env) 1 $
594 text "Warning: _result has been evaluated, some bindings have been lost"
596 new_ids <- zipWithM mkNewId occs filtered_ids
597 let names = map idName new_ids
599 -- make an Id for _result. We use the Unique of the FastString "_result";
600 -- we don't care about uniqueness here, because there will only be one
601 -- _result in scope at any time.
602 let result_name = mkInternalName (getUnique result_fs)
603 (mkVarOccFS result_fs) span
604 result_id = Id.mkVanillaGlobal result_name result_ty
606 -- for each Id we're about to bind in the local envt:
607 -- - skolemise the type variables in its type, so they can't
608 -- be randomly unified with other types. These type variables
609 -- can only be resolved by type reconstruction in RtClosureInspect
610 -- - tidy the type variables
611 -- - globalise the Id (Ids are supposed to be Global, apparently).
613 let result_ok = isPointer result_id
614 && not (isUnboxedTupleType (idType result_id))
616 all_ids | result_ok = result_id : new_ids
617 | otherwise = new_ids
618 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
619 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
620 new_tyvars = unionVarSets tyvarss
621 final_ids = zipWith setIdType all_ids tidy_tys
622 ictxt0 = hsc_IC hsc_env
623 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
625 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
626 when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
627 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
628 return (hsc_env1, if result_ok then result_name:names else names, span)
630 mkNewId :: OccName -> Id -> IO Id
632 us <- mkSplitUniqSupply 'I'
633 -- we need a fresh Unique for each Id we bind, because the linker
634 -- state is single-threaded and otherwise we'd spam old bindings
635 -- whenever we stop at a breakpoint. The InteractveContext is properly
636 -- saved/restored, but not the linker state. See #1743, test break026.
638 uniq = uniqFromSupply us
639 loc = nameSrcSpan (idName id)
640 name = mkInternalName uniq occ loc
642 new_id = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
645 rttiEnvironment :: HscEnv -> IO HscEnv
646 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
647 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
648 incompletelyTypedIds =
651 , (occNameFS.nameOccName.idName) id /= result_fs]
652 hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
655 noSkolems = null . filter isSkolemTyVar . varSetElems . tyVarsOfType . idType
656 improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
657 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
658 Just id = find (\i -> idName i == name) tmp_ids
662 mb_new_ty <- reconstructType hsc_env 10 id
663 let old_ty = idType id
665 Nothing -> return hsc_env
667 mb_subst <- improveRTTIType hsc_env old_ty new_ty
670 WARN(True, text (":print failed to calculate the "
671 ++ "improvement for a type")) hsc_env
673 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
674 printForUser stderr alwaysQualify $
675 fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
677 let (subst', skols) = skolemiseSubst subst
678 ic' = extendInteractiveContext
679 (substInteractiveContext ic subst') [] skols
680 return hsc_env{hsc_IC=ic'}
682 skolemiseSubst :: TvSubst -> (TvSubst, TyVarSet)
683 skolemiseSubst subst = let
684 varenv = getTvSubstEnv subst
685 all_together = mapVarEnv skolemiseTy varenv
686 (varenv', skol_vars) = ( mapVarEnv fst all_together
687 , map snd (varEnvElts all_together))
688 in (subst `setTvSubstEnv` varenv', unionVarSets skol_vars)
691 skolemiseTy :: Type -> (Type, TyVarSet)
692 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
693 where env = mkVarEnv (zip tyvars new_tyvar_tys)
694 subst = mkTvSubst emptyInScopeSet env
695 tyvars = varSetElems (tyVarsOfType ty)
696 new_tyvars = map skolemiseTyVar tyvars
697 new_tyvar_tys = map mkTyVarTy new_tyvars
699 skolemiseTyVar :: TyVar -> TyVar
700 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
701 (SkolemTv RuntimeUnkSkol)
703 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
704 getIdValFromApStack apStack (I# stackDepth) = do
705 case getApStackVal# apStack (stackDepth +# 1#) of
706 -- The +1 is magic! I don't know where it comes
707 -- from, but this makes things line up. --SDM
710 0# -> return Nothing -- AP_STACK not found
711 _ -> return (Just (unsafeCoerce# result))
713 pushResume :: HscEnv -> Resume -> HscEnv
714 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
716 ictxt0 = hsc_IC hsc_env
717 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
719 -- -----------------------------------------------------------------------------
720 -- Abandoning a resume context
722 abandon :: 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 = rs } }
734 abandonAll :: GhcMonad m => m Bool
736 hsc_env <- getSession
737 let ic = hsc_IC hsc_env
738 resume = ic_resume ic
742 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
743 liftIO $ mapM_ abandon_ rs
746 -- when abandoning a computation we have to
747 -- (a) kill the thread with an async exception, so that the
748 -- computation itself is stopped, and
749 -- (b) fill in the MVar. This step is necessary because any
750 -- thunks that were under evaluation will now be updated
751 -- with the partial computation, which still ends in takeMVar,
752 -- so any attempt to evaluate one of these thunks will block
753 -- unless we fill in the MVar.
754 -- See test break010.
755 abandon_ :: Resume -> IO ()
757 killThread (resumeThreadId r)
758 putMVar (resumeBreakMVar r) ()
760 -- -----------------------------------------------------------------------------
761 -- Bounded list, optimised for repeated cons
763 data BoundedList a = BL
764 {-# UNPACK #-} !Int -- length
765 {-# UNPACK #-} !Int -- bound
767 [a] -- right, list is (left ++ reverse right)
769 nilBL :: Int -> BoundedList a
770 nilBL bound = BL 0 bound [] []
772 consBL :: a -> BoundedList a -> BoundedList a
773 consBL a (BL len bound left right)
774 | len < bound = BL (len+1) bound (a:left) right
775 | null right = BL len bound [a] $! tail (reverse left)
776 | otherwise = BL len bound (a:left) $! tail right
778 toListBL :: BoundedList a -> [a]
779 toListBL (BL _ _ left right) = left ++ reverse right
781 fromListBL :: Int -> [a] -> BoundedList a
782 fromListBL bound l = BL (length l) bound l []
784 -- lenBL (BL len _ _ _) = len
786 -- -----------------------------------------------------------------------------
787 -- | Set the interactive evaluation context.
789 -- Setting the context doesn't throw away any bindings; the bindings
790 -- we've built up in the InteractiveContext simply move to the new
791 -- module. They always shadow anything in scope in the current context.
792 setContext :: GhcMonad m =>
793 [Module] -- ^ entire top level scope of these modules
794 -> [Module] -- ^ exports only of these modules
796 setContext toplev_mods export_mods = do
797 hsc_env <- getSession
798 let old_ic = hsc_IC hsc_env
799 hpt = hsc_HPT hsc_env
801 export_env <- liftIO $ mkExportEnv hsc_env export_mods
802 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
803 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
804 modifySession $ \_ ->
805 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
806 ic_exports = export_mods,
807 ic_rn_gbl_env = all_env }}
809 -- Make a GlobalRdrEnv based on the exports of the modules only.
810 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
811 mkExportEnv hsc_env mods
812 = do { stuff <- mapM (getModuleExports hsc_env) mods
813 ; let (_msgs, mb_name_sets) = unzip stuff
814 envs = [ availsToGlobalRdrEnv (moduleName mod) avails
815 | (Just avails, mod) <- zip mb_name_sets mods ]
816 ; return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv envs }
818 availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
819 availsToGlobalRdrEnv mod_name avails
820 = mkGlobalRdrEnv (gresFromAvails imp_prov avails)
822 -- We're building a GlobalRdrEnv as if the user imported
823 -- all the specified modules into the global interactive module
824 imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
825 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
827 is_dloc = srcLocSpan interactiveSrcLoc }
829 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
831 = case lookupUFM hpt (moduleName modl) of
832 Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
833 showSDoc (ppr modl)))
835 case mi_globals (hm_iface details) of
837 ghcError (ProgramError ("mkTopLevEnv: not interpreted "
838 ++ showSDoc (ppr modl)))
839 Just env -> return env
841 -- | Get the interactive evaluation context, consisting of a pair of the
842 -- set of modules from which we take the full top-level scope, and the set
843 -- of modules from which we take just the exports respectively.
844 getContext :: GhcMonad m => m ([Module],[Module])
845 getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
846 return (ic_toplev_scope ic, ic_exports ic)
848 -- | Returns @True@ if the specified module is interpreted, and hence has
849 -- its full top-level scope available.
850 moduleIsInterpreted :: GhcMonad m => Module -> m Bool
851 moduleIsInterpreted modl = withSession $ \h ->
852 if modulePackageId modl /= thisPackage (hsc_dflags h)
854 else case lookupUFM (hsc_HPT h) (moduleName modl) of
855 Just details -> return (isJust (mi_globals (hm_iface details)))
856 _not_a_home_module -> return False
858 -- | Looks up an identifier in the current interactive context (for :info)
859 -- Filter the instances by the ones whose tycons (or clases resp)
860 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
861 -- The exact choice of which ones to show, and which to hide, is a judgement call.
863 getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance]))
865 = withSession $ \hsc_env ->
866 do mb_stuff <- ioMsg $ tcRnGetInfo hsc_env name
868 Nothing -> return Nothing
869 Just (thing, fixity, ispecs) -> do
870 let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
871 return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
873 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
874 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
875 where -- A name is ok if it's in the rdr_env,
876 -- whether qualified or not
877 ok n | n == name = True -- The one we looked for in the first place!
878 | isBuiltInSyntax n = True
879 | isExternalName n = any ((== n) . gre_name)
880 (lookupGRE_Name rdr_env n)
883 -- | Returns all names in scope in the current interactive context
884 getNamesInScope :: GhcMonad m => m [Name]
885 getNamesInScope = withSession $ \hsc_env -> do
886 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
888 getRdrNamesInScope :: GhcMonad m => m [RdrName]
889 getRdrNamesInScope = withSession $ \hsc_env -> do
892 gbl_rdrenv = ic_rn_gbl_env ic
894 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
895 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
897 return (gbl_names ++ lcl_names)
900 -- ToDo: move to RdrName
901 greToRdrNames :: GlobalRdrElt -> [RdrName]
902 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
905 Imported specs -> concat (map do_spec (map is_decl specs))
907 occ = nameOccName name
910 | is_qual decl_spec = [qual]
911 | otherwise = [unqual,qual]
912 where qual = Qual (is_as decl_spec) occ
914 -- | Parses a string as an identifier, and returns the list of 'Name's that
915 -- the identifier can refer to in the current interactive context.
916 parseName :: GhcMonad m => String -> m [Name]
917 parseName str = withSession $ \hsc_env -> do
918 (L _ rdr_name) <- hscParseIdentifier (hsc_dflags hsc_env) str
919 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
921 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
922 -- entity known to GHC, including 'Name's defined using 'runStmt'.
923 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
924 lookupName name = withSession $ \hsc_env -> do
925 mb_tything <- ioMsg $ tcRnLookupName hsc_env name
927 -- XXX: calls panic in some circumstances; is that ok?
929 -- -----------------------------------------------------------------------------
930 -- Getting the type of an expression
932 -- | Get the type of an expression
933 exprType :: GhcMonad m => String -> m Type
934 exprType expr = withSession $ \hsc_env -> do
935 ty <- hscTcExpr hsc_env expr
936 return $ tidyType emptyTidyEnv ty
938 -- -----------------------------------------------------------------------------
939 -- Getting the kind of a type
941 -- | Get the kind of a type
942 typeKind :: GhcMonad m => String -> m Kind
943 typeKind str = withSession $ \hsc_env -> do
944 hscKcType hsc_env str
946 -----------------------------------------------------------------------------
947 -- cmCompileExpr: compile an expression and deliver an HValue
949 compileExpr :: GhcMonad m => String -> m HValue
950 compileExpr expr = withSession $ \hsc_env -> do
951 Just (ids, hval) <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
953 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
956 ([_],[hv]) -> return hv
957 _ -> panic "compileExpr"
959 -- -----------------------------------------------------------------------------
960 -- Compile an expression into a dynamic
962 dynCompileExpr :: GhcMonad m => String -> m Dynamic
963 dynCompileExpr expr = do
964 (full,exports) <- getContext
967 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
969 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
970 Just (ids, hvals) <- withSession (flip hscStmt stmt)
971 setContext full exports
972 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
974 (_:[], v:[]) -> return v
975 _ -> panic "dynCompileExpr"
977 -----------------------------------------------------------------------------
978 -- show a module and it's source/object filenames
980 showModule :: GhcMonad m => ModSummary -> m String
981 showModule mod_summary =
982 withSession $ \hsc_env -> do
983 interpreted <- isModuleInterpreted mod_summary
984 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
986 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
987 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
988 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
989 Nothing -> panic "missing linkable"
990 Just mod_info -> return (not obj_linkable)
992 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
994 ----------------------------------------------------------------------------
997 obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
998 obtainTermFromVal hsc_env bound force ty x =
999 cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
1001 obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
1002 obtainTermFromId hsc_env bound force id = do
1003 hv <- Linker.getHValue hsc_env (varName id)
1004 cvObtainTerm hsc_env bound force (idType id) hv
1006 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
1007 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
1008 reconstructType hsc_env bound id = do
1009 hv <- Linker.getHValue hsc_env (varName id)
1010 cvReconstructType hsc_env bound (idType id) hv