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(..),
19 setContext, getContext,
20 nameSetToGlobalRdrEnv,
30 compileExpr, dynCompileExpr,
32 obtainTerm, obtainTerm1, reconstructType,
33 skolemiseSubst, skolemiseTy
39 #include "HsVersions.h"
41 import HscMain hiding (compileExpr)
44 import Type hiding (typeKind)
45 import TcType hiding (typeKind)
47 import Var hiding (setIdType)
50 import Name hiding ( varName )
67 import RtClosureInspect
78 import Control.Exception as Exception
79 import Control.Concurrent
81 import Foreign.StablePtr
83 -- -----------------------------------------------------------------------------
84 -- running a statement interactively
87 = RunOk [Name] -- ^ names bound by this evaluation
88 | RunFailed -- ^ statement failed compilation
89 | RunException Exception -- ^ statement raised an exception
90 | RunBreak ThreadId [Name] (Maybe BreakInfo)
93 = Break Bool HValue BreakInfo ThreadId
94 -- ^ the computation hit a breakpoint (Bool <=> was an exception)
95 | Complete (Either Exception [HValue])
96 -- ^ the computation completed with either an exception or a value
100 resumeStmt :: String, -- the original statement
101 resumeThreadId :: ThreadId, -- thread running the computation
102 resumeBreakMVar :: MVar (),
103 resumeStatMVar :: MVar Status,
104 resumeBindings :: ([Id], TyVarSet),
105 resumeFinalIds :: [Id], -- [Id] to bind on completion
106 resumeApStack :: HValue, -- The object from which we can get
107 -- value of the free variables.
108 resumeBreakInfo :: Maybe BreakInfo,
109 -- the breakpoint we stopped at
110 -- (Nothing <=> exception)
111 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
112 -- to fetch the ModDetails & ModBreaks
114 resumeHistory :: [History],
115 resumeHistoryIx :: Int -- 0 <==> at the top of the history
118 getResumeContext :: Session -> IO [Resume]
119 getResumeContext s = withSession s (return . ic_resume . hsc_IC)
126 isStep RunToCompletion = False
131 historyApStack :: HValue,
132 historyBreakInfo :: BreakInfo
135 getHistoryModule :: History -> Module
136 getHistoryModule = breakInfo_module . historyBreakInfo
138 getHistorySpan :: Session -> History -> IO SrcSpan
139 getHistorySpan s hist = withSession s $ \hsc_env -> do
140 let inf = historyBreakInfo hist
141 num = breakInfo_number inf
142 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
143 Just hmi -> return (modBreaks_locs (md_modBreaks (hm_details hmi)) ! num)
144 _ -> panic "getHistorySpan"
146 -- | Run a statement in the current interactive context. Statement
147 -- may bind multple values.
148 runStmt :: Session -> String -> SingleStep -> IO RunResult
149 runStmt (Session ref) expr step
151 hsc_env <- readIORef ref
153 breakMVar <- newEmptyMVar -- wait on this when we hit a breakpoint
154 statusMVar <- newEmptyMVar -- wait on this when a computation is running
156 -- Turn off -fwarn-unused-bindings when running a statement, to hide
157 -- warnings about the implicit bindings we introduce.
158 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
159 hsc_env' = hsc_env{ hsc_dflags = dflags' }
161 maybe_stuff <- hscStmt hsc_env' expr
164 Nothing -> return RunFailed
165 Just (ids, hval) -> do
167 withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
169 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
170 status <- sandboxIO statusMVar thing_to_run
172 let ic = hsc_IC hsc_env
173 bindings = (ic_tmp_ids ic, ic_tyvars ic)
177 traceRunStatus expr ref bindings ids
178 breakMVar statusMVar status emptyHistory
180 handleRunStatus expr ref bindings ids
181 breakMVar statusMVar status emptyHistory
184 emptyHistory = nilBL 50 -- keep a log of length 50
186 handleRunStatus expr ref bindings final_ids breakMVar statusMVar status
189 -- did we hit a breakpoint or did we complete?
190 (Break is_exception apStack info tid) -> do
191 hsc_env <- readIORef ref
192 let mb_info | is_exception = Nothing
193 | otherwise = Just info
194 (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env
197 resume = Resume expr tid breakMVar statusMVar
198 bindings final_ids apStack mb_info span
200 hsc_env2 = pushResume hsc_env1 resume
202 writeIORef ref hsc_env2
203 return (RunBreak tid names mb_info)
204 (Complete either_hvals) ->
206 Left e -> return (RunException e)
208 hsc_env <- readIORef ref
209 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
210 final_ids emptyVarSet
211 -- the bound Ids never have any free TyVars
212 final_names = map idName final_ids
213 Linker.extendLinkEnv (zip final_names hvals)
214 hsc_env' <- rttiEnvironment hsc_env{hsc_IC=final_ic}
215 writeIORef ref hsc_env'
216 return (RunOk final_names)
219 traceRunStatus expr ref bindings final_ids
220 breakMVar statusMVar status history = do
221 hsc_env <- readIORef ref
223 -- when tracing, if we hit a breakpoint that is not explicitly
224 -- enabled, then we just log the event in the history and continue.
225 (Break is_exception apStack info tid) | not is_exception -> do
226 b <- isBreakEnabled hsc_env info
230 let history' = consBL (History apStack info) history
231 -- probably better make history strict here, otherwise
232 -- our BoundedList will be pointless.
234 status <- withBreakAction True (hsc_dflags hsc_env)
235 breakMVar statusMVar $ do
237 (do putMVar breakMVar () -- awaken the stopped thread
239 (takeMVar statusMVar) -- and wait for the result
240 traceRunStatus expr ref bindings final_ids
241 breakMVar statusMVar status history'
245 handle_normally = handleRunStatus expr ref bindings final_ids
246 breakMVar statusMVar status history
249 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
250 isBreakEnabled hsc_env inf =
251 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
253 w <- getBreak (modBreaks_flags (md_modBreaks (hm_details hmi)))
254 (breakInfo_number inf)
255 case w of Just n -> return (n /= 0); _other -> return False
260 foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
261 foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
263 setStepFlag = poke stepFlag 1
264 resetStepFlag = poke stepFlag 0
266 -- this points to the IO action that is executed when a breakpoint is hit
267 foreign import ccall "&rts_breakpoint_io_action"
268 breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
270 -- When running a computation, we redirect ^C exceptions to the running
271 -- thread. ToDo: we might want a way to continue even if the target
272 -- thread doesn't die when it receives the exception... "this thread
273 -- is not responding".
274 sandboxIO :: MVar Status -> IO [HValue] -> IO Status
275 sandboxIO statusMVar thing =
277 (forkIO (do res <- Exception.try (rethrow thing)
278 putMVar statusMVar (Complete res)))
279 (takeMVar statusMVar)
281 -- We want to turn ^C into a break when -fbreak-on-exception is on,
282 -- but it's an async exception and we only break for sync exceptions.
283 -- Idea: if we catch and re-throw it, then the re-throw will trigger
284 -- a break. Great - but we don't want to re-throw all exceptions, because
285 -- then we'll get a double break for ordinary sync exceptions (you'd have
286 -- to :continue twice, which looks strange). So if the exception is
287 -- not "Interrupted", we unset the exception flag before throwing.
289 rethrow :: IO a -> IO a
290 rethrow io = Exception.catch io $ \e -> -- NB. not catchDyn
292 DynException d | Just Interrupted <- fromDynamic d
293 -> Exception.throwIO e
294 _ -> do poke exceptionFlag 0; Exception.throwIO e
297 withInterruptsSentTo :: IO ThreadId -> IO r -> IO r
298 withInterruptsSentTo io get_result = do
299 ts <- takeMVar interruptTargetThread
301 putMVar interruptTargetThread (child:ts)
302 get_result `finally` modifyMVar_ interruptTargetThread (return.tail)
304 -- This function sets up the interpreter for catching breakpoints, and
305 -- resets everything when the computation has stopped running. This
306 -- is a not-very-good way to ensure that only the interactive
307 -- evaluation should generate breakpoints.
308 withBreakAction step dflags breakMVar statusMVar io
309 = bracket setBreakAction resetBreakAction (\_ -> io)
312 stablePtr <- newStablePtr onBreak
313 poke breakPointIOAction stablePtr
314 when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
315 when step $ setStepFlag
317 -- Breaking on exceptions is not enabled by default, since it
318 -- might be a bit surprising. The exception flag is turned off
319 -- as soon as it is hit, or in resetBreakAction below.
321 onBreak is_exception info apStack = do
323 putMVar statusMVar (Break is_exception apStack info tid)
326 resetBreakAction stablePtr = do
327 poke breakPointIOAction noBreakStablePtr
330 freeStablePtr stablePtr
332 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
334 noBreakAction False info apStack = putStrLn "*** Ignoring breakpoint"
335 noBreakAction True info apStack = return () -- exception: just continue
337 resume :: Session -> SingleStep -> IO RunResult
338 resume (Session ref) step
340 hsc_env <- readIORef ref
341 let ic = hsc_IC hsc_env
342 resume = ic_resume ic
345 [] -> throwDyn (ProgramError "not stopped at a breakpoint")
347 -- unbind the temporary locals by restoring the TypeEnv from
348 -- before the breakpoint, and drop this Resume from the
349 -- InteractiveContext.
350 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
351 ic' = ic { ic_tmp_ids = resume_tmp_ids,
352 ic_tyvars = resume_tyvars,
354 writeIORef ref hsc_env{ hsc_IC = ic' }
356 -- remove any bindings created since the breakpoint from the
357 -- linker's environment
358 let new_names = map idName (filter (`notElem` resume_tmp_ids)
360 Linker.deleteFromLinkEnv new_names
362 when (isStep step) $ setStepFlag
364 Resume expr tid breakMVar statusMVar bindings
365 final_ids apStack info _ hist _ -> do
366 withBreakAction (isStep step) (hsc_dflags hsc_env)
367 breakMVar statusMVar $ do
368 status <- withInterruptsSentTo
369 (do putMVar breakMVar ()
370 -- this awakens the stopped thread...
372 (takeMVar statusMVar)
373 -- and wait for the result
374 let hist' = case info of
375 Nothing -> fromListBL 50 hist
376 Just i -> History apStack i `consBL`
380 traceRunStatus expr ref bindings final_ids
381 breakMVar statusMVar status hist'
383 handleRunStatus expr ref bindings final_ids
384 breakMVar statusMVar status hist'
387 back :: Session -> IO ([Name], Int, SrcSpan)
390 forward :: Session -> IO ([Name], Int, SrcSpan)
391 forward = moveHist (subtract 1)
393 moveHist fn (Session ref) = do
394 hsc_env <- readIORef ref
395 case ic_resume (hsc_IC hsc_env) of
396 [] -> throwDyn (ProgramError "not stopped at a breakpoint")
398 let ix = resumeHistoryIx r
399 history = resumeHistory r
402 when (new_ix > length history) $
403 throwDyn (ProgramError "no more logged breakpoints")
405 throwDyn (ProgramError "already at the beginning of the history")
408 update_ic apStack mb_info = do
409 (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env
411 let ic = hsc_IC hsc_env1
412 r' = r { resumeHistoryIx = new_ix }
413 ic' = ic { ic_resume = r':rs }
415 writeIORef ref hsc_env1{ hsc_IC = ic' }
417 return (names, new_ix, span)
419 -- careful: we want apStack to be the AP_STACK itself, not a thunk
420 -- around it, hence the cases are carefully constructed below to
421 -- make this the case. ToDo: this is v. fragile, do something better.
424 Resume { resumeApStack = apStack,
425 resumeBreakInfo = mb_info } ->
426 update_ic apStack mb_info
427 else case history !! (new_ix - 1) of
428 History apStack info ->
429 update_ic apStack (Just info)
431 -- -----------------------------------------------------------------------------
432 -- After stopping at a breakpoint, add free variables to the environment
433 result_fs = FSLIT("_result")
435 bindLocalsAtBreakpoint
439 -> IO (HscEnv, [Name], SrcSpan)
441 -- Nothing case: we stopped when an exception was raised, not at a
442 -- breakpoint. We have no location information or local variables to
443 -- bind, all we can do is bind a local variable to the exception
445 bindLocalsAtBreakpoint hsc_env apStack Nothing = do
446 let exn_fs = FSLIT("_exception")
447 exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
449 e_name = mkInternalName (getUnique e_fs) (mkTyVarOcc e_fs) span
450 e_tyvar = mkTcTyVar e_name liftedTypeKind (SkolemTv RuntimeUnkSkol)
451 exn_id = Id.mkGlobalId VanillaGlobal exn_name (mkTyVarTy e_tyvar)
453 new_tyvars = unitVarSet e_tyvar
455 ictxt0 = hsc_IC hsc_env
456 ictxt1 = extendInteractiveContext ictxt0 [exn_id] new_tyvars
458 span = mkGeneralSrcSpan FSLIT("<exception thrown>")
460 Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
461 return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
463 -- Just case: we stopped at a breakpoint, we have information about the location
464 -- of the breakpoint and the free variables of the expression.
465 bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
468 mod_name = moduleName (breakInfo_module info)
469 mod_details = fmap hm_details (lookupUFM (hsc_HPT hsc_env) mod_name)
470 breaks = md_modBreaks (expectJust "handlRunStatus" mod_details)
471 index = breakInfo_number info
472 vars = breakInfo_vars info
473 result_ty = breakInfo_resty info
474 occs = modBreaks_vars breaks ! index
475 span = modBreaks_locs breaks ! index
477 -- filter out any unboxed ids; we can't bind these at the prompt
478 let pointers = filter (\(id,_) -> isPointer id) vars
479 isPointer id | PtrRep <- idPrimRep id = True
482 let (ids, offsets) = unzip pointers
484 -- It might be that getIdValFromApStack fails, because the AP_STACK
485 -- has been accidentally evaluated, or something else has gone wrong.
486 -- So that we don't fall over in a heap when this happens, just don't
487 -- bind any free variables instead, and we emit a warning.
488 mb_hValues <- mapM (getIdValFromApStack apStack) offsets
489 let (filtered_hvs, filtered_ids) =
490 unzip [ (hv, id) | (id, Just hv) <- zip ids mb_hValues ]
491 when (any isNothing mb_hValues) $
492 debugTraceMsg (hsc_dflags hsc_env) 1 $
493 text "Warning: _result has been evaluated, some bindings have been lost"
495 new_ids <- zipWithM mkNewId occs filtered_ids
496 let names = map idName new_ids
498 -- make an Id for _result. We use the Unique of the FastString "_result";
499 -- we don't care about uniqueness here, because there will only be one
500 -- _result in scope at any time.
501 let result_name = mkInternalName (getUnique result_fs)
502 (mkVarOccFS result_fs) span
503 result_id = Id.mkGlobalId VanillaGlobal result_name result_ty
506 -- for each Id we're about to bind in the local envt:
507 -- - skolemise the type variables in its type, so they can't
508 -- be randomly unified with other types. These type variables
509 -- can only be resolved by type reconstruction in RtClosureInspect
510 -- - tidy the type variables
511 -- - globalise the Id (Ids are supposed to be Global, apparently).
513 let all_ids | isPointer result_id = result_id : new_ids
514 | otherwise = new_ids
515 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
516 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
517 new_tyvars = unionVarSets tyvarss
518 let final_ids = zipWith setIdType all_ids tidy_tys
519 ictxt0 = hsc_IC hsc_env
520 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
521 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
522 Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
523 hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
524 return (hsc_env1, result_name:names, span)
526 mkNewId :: OccName -> Id -> IO Id
528 let uniq = idUnique id
529 loc = nameSrcSpan (idName id)
530 name = mkInternalName uniq occ loc
532 new_id = Id.mkGlobalId VanillaGlobal name ty (idInfo id)
535 rttiEnvironment :: HscEnv -> IO HscEnv
536 rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
537 let InteractiveContext{ic_tmp_ids=tmp_ids, ic_tyvars = tyvars} = ic
538 incompletelyTypedIds =
540 , not $ null [v | v <- varSetElems$ tyVarsOfType (idType id)
542 , (occNameFS.nameOccName.idName) id /= result_fs]
543 tys <- reconstructType hsc_env False `mapM` incompletelyTypedIds
544 -- map termType `fmap` (obtainTerm hsc_env False `mapM` incompletelyTypedIds)
546 let substs = [computeRTTIsubst ty ty'
547 | (ty, Just ty') <- zip (map idType incompletelyTypedIds) tys]
548 ic' = foldr (flip substInteractiveContext) ic
549 (map skolemiseSubst $ catMaybes substs)
550 return hsc_env{hsc_IC=ic'}
552 skolemiseSubst subst = subst `setTvSubstEnv`
553 mapVarEnv (fst.skolemiseTy) (getTvSubstEnv subst)
555 skolemiseTy :: Type -> (Type, TyVarSet)
556 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
557 where env = mkVarEnv (zip tyvars new_tyvar_tys)
558 subst = mkTvSubst emptyInScopeSet env
559 tyvars = varSetElems (tyVarsOfType ty)
560 new_tyvars = map skolemiseTyVar tyvars
561 new_tyvar_tys = map mkTyVarTy new_tyvars
563 skolemiseTyVar :: TyVar -> TyVar
564 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
565 (SkolemTv RuntimeUnkSkol)
567 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
568 getIdValFromApStack apStack (I# stackDepth) = do
569 case getApStackVal# apStack (stackDepth +# 1#) of
570 -- The +1 is magic! I don't know where it comes
571 -- from, but this makes things line up. --SDM
574 0# -> return Nothing -- AP_STACK not found
575 _ -> return (Just (unsafeCoerce# result))
577 pushResume :: HscEnv -> Resume -> HscEnv
578 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
580 ictxt0 = hsc_IC hsc_env
581 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
583 -- -----------------------------------------------------------------------------
584 -- Abandoning a resume context
586 abandon :: Session -> IO Bool
587 abandon (Session ref) = do
588 hsc_env <- readIORef ref
589 let ic = hsc_IC hsc_env
590 resume = ic_resume ic
594 writeIORef ref hsc_env{ hsc_IC = ic { ic_resume = rs } }
598 abandonAll :: Session -> IO Bool
599 abandonAll (Session ref) = do
600 hsc_env <- readIORef ref
601 let ic = hsc_IC hsc_env
602 resume = ic_resume ic
606 writeIORef ref hsc_env{ hsc_IC = ic { ic_resume = [] } }
610 -- when abandoning a computation we have to
611 -- (a) kill the thread with an async exception, so that the
612 -- computation itself is stopped, and
613 -- (b) fill in the MVar. This step is necessary because any
614 -- thunks that were under evaluation will now be updated
615 -- with the partial computation, which still ends in takeMVar,
616 -- so any attempt to evaluate one of these thunks will block
617 -- unless we fill in the MVar.
618 -- See test break010.
619 abandon_ :: Resume -> IO ()
621 killThread (resumeThreadId r)
622 putMVar (resumeBreakMVar r) ()
624 -- -----------------------------------------------------------------------------
625 -- Bounded list, optimised for repeated cons
627 data BoundedList a = BL
628 {-# UNPACK #-} !Int -- length
629 {-# UNPACK #-} !Int -- bound
631 [a] -- right, list is (left ++ reverse right)
633 nilBL :: Int -> BoundedList a
634 nilBL bound = BL 0 bound [] []
636 consBL a (BL len bound left right)
637 | len < bound = BL (len+1) bound (a:left) right
638 | null right = BL len bound [a] $! tail (reverse left)
639 | otherwise = BL len bound (a:left) $! tail right
641 toListBL (BL _ _ left right) = left ++ reverse right
643 fromListBL bound l = BL (length l) bound l []
645 -- lenBL (BL len _ _ _) = len
647 -- -----------------------------------------------------------------------------
648 -- | Set the interactive evaluation context.
650 -- Setting the context doesn't throw away any bindings; the bindings
651 -- we've built up in the InteractiveContext simply move to the new
652 -- module. They always shadow anything in scope in the current context.
653 setContext :: Session
654 -> [Module] -- entire top level scope of these modules
655 -> [Module] -- exports only of these modules
657 setContext sess@(Session ref) toplev_mods export_mods = do
658 hsc_env <- readIORef ref
659 let old_ic = hsc_IC hsc_env
660 hpt = hsc_HPT hsc_env
662 export_env <- mkExportEnv hsc_env export_mods
663 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
664 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
665 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
666 ic_exports = export_mods,
667 ic_rn_gbl_env = all_env }}
669 -- Make a GlobalRdrEnv based on the exports of the modules only.
670 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
671 mkExportEnv hsc_env mods = do
672 stuff <- mapM (getModuleExports hsc_env) mods
674 (_msgs, mb_name_sets) = unzip stuff
675 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
676 | (Just avails, mod) <- zip mb_name_sets mods ]
678 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
680 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
681 nameSetToGlobalRdrEnv names mod =
682 mkGlobalRdrEnv [ GRE { gre_name = name, gre_par = NoParent, gre_prov = vanillaProv mod }
683 | name <- nameSetToList names ]
685 vanillaProv :: ModuleName -> Provenance
686 -- We're building a GlobalRdrEnv as if the user imported
687 -- all the specified modules into the global interactive module
688 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
690 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
692 is_dloc = srcLocSpan interactiveSrcLoc }
694 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
696 = case lookupUFM hpt (moduleName modl) of
697 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
698 showSDoc (ppr modl)))
700 case mi_globals (hm_iface details) of
702 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
703 ++ showSDoc (ppr modl)))
704 Just env -> return env
706 -- | Get the interactive evaluation context, consisting of a pair of the
707 -- set of modules from which we take the full top-level scope, and the set
708 -- of modules from which we take just the exports respectively.
709 getContext :: Session -> IO ([Module],[Module])
710 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
711 return (ic_toplev_scope ic, ic_exports ic))
713 -- | Returns 'True' if the specified module is interpreted, and hence has
714 -- its full top-level scope available.
715 moduleIsInterpreted :: Session -> Module -> IO Bool
716 moduleIsInterpreted s modl = withSession s $ \h ->
717 if modulePackageId modl /= thisPackage (hsc_dflags h)
719 else case lookupUFM (hsc_HPT h) (moduleName modl) of
720 Just details -> return (isJust (mi_globals (hm_iface details)))
721 _not_a_home_module -> return False
723 -- | Looks up an identifier in the current interactive context (for :info)
724 -- Filter the instances by the ones whose tycons (or clases resp)
725 -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
726 -- The exact choice of which ones to show, and which to hide, is a judgement call.
728 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
730 = withSession s $ \hsc_env ->
731 do { mb_stuff <- tcRnGetInfo hsc_env name
733 Nothing -> return Nothing
734 Just (thing, fixity, ispecs) -> do
735 { let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
736 ; return (Just (thing, fixity, filter (plausible rdr_env) ispecs)) } }
738 plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
739 = all ok $ nameSetToList $ tyClsNamesOfType $ idType $ instanceDFunId ispec
740 where -- A name is ok if it's in the rdr_env,
741 -- whether qualified or not
742 ok n | n == name = True -- The one we looked for in the first place!
743 | isBuiltInSyntax n = True
744 | isExternalName n = any ((== n) . gre_name)
745 (lookupGRE_Name rdr_env n)
748 -- | Returns all names in scope in the current interactive context
749 getNamesInScope :: Session -> IO [Name]
750 getNamesInScope s = withSession s $ \hsc_env -> do
751 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
753 getRdrNamesInScope :: Session -> IO [RdrName]
754 getRdrNamesInScope s = withSession s $ \hsc_env -> do
757 gbl_rdrenv = ic_rn_gbl_env ic
759 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
760 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
762 return (gbl_names ++ lcl_names)
765 -- ToDo: move to RdrName
766 greToRdrNames :: GlobalRdrElt -> [RdrName]
767 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
770 Imported specs -> concat (map do_spec (map is_decl specs))
772 occ = nameOccName name
775 | is_qual decl_spec = [qual]
776 | otherwise = [unqual,qual]
777 where qual = Qual (is_as decl_spec) occ
779 -- | Parses a string as an identifier, and returns the list of 'Name's that
780 -- the identifier can refer to in the current interactive context.
781 parseName :: Session -> String -> IO [Name]
782 parseName s str = withSession s $ \hsc_env -> do
783 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
784 case maybe_rdr_name of
786 Just (L _ rdr_name) -> do
787 mb_names <- tcRnLookupRdrName hsc_env rdr_name
791 -- ToDo: should return error messages
793 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
794 -- entity known to GHC, including 'Name's defined using 'runStmt'.
795 lookupName :: Session -> Name -> IO (Maybe TyThing)
796 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
798 -- -----------------------------------------------------------------------------
799 -- Getting the type of an expression
801 -- | Get the type of an expression
802 exprType :: Session -> String -> IO (Maybe Type)
803 exprType s expr = withSession s $ \hsc_env -> do
804 maybe_stuff <- hscTcExpr hsc_env expr
806 Nothing -> return Nothing
807 Just ty -> return (Just tidy_ty)
809 tidy_ty = tidyType emptyTidyEnv ty
811 -- -----------------------------------------------------------------------------
812 -- Getting the kind of a type
814 -- | Get the kind of a type
815 typeKind :: Session -> String -> IO (Maybe Kind)
816 typeKind s str = withSession s $ \hsc_env -> do
817 maybe_stuff <- hscKcType hsc_env str
819 Nothing -> return Nothing
820 Just kind -> return (Just kind)
822 -----------------------------------------------------------------------------
823 -- cmCompileExpr: compile an expression and deliver an HValue
825 compileExpr :: Session -> String -> IO (Maybe HValue)
826 compileExpr s expr = withSession s $ \hsc_env -> do
827 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
829 Nothing -> return Nothing
830 Just (ids, hval) -> do
832 hvals <- (unsafeCoerce# hval) :: IO [HValue]
835 ([n],[hv]) -> return (Just hv)
836 _ -> panic "compileExpr"
838 -- -----------------------------------------------------------------------------
839 -- Compile an expression into a dynamic
841 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
842 dynCompileExpr ses expr = do
843 (full,exports) <- getContext ses
844 setContext ses full $
846 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
848 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
849 res <- withSession ses (flip hscStmt stmt)
850 setContext ses full exports
852 Nothing -> return Nothing
853 Just (ids, hvals) -> do
854 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
856 (_:[], v:[]) -> return (Just v)
857 _ -> panic "dynCompileExpr"
859 -----------------------------------------------------------------------------
860 -- show a module and it's source/object filenames
862 showModule :: Session -> ModSummary -> IO String
863 showModule s mod_summary = withSession s $ \hsc_env ->
864 isModuleInterpreted s mod_summary >>= \interpreted ->
865 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
867 isModuleInterpreted :: Session -> ModSummary -> IO Bool
868 isModuleInterpreted s mod_summary = withSession s $ \hsc_env ->
869 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
870 Nothing -> panic "missing linkable"
871 Just mod_info -> return (not obj_linkable)
873 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
875 ----------------------------------------------------------------------------
878 obtainTerm1 :: HscEnv -> Bool -> Maybe Type -> a -> IO Term
879 obtainTerm1 hsc_env force mb_ty x =
880 cvObtainTerm hsc_env force mb_ty (unsafeCoerce# x)
882 obtainTerm :: HscEnv -> Bool -> Id -> IO Term
883 obtainTerm hsc_env force id = do
884 hv <- Linker.getHValue hsc_env (varName id)
885 cvObtainTerm hsc_env force (Just$ idType id) hv
887 -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
888 reconstructType :: HscEnv -> Bool -> Id -> IO (Maybe Type)
889 reconstructType hsc_env force id = do
890 hv <- Linker.getHValue hsc_env (varName id)
891 cvReconstructType hsc_env force (Just$ idType id) hv