1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005-2007
5 -- Running statements interactively
7 -- -----------------------------------------------------------------------------
9 module InteractiveEval (
11 RunResult(..), Status(..), Resume(..), History(..),
12 runStmt, parseImportDecl, SingleStep(..),
20 setContext, getContext,
31 compileExpr, dynCompileExpr,
33 Term(..), obtainTermFromId, obtainTermFromVal, reconstructType,
34 skolemiseSubst, skolemiseTy
40 #include "HsVersions.h"
42 import HscMain hiding (compileExpr)
43 import HsSyn (ImportDecl)
46 import TcRnMonad (initTc)
47 import RnNames (gresFromAvails, rnImports)
50 import TcType hiding( typeKind )
53 import Name hiding ( varName )
56 import PrelNames (pRELUDE)
72 import RtClosureInspect
78 import System.Directory
80 import Data.List (find, partition)
87 import Control.Concurrent
88 import Data.List (sortBy)
89 -- import Foreign.StablePtr
92 -- -----------------------------------------------------------------------------
93 -- running a statement interactively
96 = RunOk [Name] -- ^ names bound by this evaluation
97 | RunFailed -- ^ statement failed compilation
98 | RunException SomeException -- ^ statement raised an exception
99 | RunBreak ThreadId [Name] (Maybe BreakInfo)
102 = Break Bool HValue BreakInfo ThreadId
103 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
104 | Complete (Either SomeException [HValue])
105 -- ^ the computation completed with either an exception or a value
109 resumeStmt :: String, -- the original statement
110 resumeThreadId :: ThreadId, -- thread running the computation
111 resumeBreakMVar :: MVar (),
112 resumeStatMVar :: MVar Status,
113 resumeBindings :: ([Id], TyVarSet),
114 resumeFinalIds :: [Id], -- [Id] to bind on completion
115 resumeApStack :: HValue, -- The object from which we can get
116 -- value of the free variables.
117 resumeBreakInfo :: Maybe BreakInfo,
118 -- the breakpoint we stopped at
119 -- (Nothing <=> exception)
120 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
121 -- to fetch the ModDetails & ModBreaks
123 resumeHistory :: [History],
124 resumeHistoryIx :: Int -- 0 <==> at the top of the history
127 getResumeContext :: GhcMonad m => m [Resume]
128 getResumeContext = withSession (return . ic_resume . hsc_IC)
135 isStep :: SingleStep -> Bool
136 isStep RunToCompletion = False
141 historyApStack :: HValue,
142 historyBreakInfo :: BreakInfo,
143 historyEnclosingDecl :: Id
144 -- ^^ A cache of the enclosing top level declaration, for convenience
147 mkHistory :: HscEnv -> HValue -> BreakInfo -> History
148 mkHistory hsc_env hval bi = let
149 h = History hval bi decl
150 decl = findEnclosingDecl hsc_env (getHistoryModule h)
151 (getHistorySpan hsc_env h)
154 getHistoryModule :: History -> Module
155 getHistoryModule = breakInfo_module . historyBreakInfo
157 getHistorySpan :: HscEnv -> History -> SrcSpan
158 getHistorySpan hsc_env hist =
159 let inf = historyBreakInfo hist
160 num = breakInfo_number inf
161 in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
162 Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
163 _ -> panic "getHistorySpan"
165 getModBreaks :: HomeModInfo -> ModBreaks
167 | Just linkable <- hm_linkable hmi,
168 [BCOs _ modBreaks] <- linkableUnlinked linkable
171 = emptyModBreaks -- probably object code
173 {- | Finds the enclosing top level function name -}
174 -- ToDo: a better way to do this would be to keep hold of the decl_path computed
175 -- by the coverage pass, which gives the list of lexically-enclosing bindings
177 findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
178 findEnclosingDecl hsc_env mod span =
179 case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
180 Nothing -> panic "findEnclosingDecl"
182 globals = typeEnvIds (md_types (hm_details hmi))
184 find (\id -> let n = idName id in
185 nameSrcSpan n < span && isExternalName n)
186 (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
190 -- | Run a statement in the current interactive context. Statement
191 -- may bind multple values.
192 runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
195 hsc_env <- getSession
197 breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
198 statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
200 -- Turn off -fwarn-unused-bindings when running a statement, to hide
201 -- warnings about the implicit bindings we introduce.
202 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
203 hsc_env' = hsc_env{ hsc_dflags = dflags' }
205 r <- hscStmt hsc_env' expr
208 Nothing -> return RunFailed -- empty statement / comment
210 Just (ids, hval) -> do
211 -- XXX: This is the only place we can print warnings before the
212 -- result. Is this really the right thing to do? It's fine for
213 -- GHCi, but what's correct for other GHC API clients? We could
214 -- introduce a callback argument.
216 liftIO $ printBagOfWarnings dflags' warns
221 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
222 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
223 liftIO $ sandboxIO dflags' statusMVar thing_to_run
225 let ic = hsc_IC hsc_env
226 bindings = (ic_tmp_ids ic, ic_tyvars ic)
230 traceRunStatus expr bindings ids
231 breakMVar statusMVar status emptyHistory
233 handleRunStatus expr bindings ids
234 breakMVar statusMVar status emptyHistory
236 withVirtualCWD :: GhcMonad m => m a -> m a
237 withVirtualCWD m = do
238 hsc_env <- getSession
239 let ic = hsc_IC hsc_env
242 dir <- liftIO $ getCurrentDirectory
244 Just dir -> liftIO $ setCurrentDirectory dir
248 reset_cwd orig_dir = do
249 virt_dir <- liftIO $ getCurrentDirectory
250 hsc_env <- getSession
251 let old_IC = hsc_IC hsc_env
252 setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
253 liftIO $ setCurrentDirectory orig_dir
255 gbracket set_cwd reset_cwd $ \_ -> m
257 parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
258 parseImportDecl expr = withSession $ \hsc_env -> hscImport hsc_env expr
260 emptyHistory :: BoundedList History
261 emptyHistory = nilBL 50 -- keep a log of length 50
263 handleRunStatus :: GhcMonad m =>
264 String-> ([Id], TyVarSet) -> [Id]
265 -> MVar () -> MVar Status -> Status -> BoundedList History
267 handleRunStatus expr bindings final_ids breakMVar statusMVar status
270 -- did we hit a breakpoint or did we complete?
271 (Break is_exception apStack info tid) -> do
272 hsc_env <- getSession
273 let mb_info | is_exception = Nothing
274 | otherwise = Just info
275 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
278 resume = Resume expr tid breakMVar statusMVar
279 bindings final_ids apStack mb_info span
281 hsc_env2 = pushResume hsc_env1 resume
283 modifySession (\_ -> hsc_env2)
284 return (RunBreak tid names mb_info)
285 (Complete either_hvals) ->
287 Left e -> return (RunException e)
289 hsc_env <- getSession
290 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
291 final_ids emptyVarSet
292 -- the bound Ids never have any free TyVars
293 final_names = map idName final_ids
294 liftIO $ Linker.extendLinkEnv (zip final_names hvals)
295 hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
296 modifySession (\_ -> hsc_env')
297 return (RunOk final_names)
299 traceRunStatus :: GhcMonad m =>
300 String -> ([Id], TyVarSet) -> [Id]
301 -> MVar () -> MVar Status -> Status -> BoundedList History
303 traceRunStatus expr bindings final_ids
304 breakMVar statusMVar status history = do
305 hsc_env <- getSession
307 -- when tracing, if we hit a breakpoint that is not explicitly
308 -- enabled, then we just log the event in the history and continue.
309 (Break is_exception apStack info tid) | not is_exception -> do
310 b <- liftIO $ isBreakEnabled hsc_env info
314 let history' = mkHistory hsc_env apStack info `consBL` history
315 -- probably better make history strict here, otherwise
316 -- our BoundedList will be pointless.
317 _ <- liftIO $ evaluate history'
319 withBreakAction True (hsc_dflags hsc_env)
320 breakMVar statusMVar $ do
321 liftIO $ withInterruptsSentTo tid $ do
322 putMVar breakMVar () -- awaken the stopped thread
323 takeMVar statusMVar -- and wait for the result
324 traceRunStatus expr bindings final_ids
325 breakMVar statusMVar status history'
329 handle_normally = handleRunStatus expr bindings final_ids
330 breakMVar statusMVar status history
333 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
334 isBreakEnabled hsc_env inf =
335 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
337 w <- getBreak (modBreaks_flags (getModBreaks hmi))
338 (breakInfo_number inf)
339 case w of Just n -> return (n /= 0); _other -> return False
344 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
345 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
348 setStepFlag = poke stepFlag 1
349 resetStepFlag :: IO ()
350 resetStepFlag = poke stepFlag 0
352 -- this points to the IO action that is executed when a breakpoint is hit
353 foreign import ccall "&rts_breakpoint_io_action"
354 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
356 -- When running a computation, we redirect ^C exceptions to the running
357 -- thread. ToDo: we might want a way to continue even if the target
358 -- thread doesn't die when it receives the exception... "this thread
359 -- is not responding".
361 -- Careful here: there may be ^C exceptions flying around, so we start the new
362 -- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
363 -- only while we execute the user's code. We can't afford to lose the final
364 -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
365 sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
366 sandboxIO dflags statusMVar thing =
367 mask $ \restore -> do -- fork starts blocked
368 id <- forkIO $ do res <- Exception.try (restore $ rethrow dflags thing)
369 putMVar statusMVar (Complete res) -- empty: can't block
370 withInterruptsSentTo id $ takeMVar statusMVar
373 -- We want to turn ^C into a break when -fbreak-on-exception is on,
374 -- but it's an async exception and we only break for sync exceptions.
375 -- Idea: if we catch and re-throw it, then the re-throw will trigger
376 -- a break. Great - but we don't want to re-throw all exceptions, because
377 -- then we'll get a double break for ordinary sync exceptions (you'd have
378 -- to :continue twice, which looks strange). So if the exception is
379 -- not "Interrupted", we unset the exception flag before throwing.
381 rethrow :: DynFlags -> IO a -> IO a
382 rethrow dflags io = Exception.catch io $ \se -> do
383 -- If -fbreak-on-error, we break unconditionally,
384 -- but with care of not breaking twice
385 if dopt Opt_BreakOnError dflags &&
386 not (dopt Opt_BreakOnException dflags)
387 then poke exceptionFlag 1
388 else case fromException se of
389 -- If it is a "UserInterrupt" exception, we allow
390 -- a possible break by way of -fbreak-on-exception
391 Just UserInterrupt -> return ()
392 -- In any other case, we don't want to break
393 _ -> poke exceptionFlag 0
397 withInterruptsSentTo :: ThreadId -> IO r -> IO r
398 withInterruptsSentTo thread get_result = do
399 bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
400 (\_ -> modifyMVar_ interruptTargetThread (\tl -> return $! tail tl))
403 -- This function sets up the interpreter for catching breakpoints, and
404 -- resets everything when the computation has stopped running. This
405 -- is a not-very-good way to ensure that only the interactive
406 -- evaluation should generate breakpoints.
407 withBreakAction :: (ExceptionMonad m, MonadIO m) =>
408 Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
409 withBreakAction step dflags breakMVar statusMVar act
410 = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
413 stablePtr <- newStablePtr onBreak
414 poke breakPointIOAction stablePtr
415 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
416 when step $ setStepFlag
418 -- Breaking on exceptions is not enabled by default, since it
419 -- might be a bit surprising. The exception flag is turned off
420 -- as soon as it is hit, or in resetBreakAction below.
422 onBreak is_exception info apStack = do
424 putMVar statusMVar (Break is_exception apStack info tid)
427 resetBreakAction stablePtr = do
428 poke breakPointIOAction noBreakStablePtr
431 freeStablePtr stablePtr
433 noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
434 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
436 noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
437 noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
438 noBreakAction True _ _ = return () -- exception: just continue
440 resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
441 resume canLogSpan step
443 hsc_env <- getSession
444 let ic = hsc_IC hsc_env
445 resume = ic_resume ic
448 [] -> ghcError (ProgramError "not stopped at a breakpoint")
450 -- unbind the temporary locals by restoring the TypeEnv from
451 -- before the breakpoint, and drop this Resume from the
452 -- InteractiveContext.
453 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
454 ic' = ic { ic_tmp_ids = resume_tmp_ids,
455 ic_tyvars = resume_tyvars,
457 modifySession (\_ -> hsc_env{ hsc_IC = ic' })
459 -- remove any bindings created since the breakpoint from the
460 -- linker's environment
461 let new_names = map idName (filter (`notElem` resume_tmp_ids)
463 liftIO $ Linker.deleteFromLinkEnv new_names
465 when (isStep step) $ liftIO setStepFlag
467 Resume expr tid breakMVar statusMVar bindings
468 final_ids apStack info span hist _ -> do
470 withBreakAction (isStep step) (hsc_dflags hsc_env)
471 breakMVar statusMVar $ do
472 status <- liftIO $ withInterruptsSentTo tid $ do
474 -- this awakens the stopped thread...
476 -- and wait for the result
477 let prevHistoryLst = fromListBL 50 hist
479 Nothing -> prevHistoryLst
481 | not $canLogSpan span -> prevHistoryLst
482 | otherwise -> mkHistory hsc_env apStack i `consBL`
486 traceRunStatus expr bindings final_ids
487 breakMVar statusMVar status hist'
489 handleRunStatus expr bindings final_ids
490 breakMVar statusMVar status hist'
492 back :: GhcMonad m => m ([Name], Int, SrcSpan)
495 forward :: GhcMonad m => m ([Name], Int, SrcSpan)
496 forward = moveHist (subtract 1)
498 moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
500 hsc_env <- getSession
501 case ic_resume (hsc_IC hsc_env) of
502 [] -> ghcError (ProgramError "not stopped at a breakpoint")
504 let ix = resumeHistoryIx r
505 history = resumeHistory r
508 when (new_ix > length history) $
509 ghcError (ProgramError "no more logged breakpoints")
511 ghcError (ProgramError "already at the beginning of the history")
514 update_ic apStack mb_info = do
515 (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
517 let ic = hsc_IC hsc_env1
518 r' = r { resumeHistoryIx = new_ix }
519 ic' = ic { ic_resume = r':rs }
521 modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
523 return (names, new_ix, span)
525 -- careful: we want apStack to be the AP_STACK itself, not a thunk
526 -- around it, hence the cases are carefully constructed below to
527 -- make this the case. ToDo: this is v. fragile, do something better.
530 Resume { resumeApStack = apStack,
531 resumeBreakInfo = mb_info } ->
532 update_ic apStack mb_info
533 else case history !! (new_ix - 1) of
534 History apStack info _ ->
535 update_ic apStack (Just info)
537 -- -----------------------------------------------------------------------------
538 -- After stopping at a breakpoint, add free variables to the environment
539 result_fs :: FastString
540 result_fs = fsLit "_result"
542 bindLocalsAtBreakpoint
546 -> IO (HscEnv, [Name], SrcSpan)
548 -- Nothing case: we stopped when an exception was raised, not at a
549 -- breakpoint. We have no location information or local variables to
550 -- bind, all we can do is bind a local variable to the exception
552 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
553 let exn_fs = fsLit "_exception"
554 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
556 e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
557 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
558 exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
559 new_tyvars = unitVarSet e_tyvar
561 ictxt0 = hsc_IC hsc_env
562 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
564 span = mkGeneralSrcSpan (fsLit "<exception thrown>")
566 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
567 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
569 -- Just case: we stopped at a breakpoint, we have information about the location
570 -- of the breakpoint and the free variables of the expression.
571 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
574 mod_name = moduleName (breakInfo_module info)
575 hmi = expectJust "bindLocalsAtBreakpoint" $
576 lookupUFM (hsc_HPT hsc_env) mod_name
577 breaks = getModBreaks hmi
578 index = breakInfo_number info
579 vars = breakInfo_vars info
580 result_ty = breakInfo_resty info
581 occs = modBreaks_vars breaks ! index
582 span = modBreaks_locs breaks ! index
584 -- filter out any unboxed ids; we can't bind these at the prompt
585 let pointers = filter (\(id,_) -> isPointer id) vars
586 isPointer id | PtrRep <- idPrimRep id = True
589 let (ids, offsets) = unzip pointers
591 -- It might be that getIdValFromApStack fails, because the AP_STACK
592 -- has been accidentally evaluated, or something else has gone wrong.
593 -- So that we don't fall over in a heap when this happens, just don't
594 -- bind any free variables instead, and we emit a warning.
595 mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
596 let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
597 when (any isNothing mb_hValues) $
598 debugTraceMsg (hsc_dflags hsc_env) 1 $
599 text "Warning: _result has been evaluated, some bindings have been lost"
601 new_ids <- zipWithM mkNewId occs filtered_ids
602 let names = map idName new_ids
604 -- make an Id for _result. We use the Unique of the FastString "_result";
605 -- we don't care about uniqueness here, because there will only be one
606 -- _result in scope at any time.
607 let result_name = mkInternalName (getUnique result_fs)
608 (mkVarOccFS result_fs) span
609 result_id = Id.mkVanillaGlobal result_name result_ty
611 -- for each Id we're about to bind in the local envt:
612 -- - skolemise the type variables in its type, so they can't
613 -- be randomly unified with other types. These type variables
614 -- can only be resolved by type reconstruction in RtClosureInspect
615 -- - tidy the type variables
616 -- - globalise the Id (Ids are supposed to be Global, apparently).
618 let result_ok = isPointer result_id
619 && not (isUnboxedTupleType (idType result_id))
621 all_ids | result_ok = result_id : new_ids
622 | otherwise = new_ids
623 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
624 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
625 new_tyvars = unionVarSets tyvarss
626 final_ids = zipWith setIdType all_ids tidy_tys
627 ictxt0 = hsc_IC hsc_env
628 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
630 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
631 when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
632 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
633 return (hsc_env1, if result_ok then result_name:names else names, span)
635 mkNewId :: OccName -> Id -> IO Id
637 us <- mkSplitUniqSupply 'I'
638 -- we need a fresh Unique for each Id we bind, because the linker
639 -- state is single-threaded and otherwise we'd spam old bindings
640 -- whenever we stop at a breakpoint. The InteractveContext is properly
641 -- saved/restored, but not the linker state. See #1743, test break026.
643 uniq = uniqFromSupply us
644 loc = nameSrcSpan (idName id)
645 name = mkInternalName uniq occ loc
647 new_id = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
650 rttiEnvironment :: HscEnv -> IO HscEnv
651 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
652 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
653 incompletelyTypedIds =
656 , (occNameFS.nameOccName.idName) id /= result_fs]
657 hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
660 noSkolems = null . filter isSkolemTyVar . varSetElems . tyVarsOfType . idType
661 improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
662 let InteractiveContext{ic_tmp_ids=tmp_ids} = ic
663 Just id = find (\i -> idName i == name) tmp_ids
667 mb_new_ty <- reconstructType hsc_env 10 id
668 let old_ty = idType id
670 Nothing -> return hsc_env
672 mb_subst <- improveRTTIType hsc_env old_ty new_ty
675 WARN(True, text (":print failed to calculate the "
676 ++ "improvement for a type")) hsc_env
678 when (dopt Opt_D_dump_rtti (hsc_dflags hsc_env)) $
679 printForUser stderr alwaysQualify $
680 fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
682 let (subst', skols) = skolemiseSubst subst
683 ic' = extendInteractiveContext
684 (substInteractiveContext ic subst') [] skols
685 return hsc_env{hsc_IC=ic'}
687 skolemiseSubst :: TvSubst -> (TvSubst, TyVarSet)
688 skolemiseSubst subst = let
689 varenv = getTvSubstEnv subst
690 all_together = mapVarEnv skolemiseTy varenv
691 (varenv', skol_vars) = ( mapVarEnv fst all_together
692 , map snd (varEnvElts all_together))
693 in (subst `setTvSubstEnv` varenv', unionVarSets skol_vars)
696 skolemiseTy :: Type -> (Type, TyVarSet)
697 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
698 where env = mkVarEnv (zip tyvars new_tyvar_tys)
699 subst = mkTvSubst emptyInScopeSet env
700 tyvars = varSetElems (tyVarsOfType ty)
701 new_tyvars = map skolemiseTyVar tyvars
702 new_tyvar_tys = map mkTyVarTy new_tyvars
704 skolemiseTyVar :: TyVar -> TyVar
705 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
706 (SkolemTv RuntimeUnkSkol)
708 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
709 getIdValFromApStack apStack (I# stackDepth) = do
710 case getApStackVal# apStack (stackDepth +# 1#) of
711 -- The +1 is magic! I don't know where it comes
712 -- from, but this makes things line up. --SDM
715 0# -> return Nothing -- AP_STACK not found
716 _ -> return (Just (unsafeCoerce# result))
718 pushResume :: HscEnv -> Resume -> HscEnv
719 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
721 ictxt0 = hsc_IC hsc_env
722 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
724 -- -----------------------------------------------------------------------------
725 -- Abandoning a resume context
727 abandon :: GhcMonad m => m Bool
729 hsc_env <- getSession
730 let ic = hsc_IC hsc_env
731 resume = ic_resume ic
735 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
739 abandonAll :: GhcMonad m => m Bool
741 hsc_env <- getSession
742 let ic = hsc_IC hsc_env
743 resume = ic_resume ic
747 modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
748 liftIO $ mapM_ abandon_ rs
751 -- when abandoning a computation we have to
752 -- (a) kill the thread with an async exception, so that the
753 -- computation itself is stopped, and
754 -- (b) fill in the MVar. This step is necessary because any
755 -- thunks that were under evaluation will now be updated
756 -- with the partial computation, which still ends in takeMVar,
757 -- so any attempt to evaluate one of these thunks will block
758 -- unless we fill in the MVar.
759 -- See test break010.
760 abandon_ :: Resume -> IO ()
762 killThread (resumeThreadId r)
763 putMVar (resumeBreakMVar r) ()
765 -- -----------------------------------------------------------------------------
766 -- Bounded list, optimised for repeated cons
768 data BoundedList a = BL
769 {-# UNPACK #-} !Int -- length
770 {-# UNPACK #-} !Int -- bound
772 [a] -- right, list is (left ++ reverse right)
774 nilBL :: Int -> BoundedList a
775 nilBL bound = BL 0 bound [] []
777 consBL :: a -> BoundedList a -> BoundedList a
778 consBL a (BL len bound left right)
779 | len < bound = BL (len+1) bound (a:left) right
780 | null right = BL len bound [a] $! tail (reverse left)
781 | otherwise = BL len bound (a:left) $! tail right
783 toListBL :: BoundedList a -> [a]
784 toListBL (BL _ _ left right) = left ++ reverse right
786 fromListBL :: Int -> [a] -> BoundedList a
787 fromListBL bound l = BL (length l) bound l []
789 -- lenBL (BL len _ _ _) = len
791 -- -----------------------------------------------------------------------------
792 -- | Set the interactive evaluation context.
794 -- Setting the context doesn't throw away any bindings; the bindings
795 -- we've built up in the InteractiveContext simply move to the new
796 -- module. They always shadow anything in scope in the current context.
797 setContext :: GhcMonad m =>
798 [Module] -- ^ entire top level scope of these modules
799 -> [(Module, Maybe (ImportDecl RdrName))] -- ^ exports of these modules
801 setContext toplev_mods other_mods = do
802 hsc_env <- getSession
803 let old_ic = hsc_IC hsc_env
804 hpt = hsc_HPT hsc_env
805 (decls,mods) = partition (isJust . snd) other_mods -- time for tracing
806 export_mods = map fst mods
807 imprt_decls = map noLoc (catMaybes (map snd decls))
809 export_env <- liftIO $ mkExportEnv hsc_env export_mods
811 if null imprt_decls then return emptyGlobalRdrEnv else do
812 let imports = rnImports imprt_decls
813 this_mod = if null toplev_mods then pRELUDE else head toplev_mods
815 ioMsgMaybe $ liftIO $ initTc hsc_env HsSrcFile False this_mod imports
817 toplev_envs <- liftIO $ mapM (mkTopLevEnv hpt) toplev_mods
818 let all_env = foldr plusGlobalRdrEnv (plusGlobalRdrEnv export_env import_env) toplev_envs
819 modifySession $ \_ ->
820 hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
821 ic_exports = other_mods,
822 ic_rn_gbl_env = all_env }}
824 -- Make a GlobalRdrEnv based on the exports of the modules only.
825 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
826 mkExportEnv hsc_env mods
827 = do { stuff <- mapM (getModuleExports hsc_env) mods
828 ; let (_msgs, mb_name_sets) = unzip stuff
829 envs = [ availsToGlobalRdrEnv (moduleName mod) avails
830 | (Just avails, mod) <- zip mb_name_sets mods ]
831 ; return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv envs }
833 availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
834 availsToGlobalRdrEnv mod_name avails
835 = mkGlobalRdrEnv (gresFromAvails imp_prov avails)
837 -- We're building a GlobalRdrEnv as if the user imported
838 -- all the specified modules into the global interactive module
839 imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
840 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
842 is_dloc = srcLocSpan interactiveSrcLoc }
844 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
846 = case lookupUFM hpt (moduleName modl) of
847 Nothing -> ghcError (ProgramError ("mkTopLevEnv: not a home module " ++
848 showSDoc (ppr modl)))
850 case mi_globals (hm_iface details) of
852 ghcError (ProgramError ("mkTopLevEnv: not interpreted "
853 ++ showSDoc (ppr modl)))
854 Just env -> return env
856 -- | Get the interactive evaluation context, consisting of a pair of the
857 -- set of modules from which we take the full top-level scope, and the set
858 -- of modules from which we take just the exports respectively.
859 getContext :: GhcMonad m => m ([Module],[(Module, Maybe (ImportDecl RdrName))])
860 getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
861 return (ic_toplev_scope ic, ic_exports ic)
863 -- | Returns @True@ if the specified module is interpreted, and hence has
864 -- its full top-level scope available.
865 moduleIsInterpreted :: GhcMonad m => Module -> m Bool
866 moduleIsInterpreted modl = withSession $ \h ->
867 if modulePackageId modl /= thisPackage (hsc_dflags h)
869 else case lookupUFM (hsc_HPT h) (moduleName modl) of
870 Just details -> return (isJust (mi_globals (hm_iface details)))
871 _not_a_home_module -> return False
873 -- | Looks up an identifier in the current interactive context (for :info)
874 -- Filter the instances by the ones whose tycons (or clases resp)
875 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
876 -- The exact choice of which ones to show, and which to hide, is a judgement call.
878 getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[Instance]))
880 = withSession $ \hsc_env ->
881 do mb_stuff <- ioMsg $ tcRnGetInfo hsc_env name
883 Nothing -> return Nothing
884 Just (thing, fixity, ispecs) -> do
885 let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
886 return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
888 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
889 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
890 where -- A name is ok if it's in the rdr_env,
891 -- whether qualified or not
892 ok n | n == name = True -- The one we looked for in the first place!
893 | isBuiltInSyntax n = True
894 | isExternalName n = any ((== n) . gre_name)
895 (lookupGRE_Name rdr_env n)
898 -- | Returns all names in scope in the current interactive context
899 getNamesInScope :: GhcMonad m => m [Name]
900 getNamesInScope = withSession $ \hsc_env -> do
901 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
903 getRdrNamesInScope :: GhcMonad m => m [RdrName]
904 getRdrNamesInScope = withSession $ \hsc_env -> do
907 gbl_rdrenv = ic_rn_gbl_env ic
909 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
910 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
912 return (gbl_names ++ lcl_names)
915 -- ToDo: move to RdrName
916 greToRdrNames :: GlobalRdrElt -> [RdrName]
917 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
920 Imported specs -> concat (map do_spec (map is_decl specs))
922 occ = nameOccName name
925 | is_qual decl_spec = [qual]
926 | otherwise = [unqual,qual]
927 where qual = Qual (is_as decl_spec) occ
929 -- | Parses a string as an identifier, and returns the list of 'Name's that
930 -- the identifier can refer to in the current interactive context.
931 parseName :: GhcMonad m => String -> m [Name]
932 parseName str = withSession $ \hsc_env -> do
933 (L _ rdr_name) <- hscParseIdentifier (hsc_dflags hsc_env) str
934 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
936 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
937 -- entity known to GHC, including 'Name's defined using 'runStmt'.
938 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
939 lookupName name = withSession $ \hsc_env -> do
940 mb_tything <- ioMsg $ tcRnLookupName hsc_env name
942 -- XXX: calls panic in some circumstances; is that ok?
944 -- -----------------------------------------------------------------------------
945 -- Getting the type of an expression
947 -- | Get the type of an expression
948 exprType :: GhcMonad m => String -> m Type
949 exprType expr = withSession $ \hsc_env -> do
950 ty <- hscTcExpr hsc_env expr
951 return $ tidyType emptyTidyEnv ty
953 -- -----------------------------------------------------------------------------
954 -- Getting the kind of a type
956 -- | Get the kind of a type
957 typeKind :: GhcMonad m => String -> m Kind
958 typeKind str = withSession $ \hsc_env -> do
959 hscKcType hsc_env str
961 -----------------------------------------------------------------------------
962 -- cmCompileExpr: compile an expression and deliver an HValue
964 compileExpr :: GhcMonad m => String -> m HValue
965 compileExpr expr = withSession $ \hsc_env -> do
966 Just (ids, hval) <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
968 hvals <- liftIO (unsafeCoerce# hval :: IO [HValue])
971 ([_],[hv]) -> return hv
972 _ -> panic "compileExpr"
974 -- -----------------------------------------------------------------------------
975 -- Compile an expression into a dynamic
977 dynCompileExpr :: GhcMonad m => String -> m Dynamic
978 dynCompileExpr expr = do
979 (full,exports) <- getContext
982 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
984 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
985 Just (ids, hvals) <- withSession (flip hscStmt stmt)
986 setContext full exports
987 vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
989 (_:[], v:[]) -> return v
990 _ -> panic "dynCompileExpr"
992 -----------------------------------------------------------------------------
993 -- show a module and it's source/object filenames
995 showModule :: GhcMonad m => ModSummary -> m String
996 showModule mod_summary =
997 withSession $ \hsc_env -> do
998 interpreted <- isModuleInterpreted mod_summary
999 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
1001 isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
1002 isModuleInterpreted mod_summary = withSession $ \hsc_env ->
1003 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
1004 Nothing -> panic "missing linkable"
1005 Just mod_info -> return (not obj_linkable)
1007 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
1009 ----------------------------------------------------------------------------
1012 obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
1013 obtainTermFromVal hsc_env bound force ty x =
1014 cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
1016 obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
1017 obtainTermFromId hsc_env bound force id = do
1018 hv <- Linker.getHValue hsc_env (varName id)
1019 cvObtainTerm hsc_env bound force (idType id) hv
1021 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
1022 reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
1023 reconstructType hsc_env bound id = do
1024 hv <- Linker.getHValue hsc_env (varName id)
1025 cvReconstructType hsc_env bound (idType id) hv