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(..),
18 setContext, getContext,
19 nameSetToGlobalRdrEnv,
29 compileExpr, dynCompileExpr,
31 obtainTerm, obtainTerm1
37 #include "HsVersions.h"
39 import HscMain hiding (compileExpr)
42 import Type hiding (typeKind)
43 import TcType hiding (typeKind)
45 import Var hiding (setIdType)
48 import Name hiding ( varName )
65 import RtClosureInspect
75 import Control.Exception as Exception
76 import Control.Concurrent
78 import Foreign.StablePtr
80 -- -----------------------------------------------------------------------------
81 -- running a statement interactively
84 = RunOk [Name] -- ^ names bound by this evaluation
85 | RunFailed -- ^ statement failed compilation
86 | RunException Exception -- ^ statement raised an exception
87 | RunBreak ThreadId [Name] BreakInfo
90 = Break HValue BreakInfo ThreadId
91 -- ^ the computation hit a breakpoint
92 | Complete (Either Exception [HValue])
93 -- ^ the computation completed with either an exception or a value
97 resumeStmt :: String, -- the original statement
98 resumeThreadId :: ThreadId, -- thread running the computation
99 resumeBreakMVar :: MVar (),
100 resumeStatMVar :: MVar Status,
101 resumeBindings :: ([Id], TyVarSet),
102 resumeFinalIds :: [Id], -- [Id] to bind on completion
103 resumeApStack :: HValue, -- The object from which we can get
104 -- value of the free variables.
105 resumeBreakInfo :: BreakInfo, -- the breakpoint we stopped at.
106 resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
107 -- to fetch the ModDetails & ModBreaks
109 resumeHistory :: [History],
110 resumeHistoryIx :: Int -- 0 <==> at the top of the history
113 getResumeContext :: Session -> IO [Resume]
114 getResumeContext s = withSession s (return . ic_resume . hsc_IC)
121 isStep RunToCompletion = False
126 historyApStack :: HValue,
127 historyBreakInfo :: BreakInfo
130 getHistorySpan :: Session -> History -> IO SrcSpan
131 getHistorySpan s hist = withSession s $ \hsc_env -> do
132 let inf = historyBreakInfo hist
133 num = breakInfo_number inf
134 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
135 Just hmi -> return (modBreaks_locs (md_modBreaks (hm_details hmi)) ! num)
136 _ -> panic "getHistorySpan"
139 [Main.hs:42:(1,0)-(3,52)] *Main> :history 2
142 [Main.hs:42:(1,0)-(3,52)] *Main> :back
143 Logged breakpoint at Foo.hs:1:3-5
147 [-1: Foo.hs:1:3-5] *Main> :back
148 Logged breakpoint at Bar.hs:5:23-48
151 [-2: Bar.hs:5:23-48] *Main> :forward
152 Logged breakpoint at Foo.hs:1:3-5
156 [-1: Foo.hs:1:3-5] *Main> :cont
160 -- | Run a statement in the current interactive context. Statement
161 -- may bind multple values.
162 runStmt :: Session -> String -> SingleStep -> IO RunResult
163 runStmt (Session ref) expr step
165 hsc_env <- readIORef ref
167 breakMVar <- newEmptyMVar -- wait on this when we hit a breakpoint
168 statusMVar <- newEmptyMVar -- wait on this when a computation is running
170 -- Turn off -fwarn-unused-bindings when running a statement, to hide
171 -- warnings about the implicit bindings we introduce.
172 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
173 hsc_env' = hsc_env{ hsc_dflags = dflags' }
175 maybe_stuff <- hscStmt hsc_env' expr
178 Nothing -> return RunFailed
179 Just (ids, hval) -> do
181 when (isStep step) $ setStepFlag
183 -- set the onBreakAction to be performed when we hit a
184 -- breakpoint this is visible in the Byte Code
185 -- Interpreter, thus it is a global variable,
186 -- implemented with stable pointers
187 withBreakAction breakMVar statusMVar $ do
189 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
190 status <- sandboxIO statusMVar thing_to_run
192 let ic = hsc_IC hsc_env
193 bindings = (ic_tmp_ids ic, ic_tyvars ic)
197 traceRunStatus expr ref bindings ids
198 breakMVar statusMVar status emptyHistory
200 handleRunStatus expr ref bindings ids
201 breakMVar statusMVar status emptyHistory
204 emptyHistory = nilBL 50 -- keep a log of length 50
206 handleRunStatus expr ref bindings final_ids breakMVar statusMVar status
209 -- did we hit a breakpoint or did we complete?
210 (Break apStack info tid) -> do
211 hsc_env <- readIORef ref
212 (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env apStack info
214 resume = Resume expr tid breakMVar statusMVar
215 bindings final_ids apStack info span
217 hsc_env2 = pushResume hsc_env1 resume
219 writeIORef ref hsc_env2
220 return (RunBreak tid names info)
221 (Complete either_hvals) ->
223 Left e -> return (RunException e)
225 hsc_env <- readIORef ref
226 let final_ic = extendInteractiveContext (hsc_IC hsc_env)
227 final_ids emptyVarSet
228 -- the bound Ids never have any free TyVars
229 final_names = map idName final_ids
230 writeIORef ref hsc_env{hsc_IC=final_ic}
231 Linker.extendLinkEnv (zip final_names hvals)
232 return (RunOk final_names)
235 traceRunStatus expr ref bindings final_ids
236 breakMVar statusMVar status history = do
237 hsc_env <- readIORef ref
239 -- when tracing, if we hit a breakpoint that is not explicitly
240 -- enabled, then we just log the event in the history and continue.
241 (Break apStack info tid) -> do
242 b <- isBreakEnabled hsc_env info
246 let history' = consBL (History apStack info) history
247 -- probably better make history strict here, otherwise
248 -- our BoundedList will be pointless.
251 status <- withBreakAction breakMVar statusMVar $ do
253 (do putMVar breakMVar () -- awaken the stopped thread
255 (takeMVar statusMVar) -- and wait for the result
256 traceRunStatus expr ref bindings final_ids
257 breakMVar statusMVar status history'
261 handle_normally = handleRunStatus expr ref bindings final_ids
262 breakMVar statusMVar status history
265 isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
266 isBreakEnabled hsc_env inf =
267 case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
269 w <- getBreak (modBreaks_flags (md_modBreaks (hm_details hmi)))
270 (breakInfo_number inf)
271 case w of Just n -> return (n /= 0); _other -> return False
276 foreign import ccall "rts_setStepFlag" setStepFlag :: IO ()
278 -- this points to the IO action that is executed when a breakpoint is hit
279 foreign import ccall "&breakPointIOAction"
280 breakPointIOAction :: Ptr (StablePtr (BreakInfo -> HValue -> IO ()))
282 -- When running a computation, we redirect ^C exceptions to the running
283 -- thread. ToDo: we might want a way to continue even if the target
284 -- thread doesn't die when it receives the exception... "this thread
285 -- is not responding".
286 sandboxIO :: MVar Status -> IO [HValue] -> IO Status
287 sandboxIO statusMVar thing =
289 (forkIO (do res <- Exception.try thing
290 putMVar statusMVar (Complete res)))
291 (takeMVar statusMVar)
293 withInterruptsSentTo :: IO ThreadId -> IO r -> IO r
294 withInterruptsSentTo io get_result = do
295 ts <- takeMVar interruptTargetThread
297 putMVar interruptTargetThread (child:ts)
298 get_result `finally` modifyMVar_ interruptTargetThread (return.tail)
300 withBreakAction breakMVar statusMVar io
301 = bracket setBreakAction resetBreakAction (\_ -> io)
304 stablePtr <- newStablePtr onBreak
305 poke breakPointIOAction stablePtr
308 onBreak info apStack = do
310 putMVar statusMVar (Break apStack info tid)
313 resetBreakAction stablePtr = do
314 poke breakPointIOAction noBreakStablePtr
315 freeStablePtr stablePtr
317 noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
318 noBreakAction info apStack = putStrLn "*** Ignoring breakpoint"
320 resume :: Session -> SingleStep -> IO RunResult
321 resume (Session ref) step
323 hsc_env <- readIORef ref
324 let ic = hsc_IC hsc_env
325 resume = ic_resume ic
328 [] -> throwDyn (ProgramError "not stopped at a breakpoint")
330 -- unbind the temporary locals by restoring the TypeEnv from
331 -- before the breakpoint, and drop this Resume from the
332 -- InteractiveContext.
333 let (resume_tmp_ids, resume_tyvars) = resumeBindings r
334 ic' = ic { ic_tmp_ids = resume_tmp_ids,
335 ic_tyvars = resume_tyvars,
337 writeIORef ref hsc_env{ hsc_IC = ic' }
339 -- remove any bindings created since the breakpoint from the
340 -- linker's environment
341 let new_names = map idName (filter (`notElem` resume_tmp_ids)
343 Linker.deleteFromLinkEnv new_names
345 when (isStep step) $ setStepFlag
347 Resume expr tid breakMVar statusMVar bindings
348 final_ids apStack info _ _ _ -> do
349 withBreakAction breakMVar statusMVar $ do
350 status <- withInterruptsSentTo
351 (do putMVar breakMVar ()
352 -- this awakens the stopped thread...
354 (takeMVar statusMVar)
355 -- and wait for the result
358 traceRunStatus expr ref bindings final_ids
359 breakMVar statusMVar status emptyHistory
361 handleRunStatus expr ref bindings final_ids
362 breakMVar statusMVar status emptyHistory
365 back :: Session -> IO ([Name], Int, SrcSpan)
368 forward :: Session -> IO ([Name], Int, SrcSpan)
369 forward = moveHist (subtract 1)
371 moveHist fn (Session ref) = do
372 hsc_env <- readIORef ref
373 case ic_resume (hsc_IC hsc_env) of
374 [] -> throwDyn (ProgramError "not stopped at a breakpoint")
376 let ix = resumeHistoryIx r
377 history = resumeHistory r
380 when (new_ix >= length history) $
381 throwDyn (ProgramError "no more logged breakpoints")
383 throwDyn (ProgramError "already at the beginning of the history")
386 update_ic apStack info = do
387 (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env
389 let ic = hsc_IC hsc_env1
390 r' = r { resumeHistoryIx = new_ix }
391 ic' = ic { ic_resume = r':rs }
393 writeIORef ref hsc_env1{ hsc_IC = ic' }
395 return (names, new_ix, span)
397 -- careful: we want apStack to be the AP_STACK itself, not a thunk
398 -- around it, hence the cases are carefully constructed below to
399 -- make this the case. ToDo: this is v. fragile, do something better.
402 Resume { resumeApStack = apStack,
403 resumeBreakInfo = info } ->
404 update_ic apStack info
405 else case history !! (new_ix - 1) of
406 History apStack info ->
407 update_ic apStack info
409 -- -----------------------------------------------------------------------------
410 -- After stopping at a breakpoint, add free variables to the environment
412 bindLocalsAtBreakpoint
416 -> IO (HscEnv, [Name], SrcSpan)
417 bindLocalsAtBreakpoint hsc_env apStack info = do
420 mod_name = moduleName (breakInfo_module info)
421 mod_details = fmap hm_details (lookupUFM (hsc_HPT hsc_env) mod_name)
422 breaks = md_modBreaks (expectJust "handlRunStatus" mod_details)
423 index = breakInfo_number info
424 vars = breakInfo_vars info
425 result_ty = breakInfo_resty info
426 occs = modBreaks_vars breaks ! index
427 span = modBreaks_locs breaks ! index
429 -- filter out any unboxed ids; we can't bind these at the prompt
430 let pointers = filter (\(id,_) -> isPointer id) vars
431 isPointer id | PtrRep <- idPrimRep id = True
434 let (ids, offsets) = unzip pointers
436 -- It might be that getIdValFromApStack fails, because the AP_STACK
437 -- has been accidentally evaluated, or something else has gone wrong.
438 -- So that we don't fall over in a heap when this happens, just don't
439 -- bind any free variables instead, and we emit a warning.
440 mb_hValues <- mapM (getIdValFromApStack apStack) offsets
441 let filtered_ids = [ id | (id, Just _) <- zip ids mb_hValues ]
442 when (any isNothing mb_hValues) $
443 debugTraceMsg (hsc_dflags hsc_env) 1 $
444 text "Warning: _result has been evaluated, some bindings have been lost"
446 new_ids <- zipWithM mkNewId occs filtered_ids
447 let names = map idName new_ids
449 -- make an Id for _result. We use the Unique of the FastString "_result";
450 -- we don't care about uniqueness here, because there will only be one
451 -- _result in scope at any time.
452 let result_fs = FSLIT("_result")
453 result_name = mkInternalName (getUnique result_fs)
454 (mkVarOccFS result_fs) span
455 result_id = Id.mkLocalId result_name result_ty
457 -- for each Id we're about to bind in the local envt:
458 -- - skolemise the type variables in its type, so they can't
459 -- be randomly unified with other types. These type variables
460 -- can only be resolved by type reconstruction in RtClosureInspect
461 -- - tidy the type variables
462 -- - globalise the Id (Ids are supposed to be Global, apparently).
464 let all_ids | isPointer result_id = result_id : new_ids
465 | otherwise = new_ids
466 (id_tys, tyvarss) = mapAndUnzip (skolemiseTy.idType) all_ids
467 (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
468 new_tyvars = unionVarSets tyvarss
469 final_ids = zipWith setIdType all_ids tidy_tys
471 let ictxt0 = hsc_IC hsc_env
472 ictxt1 = extendInteractiveContext ictxt0 final_ids new_tyvars
474 Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
475 Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
476 return (hsc_env{ hsc_IC = ictxt1 }, result_name:names, span)
478 mkNewId :: OccName -> Id -> IO Id
480 let uniq = idUnique id
481 loc = nameSrcSpan (idName id)
482 name = mkInternalName uniq occ loc
484 new_id = Id.mkGlobalId VanillaGlobal name ty (idInfo id)
487 skolemiseTy :: Type -> (Type, TyVarSet)
488 skolemiseTy ty = (substTy subst ty, mkVarSet new_tyvars)
489 where env = mkVarEnv (zip tyvars new_tyvar_tys)
490 subst = mkTvSubst emptyInScopeSet env
491 tyvars = varSetElems (tyVarsOfType ty)
492 new_tyvars = map skolemiseTyVar tyvars
493 new_tyvar_tys = map mkTyVarTy new_tyvars
495 skolemiseTyVar :: TyVar -> TyVar
496 skolemiseTyVar tyvar = mkTcTyVar (tyVarName tyvar) (tyVarKind tyvar)
497 (SkolemTv RuntimeUnkSkol)
499 getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
500 getIdValFromApStack apStack (I# stackDepth) = do
501 case getApStackVal# apStack (stackDepth +# 1#) of
502 -- The +1 is magic! I don't know where it comes
503 -- from, but this makes things line up. --SDM
506 0# -> return Nothing -- AP_STACK not found
507 _ -> return (Just (unsafeCoerce# result))
509 pushResume :: HscEnv -> Resume -> HscEnv
510 pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
512 ictxt0 = hsc_IC hsc_env
513 ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
515 -- -----------------------------------------------------------------------------
516 -- Abandoning a resume context
518 abandon :: Session -> IO Bool
519 abandon (Session ref) = do
520 hsc_env <- readIORef ref
521 let ic = hsc_IC hsc_env
522 resume = ic_resume ic
526 writeIORef ref hsc_env{ hsc_IC = ic { ic_resume = rs } }
530 abandonAll :: Session -> IO Bool
531 abandonAll (Session ref) = do
532 hsc_env <- readIORef ref
533 let ic = hsc_IC hsc_env
534 resume = ic_resume ic
538 writeIORef ref hsc_env{ hsc_IC = ic { ic_resume = [] } }
542 -- when abandoning a computation we have to
543 -- (a) kill the thread with an async exception, so that the
544 -- computation itself is stopped, and
545 -- (b) fill in the MVar. This step is necessary because any
546 -- thunks that were under evaluation will now be updated
547 -- with the partial computation, which still ends in takeMVar,
548 -- so any attempt to evaluate one of these thunks will block
549 -- unless we fill in the MVar.
550 -- See test break010.
551 abandon_ :: Resume -> IO ()
553 killThread (resumeThreadId r)
554 putMVar (resumeBreakMVar r) ()
556 -- -----------------------------------------------------------------------------
557 -- Bounded list, optimised for repeated cons
559 data BoundedList a = BL
560 {-# UNPACK #-} !Int -- length
561 {-# UNPACK #-} !Int -- bound
563 [a] -- right, list is (left ++ reverse right)
565 nilBL :: Int -> BoundedList a
566 nilBL bound = BL 0 bound [] []
568 consBL a (BL len bound left right)
569 | len < bound = BL (len+1) bound (a:left) right
570 | null right = BL len bound [a] $! tail (reverse left)
571 | otherwise = BL len bound (a:left) $! tail right
573 toListBL (BL _ _ left right) = left ++ reverse right
575 -- lenBL (BL len _ _ _) = len
577 -- -----------------------------------------------------------------------------
578 -- | Set the interactive evaluation context.
580 -- Setting the context doesn't throw away any bindings; the bindings
581 -- we've built up in the InteractiveContext simply move to the new
582 -- module. They always shadow anything in scope in the current context.
583 setContext :: Session
584 -> [Module] -- entire top level scope of these modules
585 -> [Module] -- exports only of these modules
587 setContext sess@(Session ref) toplev_mods export_mods = do
588 hsc_env <- readIORef ref
589 let old_ic = hsc_IC hsc_env
590 hpt = hsc_HPT hsc_env
592 export_env <- mkExportEnv hsc_env export_mods
593 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
594 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
595 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
596 ic_exports = export_mods,
597 ic_rn_gbl_env = all_env }}
599 -- Make a GlobalRdrEnv based on the exports of the modules only.
600 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
601 mkExportEnv hsc_env mods = do
602 stuff <- mapM (getModuleExports hsc_env) mods
604 (_msgs, mb_name_sets) = unzip stuff
605 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
606 | (Just avails, mod) <- zip mb_name_sets mods ]
608 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
610 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
611 nameSetToGlobalRdrEnv names mod =
612 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
613 | name <- nameSetToList names ]
615 vanillaProv :: ModuleName -> Provenance
616 -- We're building a GlobalRdrEnv as if the user imported
617 -- all the specified modules into the global interactive module
618 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
620 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
622 is_dloc = srcLocSpan interactiveSrcLoc }
624 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
626 = case lookupUFM hpt (moduleName modl) of
627 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
628 showSDoc (ppr modl)))
630 case mi_globals (hm_iface details) of
632 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
633 ++ showSDoc (ppr modl)))
634 Just env -> return env
636 -- | Get the interactive evaluation context, consisting of a pair of the
637 -- set of modules from which we take the full top-level scope, and the set
638 -- of modules from which we take just the exports respectively.
639 getContext :: Session -> IO ([Module],[Module])
640 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
641 return (ic_toplev_scope ic, ic_exports ic))
643 -- | Returns 'True' if the specified module is interpreted, and hence has
644 -- its full top-level scope available.
645 moduleIsInterpreted :: Session -> Module -> IO Bool
646 moduleIsInterpreted s modl = withSession s $ \h ->
647 if modulePackageId modl /= thisPackage (hsc_dflags h)
649 else case lookupUFM (hsc_HPT h) (moduleName modl) of
650 Just details -> return (isJust (mi_globals (hm_iface details)))
651 _not_a_home_module -> return False
653 -- | Looks up an identifier in the current interactive context (for :info)
654 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
655 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
657 -- | Returns all names in scope in the current interactive context
658 getNamesInScope :: Session -> IO [Name]
659 getNamesInScope s = withSession s $ \hsc_env -> do
660 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
662 getRdrNamesInScope :: Session -> IO [RdrName]
663 getRdrNamesInScope s = withSession s $ \hsc_env -> do
666 gbl_rdrenv = ic_rn_gbl_env ic
668 gbl_names = concat (map greToRdrNames (globalRdrEnvElts gbl_rdrenv))
669 lcl_names = map (mkRdrUnqual.nameOccName.idName) ids
671 return (gbl_names ++ lcl_names)
674 -- ToDo: move to RdrName
675 greToRdrNames :: GlobalRdrElt -> [RdrName]
676 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
679 Imported specs -> concat (map do_spec (map is_decl specs))
681 occ = nameOccName name
684 | is_qual decl_spec = [qual]
685 | otherwise = [unqual,qual]
686 where qual = Qual (is_as decl_spec) occ
688 -- | Parses a string as an identifier, and returns the list of 'Name's that
689 -- the identifier can refer to in the current interactive context.
690 parseName :: Session -> String -> IO [Name]
691 parseName s str = withSession s $ \hsc_env -> do
692 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
693 case maybe_rdr_name of
695 Just (L _ rdr_name) -> do
696 mb_names <- tcRnLookupRdrName hsc_env rdr_name
700 -- ToDo: should return error messages
702 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
703 -- entity known to GHC, including 'Name's defined using 'runStmt'.
704 lookupName :: Session -> Name -> IO (Maybe TyThing)
705 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
707 -- -----------------------------------------------------------------------------
708 -- Getting the type of an expression
710 -- | Get the type of an expression
711 exprType :: Session -> String -> IO (Maybe Type)
712 exprType s expr = withSession s $ \hsc_env -> do
713 maybe_stuff <- hscTcExpr hsc_env expr
715 Nothing -> return Nothing
716 Just ty -> return (Just tidy_ty)
718 tidy_ty = tidyType emptyTidyEnv ty
720 -- -----------------------------------------------------------------------------
721 -- Getting the kind of a type
723 -- | Get the kind of a type
724 typeKind :: Session -> String -> IO (Maybe Kind)
725 typeKind s str = withSession s $ \hsc_env -> do
726 maybe_stuff <- hscKcType hsc_env str
728 Nothing -> return Nothing
729 Just kind -> return (Just kind)
731 -----------------------------------------------------------------------------
732 -- cmCompileExpr: compile an expression and deliver an HValue
734 compileExpr :: Session -> String -> IO (Maybe HValue)
735 compileExpr s expr = withSession s $ \hsc_env -> do
736 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
738 Nothing -> return Nothing
739 Just (ids, hval) -> do
741 hvals <- (unsafeCoerce# hval) :: IO [HValue]
744 ([n],[hv]) -> return (Just hv)
745 _ -> panic "compileExpr"
747 -- -----------------------------------------------------------------------------
748 -- Compile an expression into a dynamic
750 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
751 dynCompileExpr ses expr = do
752 (full,exports) <- getContext ses
753 setContext ses full $
755 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
757 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
758 res <- withSession ses (flip hscStmt stmt)
759 setContext ses full exports
761 Nothing -> return Nothing
762 Just (ids, hvals) -> do
763 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
765 (_:[], v:[]) -> return (Just v)
766 _ -> panic "dynCompileExpr"
768 -----------------------------------------------------------------------------
769 -- show a module and it's source/object filenames
771 showModule :: Session -> ModSummary -> IO String
772 showModule s mod_summary = withSession s $ \hsc_env ->
773 isModuleInterpreted s mod_summary >>= \interpreted ->
774 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
776 isModuleInterpreted :: Session -> ModSummary -> IO Bool
777 isModuleInterpreted s mod_summary = withSession s $ \hsc_env ->
778 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
779 Nothing -> panic "missing linkable"
780 Just mod_info -> return (not obj_linkable)
782 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
784 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
785 obtainTerm1 sess force mb_ty x = withSession sess $ \hsc_env -> cvObtainTerm hsc_env force mb_ty (unsafeCoerce# x)
787 obtainTerm :: Session -> Bool -> Id -> IO Term
788 obtainTerm sess force id = withSession sess $ \hsc_env -> do
789 hv <- Linker.getHValue hsc_env (varName id)
790 cvObtainTerm hsc_env force (Just$ idType id) hv