1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
25 Target(..), TargetId(..), Phase,
32 -- * Loading\/compiling the program
34 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
35 workingDirectoryChanged,
36 checkModule, CheckedModule(..),
37 TypecheckedSource, ParsedSource, RenamedSource,
39 -- * Inspecting the module structure of the program
40 ModuleGraph, ModSummary(..), ModLocation(..),
45 -- * Inspecting modules
50 modInfoPrintUnqualified,
53 modInfoIsExportedName,
58 PrintUnqualified, alwaysQualify,
60 -- * Interactive evaluation
61 getBindings, getPrintUnqual,
63 setContext, getContext,
78 -- * Abstract syntax elements
81 Module, mkModule, pprModule,
85 nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
91 isImplicitId, isDeadBinder,
92 isExportedId, isLocalId, isGlobalId,
94 isPrimOpId, isFCallId, isClassOpId_maybe,
95 isDataConWorkId, idDataCon,
96 isBottomingId, isDictonaryId,
97 recordSelectorFieldLabel,
99 -- ** Type constructors
101 tyConTyVars, tyConDataCons, tyConArity,
102 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
103 synTyConDefn, synTyConRhs,
109 -- ** Data constructors
111 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
112 dataConIsInfix, isVanillaDataCon,
114 StrictnessMark(..), isMarkedStrict,
118 classMethods, classSCTheta, classTvsFds,
123 instanceDFunId, pprInstance, pprInstanceHdr,
125 -- ** Types and Kinds
126 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
129 ThetaType, pprThetaArrow,
135 module HsSyn, -- ToDo: remove extraneous bits
139 defaultFixity, maxPrecedence,
143 -- ** Source locations
147 GhcException(..), showGhcException,
157 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
158 * we need to expose DynFlags, so should parseDynamicFlags really be
159 part of this interface?
160 * what StaticFlags should we expose, if any?
163 #include "HsVersions.h"
166 import qualified Linker
167 import Linker ( HValue, extendLinkEnv )
168 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
169 tcRnLookupName, getModuleExports )
170 import RdrName ( plusGlobalRdrEnv, Provenance(..),
171 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
172 emptyGlobalRdrEnv, mkGlobalRdrEnv )
173 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
174 import Type ( tidyType )
175 import VarEnv ( emptyTidyEnv )
176 import GHC.Exts ( unsafeCoerce# )
179 import Packages ( initPackages )
180 import NameSet ( NameSet, nameSetToList, elemNameSet )
181 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
184 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
185 pprThetaArrow, pprParendType, splitForAllTys,
187 import Id ( Id, idType, isImplicitId, isDeadBinder,
188 isExportedId, isLocalId, isGlobalId,
189 isRecordSelector, recordSelectorFieldLabel,
190 isPrimOpId, isFCallId, isClassOpId_maybe,
191 isDataConWorkId, idDataCon,
194 import TysPrim ( alphaTyVars )
195 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
196 isPrimTyCon, isFunTyCon, tyConArity,
197 tyConTyVars, tyConDataCons, synTyConDefn, synTyConRhs )
198 import Class ( Class, classSCTheta, classTvsFds, classMethods )
199 import FunDeps ( pprFundeps )
200 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
201 dataConFieldLabels, dataConStrictMarks,
202 dataConIsInfix, isVanillaDataCon )
203 import Name ( Name, nameModule, NamedThing(..), nameParent_maybe,
204 nameSrcLoc, nameOccName )
205 import OccName ( parenSymOcc )
206 import NameEnv ( nameEnvElts )
207 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
209 import DriverPipeline
210 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
211 import GetImports ( getImports )
212 import Packages ( isHomePackage )
214 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
218 import SysTools ( initSysTools, cleanTempFiles )
223 import Bag ( unitBag )
224 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
225 mkPlainErrMsg, printBagOfErrors, printErrorsAndWarnings )
226 import qualified ErrUtils
228 import StringBuffer ( StringBuffer, hGetStringBuffer )
230 import SysTools ( cleanTempFilesExcept )
232 import TcType ( tcSplitSigmaTy, isDictTy )
233 import Maybes ( expectJust, mapCatMaybes )
235 import Control.Concurrent
236 import System.Directory ( getModificationTime, doesFileExist )
237 import Data.Maybe ( isJust, isNothing )
238 import Data.List ( partition, nub )
239 import qualified Data.List as List
240 import Control.Monad ( unless, when )
241 import System.Exit ( exitWith, ExitCode(..) )
242 import System.Time ( ClockTime )
243 import Control.Exception as Exception hiding (handle)
246 import System.IO.Error ( isDoesNotExistError )
247 import System.IO.Unsafe ( unsafePerformIO )
248 import Prelude hiding (init)
250 #if __GLASGOW_HASKELL__ < 600
251 import System.IO as System.IO.Error ( try )
253 import System.IO.Error ( try )
256 -- -----------------------------------------------------------------------------
257 -- Exception handlers
259 -- | Install some default exception handlers and run the inner computation.
260 -- Unless you want to handle exceptions yourself, you should wrap this around
261 -- the top level of your program. The default handlers output the error
262 -- message(s) to stderr and exit cleanly.
263 defaultErrorHandler :: DynFlags -> IO a -> IO a
264 defaultErrorHandler dflags inner =
265 -- top-level exception handler: any unrecognised exception is a compiler bug.
266 handle (\exception -> do
269 -- an IO exception probably isn't our fault, so don't panic
271 fatalErrorMsg dflags (text (show exception))
272 AsyncException StackOverflow ->
273 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
275 fatalErrorMsg dflags (text (show (Panic (show exception))))
276 exitWith (ExitFailure 1)
279 -- program errors: messages with locations attached. Sometimes it is
280 -- convenient to just throw these as exceptions.
281 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
282 exitWith (ExitFailure 1)) $
284 -- error messages propagated as exceptions
285 handleDyn (\dyn -> do
288 PhaseFailed _ code -> exitWith code
289 Interrupted -> exitWith (ExitFailure 1)
290 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
291 exitWith (ExitFailure 1)
295 -- | Install a default cleanup handler to remove temporary files
296 -- deposited by a GHC run. This is seperate from
297 -- 'defaultErrorHandler', because you might want to override the error
298 -- handling, but still get the ordinary cleanup behaviour.
299 defaultCleanupHandler :: DynFlags -> IO a -> IO a
300 defaultCleanupHandler dflags inner =
301 -- make sure we clean up after ourselves
302 later (unless (dopt Opt_KeepTmpFiles dflags) $
303 cleanTempFiles dflags)
304 -- exceptions will be blocked while we clean the temporary files,
305 -- so there shouldn't be any difficulty if we receive further
310 -- | Initialises GHC. This must be done /once/ only. Takes the
311 -- TopDir path without the '-B' prefix.
313 init :: Maybe String -> IO ()
316 main_thread <- myThreadId
317 putMVar interruptTargetThread [main_thread]
318 installSignalHandlers
320 dflags0 <- initSysTools mbMinusB defaultDynFlags
321 writeIORef v_initDynFlags dflags0
323 -- | Initialises GHC. This must be done /once/ only. Takes the
324 -- command-line arguments. All command-line arguments which aren't
325 -- understood by GHC will be returned.
327 initFromArgs :: [String] -> IO [String]
331 where -- Grab the -B option if there is one
332 (minusB_args, argv1) = partition (prefixMatch "-B") args
333 mbMinusB | null minusB_args
336 = Just (drop 2 (last minusB_args))
338 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
339 -- stores the DynFlags between the call to init and subsequent
340 -- calls to newSession.
342 -- | Starts a new session. A session consists of a set of loaded
343 -- modules, a set of options (DynFlags), and an interactive context.
344 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
346 newSession :: GhcMode -> IO Session
348 dflags0 <- readIORef v_initDynFlags
349 dflags <- initDynFlags dflags0
350 env <- newHscEnv dflags{ ghcMode=mode }
354 -- tmp: this breaks the abstraction, but required because DriverMkDepend
355 -- needs to call the Finder. ToDo: untangle this.
356 sessionHscEnv :: Session -> IO HscEnv
357 sessionHscEnv (Session ref) = readIORef ref
359 withSession :: Session -> (HscEnv -> IO a) -> IO a
360 withSession (Session ref) f = do h <- readIORef ref; f h
362 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
363 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
365 -- -----------------------------------------------------------------------------
368 -- | Grabs the DynFlags from the Session
369 getSessionDynFlags :: Session -> IO DynFlags
370 getSessionDynFlags s = withSession s (return . hsc_dflags)
372 -- | Updates the DynFlags in a Session
373 setSessionDynFlags :: Session -> DynFlags -> IO ()
374 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
376 -- | If there is no -o option, guess the name of target executable
377 -- by using top-level source file name as a base.
378 guessOutputFile :: Session -> IO ()
379 guessOutputFile s = modifySession s $ \env ->
380 let dflags = hsc_dflags env
381 mod_graph = hsc_mod_graph env
382 mainModuleSrcPath, guessedName :: Maybe String
383 mainModuleSrcPath = do
384 let isMain = (== mainModIs dflags) . ms_mod
385 [ms] <- return (filter isMain mod_graph)
386 ml_hs_file (ms_location ms)
387 guessedName = fmap basenameOf mainModuleSrcPath
389 case outputFile dflags of
391 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
393 -- -----------------------------------------------------------------------------
396 -- ToDo: think about relative vs. absolute file paths. And what
397 -- happens when the current directory changes.
399 -- | Sets the targets for this session. Each target may be a module name
400 -- or a filename. The targets correspond to the set of root modules for
401 -- the program\/library. Unloading the current program is achieved by
402 -- setting the current set of targets to be empty, followed by load.
403 setTargets :: Session -> [Target] -> IO ()
404 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
406 -- | returns the current set of targets
407 getTargets :: Session -> IO [Target]
408 getTargets s = withSession s (return . hsc_targets)
410 -- | Add another target
411 addTarget :: Session -> Target -> IO ()
413 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
416 removeTarget :: Session -> TargetId -> IO ()
417 removeTarget s target_id
418 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
420 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
422 -- Attempts to guess what Target a string refers to. This function implements
423 -- the --make/GHCi command-line syntax for filenames:
425 -- - if the string looks like a Haskell source filename, then interpret
427 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
429 -- - otherwise interpret the string as a module name
431 guessTarget :: String -> Maybe Phase -> IO Target
432 guessTarget file (Just phase)
433 = return (Target (TargetFile file (Just phase)) Nothing)
434 guessTarget file Nothing
435 | isHaskellSrcFilename file
436 = return (Target (TargetFile file Nothing) Nothing)
438 = do exists <- doesFileExist hs_file
440 then return (Target (TargetFile hs_file Nothing) Nothing)
442 exists <- doesFileExist lhs_file
444 then return (Target (TargetFile lhs_file Nothing) Nothing)
446 return (Target (TargetModule (mkModule file)) Nothing)
448 hs_file = file `joinFileExt` "hs"
449 lhs_file = file `joinFileExt` "lhs"
451 -- -----------------------------------------------------------------------------
452 -- Loading the program
454 -- Perform a dependency analysis starting from the current targets
455 -- and update the session with the new module graph.
456 depanal :: Session -> [Module] -> Bool -> IO (Maybe ModuleGraph)
457 depanal (Session ref) excluded_mods allow_dup_roots = do
458 hsc_env <- readIORef ref
460 dflags = hsc_dflags hsc_env
461 gmode = ghcMode (hsc_dflags hsc_env)
462 targets = hsc_targets hsc_env
463 old_graph = hsc_mod_graph hsc_env
465 showPass dflags "Chasing dependencies"
466 when (gmode == BatchCompile) $
467 debugTraceMsg dflags 1 (hcat [
468 text "Chasing modules from: ",
469 hcat (punctuate comma (map pprTarget targets))])
471 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
473 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
478 -- | The result of load.
480 = LoadOk Errors -- ^ all specified targets were loaded successfully.
481 | LoadFailed Errors -- ^ not all modules were loaded.
483 type Errors = [String]
485 data ErrMsg = ErrMsg {
486 errMsgSeverity :: Severity, -- warning, error, etc.
487 errMsgSpans :: [SrcSpan],
488 errMsgShortDoc :: Doc,
489 errMsgExtraInfo :: Doc
496 | LoadDependenciesOf Module
498 -- | Try to load the program. If a Module is supplied, then just
499 -- attempt to load up to this target. If no Module is supplied,
500 -- then try to load all targets.
501 load :: Session -> LoadHowMuch -> IO SuccessFlag
502 load s@(Session ref) how_much
504 -- Dependency analysis first. Note that this fixes the module graph:
505 -- even if we don't get a fully successful upsweep, the full module
506 -- graph is still retained in the Session. We can tell which modules
507 -- were successfully loaded by inspecting the Session's HPT.
508 mb_graph <- depanal s [] False
510 Just mod_graph -> load2 s how_much mod_graph
511 Nothing -> return Failed
513 load2 s@(Session ref) how_much mod_graph = do
515 hsc_env <- readIORef ref
517 let hpt1 = hsc_HPT hsc_env
518 let dflags = hsc_dflags hsc_env
519 let ghci_mode = ghcMode dflags -- this never changes
521 -- The "bad" boot modules are the ones for which we have
522 -- B.hs-boot in the module graph, but no B.hs
523 -- The downsweep should have ensured this does not happen
525 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
527 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
528 not (ms_mod s `elem` all_home_mods)]
530 ASSERT( null bad_boot_mods ) return ()
532 -- mg2_with_srcimps drops the hi-boot nodes, returning a
533 -- graph with cycles. Among other things, it is used for
534 -- backing out partially complete cycles following a failed
535 -- upsweep, and for removing from hpt all the modules
536 -- not in strict downwards closure, during calls to compile.
537 let mg2_with_srcimps :: [SCC ModSummary]
538 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
540 -- check the stability property for each module.
541 stable_mods@(stable_obj,stable_bco)
542 | BatchCompile <- ghci_mode = ([],[])
543 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
545 -- prune bits of the HPT which are definitely redundant now,
547 pruned_hpt = pruneHomePackageTable hpt1
548 (flattenSCCs mg2_with_srcimps)
553 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
554 text "Stable BCO:" <+> ppr stable_bco)
556 -- Unload any modules which are going to be re-linked this time around.
557 let stable_linkables = [ linkable
558 | m <- stable_obj++stable_bco,
559 Just hmi <- [lookupModuleEnv pruned_hpt m],
560 Just linkable <- [hm_linkable hmi] ]
561 unload hsc_env stable_linkables
563 -- We could at this point detect cycles which aren't broken by
564 -- a source-import, and complain immediately, but it seems better
565 -- to let upsweep_mods do this, so at least some useful work gets
566 -- done before the upsweep is abandoned.
567 --hPutStrLn stderr "after tsort:\n"
568 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
570 -- Now do the upsweep, calling compile for each module in
571 -- turn. Final result is version 3 of everything.
573 -- Topologically sort the module graph, this time including hi-boot
574 -- nodes, and possibly just including the portion of the graph
575 -- reachable from the module specified in the 2nd argument to load.
576 -- This graph should be cycle-free.
577 -- If we're restricting the upsweep to a portion of the graph, we
578 -- also want to retain everything that is still stable.
579 let full_mg :: [SCC ModSummary]
580 full_mg = topSortModuleGraph False mod_graph Nothing
582 maybe_top_mod = case how_much of
584 LoadDependenciesOf m -> Just m
587 partial_mg0 :: [SCC ModSummary]
588 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
590 -- LoadDependenciesOf m: we want the upsweep to stop just
591 -- short of the specified module (unless the specified module
594 | LoadDependenciesOf mod <- how_much
595 = ASSERT( case last partial_mg0 of
596 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
597 List.init partial_mg0
603 | AcyclicSCC ms <- full_mg,
604 ms_mod ms `elem` stable_obj++stable_bco,
605 ms_mod ms `notElem` [ ms_mod ms' |
606 AcyclicSCC ms' <- partial_mg ] ]
608 mg = stable_mg ++ partial_mg
610 -- clean up between compilations
611 let cleanup = cleanTempFilesExcept dflags
612 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
614 (upsweep_ok, hsc_env1, modsUpswept)
615 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
616 pruned_hpt stable_mods cleanup mg
618 -- Make modsDone be the summaries for each home module now
619 -- available; this should equal the domain of hpt3.
620 -- Get in in a roughly top .. bottom order (hence reverse).
622 let modsDone = reverse modsUpswept
624 -- Try and do linking in some form, depending on whether the
625 -- upsweep was completely or only partially successful.
627 if succeeded upsweep_ok
630 -- Easy; just relink it all.
631 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
633 -- Clean up after ourselves
634 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
636 -- Issue a warning for the confusing case where the user
637 -- said '-o foo' but we're not going to do any linking.
638 -- We attempt linking if either (a) one of the modules is
639 -- called Main, or (b) the user said -no-hs-main, indicating
640 -- that main() is going to come from somewhere else.
642 let ofile = outputFile dflags
643 let no_hs_main = dopt Opt_NoHsMain dflags
645 main_mod = mainModIs dflags
646 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
647 do_linking = a_root_is_Main || no_hs_main
649 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
650 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
651 "but no output will be generated\n" ++
652 "because there is no " ++ moduleString main_mod ++ " module."))
654 -- link everything together
655 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
657 loadFinish Succeeded linkresult ref hsc_env1
660 -- Tricky. We need to back out the effects of compiling any
661 -- half-done cycles, both so as to clean up the top level envs
662 -- and to avoid telling the interactive linker to link them.
663 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
666 = map ms_mod modsDone
667 let mods_to_zap_names
668 = findPartiallyCompletedCycles modsDone_names
671 = filter ((`notElem` mods_to_zap_names).ms_mod)
674 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
677 -- Clean up after ourselves
678 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
680 -- there should be no Nothings where linkables should be, now
681 ASSERT(all (isJust.hm_linkable)
682 (moduleEnvElts (hsc_HPT hsc_env))) do
684 -- Link everything together
685 linkresult <- link ghci_mode dflags False hpt4
687 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
688 loadFinish Failed linkresult ref hsc_env4
690 -- Finish up after a load.
692 -- If the link failed, unload everything and return.
693 loadFinish all_ok Failed ref hsc_env
694 = do unload hsc_env []
695 writeIORef ref $! discardProg hsc_env
698 -- Empty the interactive context and set the module context to the topmost
699 -- newly loaded module, or the Prelude if none were loaded.
700 loadFinish all_ok Succeeded ref hsc_env
701 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
705 -- Forget the current program, but retain the persistent info in HscEnv
706 discardProg :: HscEnv -> HscEnv
708 = hsc_env { hsc_mod_graph = emptyMG,
709 hsc_IC = emptyInteractiveContext,
710 hsc_HPT = emptyHomePackageTable }
712 -- used to fish out the preprocess output files for the purposes of
713 -- cleaning up. The preprocessed file *might* be the same as the
714 -- source file, but that doesn't do any harm.
715 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
717 -- -----------------------------------------------------------------------------
721 CheckedModule { parsedSource :: ParsedSource,
722 renamedSource :: Maybe RenamedSource,
723 typecheckedSource :: Maybe TypecheckedSource,
724 checkedModuleInfo :: Maybe ModuleInfo
726 -- ToDo: improvements that could be made here:
727 -- if the module succeeded renaming but not typechecking,
728 -- we can still get back the GlobalRdrEnv and exports, so
729 -- perhaps the ModuleInfo should be split up into separate
730 -- fields within CheckedModule.
732 type ParsedSource = Located (HsModule RdrName)
733 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name])
734 type TypecheckedSource = LHsBinds Id
737 -- - things that aren't in the output of the typechecker right now:
741 -- - type/data/newtype declarations
742 -- - class declarations
744 -- - extra things in the typechecker's output:
745 -- - default methods are turned into top-level decls.
746 -- - dictionary bindings
749 -- | This is the way to get access to parsed and typechecked source code
750 -- for a module. 'checkModule' loads all the dependencies of the specified
751 -- module in the Session, and then attempts to typecheck the module. If
752 -- successful, it returns the abstract syntax for the module.
753 checkModule :: Session -> Module -> IO (Maybe CheckedModule)
754 checkModule session@(Session ref) mod = do
755 -- load up the dependencies first
756 r <- load session (LoadDependenciesOf mod)
757 if (failed r) then return Nothing else do
759 -- now parse & typecheck the module
760 hsc_env <- readIORef ref
761 let mg = hsc_mod_graph hsc_env
762 case [ ms | ms <- mg, ms_mod ms == mod ] of
765 -- Add in the OPTIONS from the source file This is nasty:
766 -- we've done this once already, in the compilation manager
767 -- It might be better to cache the flags in the
768 -- ml_hspp_file field, say
769 let dflags0 = hsc_dflags hsc_env
770 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
771 filename = expectJust "checkModule" (ml_hs_file (ms_location ms))
772 opts = getOptionsFromStringBuffer hspp_buf filename
773 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
774 if (not (null leftovers))
775 then do printErrorsAndWarnings dflags1 (optionsErrorMsgs leftovers opts filename)
779 mbChecked <- hscFileCheck hsc_env{hsc_dflags=dflags1} ms
781 Nothing -> return Nothing
782 Just (HscChecked parsed renamed Nothing) ->
783 return (Just (CheckedModule {
784 parsedSource = parsed,
785 renamedSource = renamed,
786 typecheckedSource = Nothing,
787 checkedModuleInfo = Nothing }))
788 Just (HscChecked parsed renamed
789 (Just (tc_binds, rdr_env, details))) -> do
790 let minf = ModuleInfo {
791 minf_type_env = md_types details,
792 minf_exports = md_exports details,
793 minf_rdr_env = Just rdr_env,
794 minf_instances = md_insts details
796 return (Just (CheckedModule {
797 parsedSource = parsed,
798 renamedSource = renamed,
799 typecheckedSource = Just tc_binds,
800 checkedModuleInfo = Just minf }))
804 -- ---------------------------------------------------------------------------
807 unload :: HscEnv -> [Linkable] -> IO ()
808 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
809 = case ghcMode (hsc_dflags hsc_env) of
810 BatchCompile -> return ()
811 JustTypecheck -> return ()
813 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
815 Interactive -> panic "unload: no interpreter"
817 other -> panic "unload: strange mode"
819 -- -----------------------------------------------------------------------------
823 Stability tells us which modules definitely do not need to be recompiled.
824 There are two main reasons for having stability:
826 - avoid doing a complete upsweep of the module graph in GHCi when
827 modules near the bottom of the tree have not changed.
829 - to tell GHCi when it can load object code: we can only load object code
830 for a module when we also load object code fo all of the imports of the
831 module. So we need to know that we will definitely not be recompiling
832 any of these modules, and we can use the object code.
834 NB. stability is of no importance to BatchCompile at all, only Interactive.
835 (ToDo: what about JustTypecheck?)
837 The stability check is as follows. Both stableObject and
838 stableBCO are used during the upsweep phase later.
841 stable m = stableObject m || stableBCO m
844 all stableObject (imports m)
845 && old linkable does not exist, or is == on-disk .o
846 && date(on-disk .o) > date(.hs)
849 all stable (imports m)
850 && date(BCO) > date(.hs)
853 These properties embody the following ideas:
855 - if a module is stable:
856 - if it has been compiled in a previous pass (present in HPT)
857 then it does not need to be compiled or re-linked.
858 - if it has not been compiled in a previous pass,
859 then we only need to read its .hi file from disk and
860 link it to produce a ModDetails.
862 - if a modules is not stable, we will definitely be at least
863 re-linking, and possibly re-compiling it during the upsweep.
864 All non-stable modules can (and should) therefore be unlinked
867 - Note that objects are only considered stable if they only depend
868 on other objects. We can't link object code against byte code.
872 :: HomePackageTable -- HPT from last compilation
873 -> [SCC ModSummary] -- current module graph (cyclic)
874 -> [Module] -- all home modules
875 -> ([Module], -- stableObject
876 [Module]) -- stableBCO
878 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
880 checkSCC (stable_obj, stable_bco) scc0
881 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
882 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
883 | otherwise = (stable_obj, stable_bco)
885 scc = flattenSCC scc0
886 scc_mods = map ms_mod scc
887 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
889 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
890 -- all imports outside the current SCC, but in the home pkg
892 stable_obj_imps = map (`elem` stable_obj) scc_allimps
893 stable_bco_imps = map (`elem` stable_bco) scc_allimps
900 and (zipWith (||) stable_obj_imps stable_bco_imps)
904 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
908 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
909 Just hmi | Just l <- hm_linkable hmi
910 -> isObjectLinkable l && t == linkableTime l
912 -- why '>=' rather than '>' above? If the filesystem stores
913 -- times to the nearset second, we may occasionally find that
914 -- the object & source have the same modification time,
915 -- especially if the source was automatically generated
916 -- and compiled. Using >= is slightly unsafe, but it matches
920 = case lookupModuleEnv hpt (ms_mod ms) of
921 Just hmi | Just l <- hm_linkable hmi ->
922 not (isObjectLinkable l) &&
923 linkableTime l >= ms_hs_date ms
926 ms_allimps :: ModSummary -> [Module]
927 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
929 -- -----------------------------------------------------------------------------
930 -- Prune the HomePackageTable
932 -- Before doing an upsweep, we can throw away:
934 -- - For non-stable modules:
935 -- - all ModDetails, all linked code
936 -- - all unlinked code that is out of date with respect to
939 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
940 -- space at the end of the upsweep, because the topmost ModDetails of the
941 -- old HPT holds on to the entire type environment from the previous
944 pruneHomePackageTable
947 -> ([Module],[Module])
950 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
951 = mapModuleEnv prune hpt
953 | is_stable modl = hmi'
954 | otherwise = hmi'{ hm_details = emptyModDetails }
956 modl = mi_module (hm_iface hmi)
957 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
958 = hmi{ hm_linkable = Nothing }
961 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
963 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
965 is_stable m = m `elem` stable_obj || m `elem` stable_bco
967 -- -----------------------------------------------------------------------------
969 -- Return (names of) all those in modsDone who are part of a cycle
970 -- as defined by theGraph.
971 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
972 findPartiallyCompletedCycles modsDone theGraph
976 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
977 chew ((CyclicSCC vs):rest)
978 = let names_in_this_cycle = nub (map ms_mod vs)
980 = nub ([done | done <- modsDone,
981 done `elem` names_in_this_cycle])
982 chewed_rest = chew rest
984 if notNull mods_in_this_cycle
985 && length mods_in_this_cycle < length names_in_this_cycle
986 then mods_in_this_cycle ++ chewed_rest
989 -- -----------------------------------------------------------------------------
992 -- This is where we compile each module in the module graph, in a pass
993 -- from the bottom to the top of the graph.
995 -- There better had not be any cyclic groups here -- we check for them.
998 :: HscEnv -- Includes initially-empty HPT
999 -> HomePackageTable -- HPT from last time round (pruned)
1000 -> ([Module],[Module]) -- stable modules (see checkStability)
1001 -> IO () -- How to clean up unwanted tmp files
1002 -> [SCC ModSummary] -- Mods to do (the worklist)
1004 HscEnv, -- With an updated HPT
1005 [ModSummary]) -- Mods which succeeded
1007 upsweep hsc_env old_hpt stable_mods cleanup mods
1008 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1010 upsweep' hsc_env old_hpt stable_mods cleanup
1012 = return (Succeeded, hsc_env, [])
1014 upsweep' hsc_env old_hpt stable_mods cleanup
1015 (CyclicSCC ms:_) _ _
1016 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1017 return (Failed, hsc_env, [])
1019 upsweep' hsc_env old_hpt stable_mods cleanup
1020 (AcyclicSCC mod:mods) mod_index nmods
1021 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1022 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1023 -- (moduleEnvElts (hsc_HPT hsc_env)))
1025 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1028 cleanup -- Remove unwanted tmp files between compilations
1031 Nothing -> return (Failed, hsc_env, [])
1033 { let this_mod = ms_mod mod
1035 -- Add new info to hsc_env
1036 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
1038 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1040 -- Space-saving: delete the old HPT entry
1041 -- for mod BUT if mod is a hs-boot
1042 -- node, don't delete it. For the
1043 -- interface, the HPT entry is probaby for the
1044 -- main Haskell source file. Deleting it
1045 -- would force .. (what?? --SDM)
1046 old_hpt1 | isBootSummary mod = old_hpt
1047 | otherwise = delModuleEnv old_hpt this_mod
1049 ; (restOK, hsc_env2, modOKs)
1050 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1051 mods (mod_index+1) nmods
1052 ; return (restOK, hsc_env2, mod:modOKs)
1056 -- Compile a single module. Always produce a Linkable for it if
1057 -- successful. If no compilation happened, return the old Linkable.
1058 upsweep_mod :: HscEnv
1060 -> ([Module],[Module])
1062 -> Int -- index of module
1063 -> Int -- total number of modules
1064 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1066 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1069 this_mod = ms_mod summary
1070 mb_obj_date = ms_obj_date summary
1071 obj_fn = ml_obj_file (ms_location summary)
1072 hs_date = ms_hs_date summary
1074 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1075 compile_it = upsweep_compile hsc_env old_hpt this_mod
1076 summary mod_index nmods
1078 case ghcMode (hsc_dflags hsc_env) of
1081 -- Batch-compilating is easy: just check whether we have
1082 -- an up-to-date object file. If we do, then the compiler
1083 -- needs to do a recompilation check.
1084 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1086 findObjectLinkable this_mod obj_fn obj_date
1087 compile_it (Just linkable)
1094 _ | is_stable_obj, isJust old_hmi ->
1096 -- object is stable, and we have an entry in the
1097 -- old HPT: nothing to do
1099 | is_stable_obj, isNothing old_hmi -> do
1101 findObjectLinkable this_mod obj_fn
1102 (expectJust "upseep1" mb_obj_date)
1103 compile_it (Just linkable)
1104 -- object is stable, but we need to load the interface
1105 -- off disk to make a HMI.
1108 ASSERT(isJust old_hmi) -- must be in the old_hpt
1110 -- BCO is stable: nothing to do
1112 | Just hmi <- old_hmi,
1113 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1114 linkableTime l >= ms_hs_date summary ->
1116 -- we have an old BCO that is up to date with respect
1117 -- to the source: do a recompilation check as normal.
1121 -- no existing code at all: we must recompile.
1123 is_stable_obj = this_mod `elem` stable_obj
1124 is_stable_bco = this_mod `elem` stable_bco
1126 old_hmi = lookupModuleEnv old_hpt this_mod
1128 -- Run hsc to compile a module
1129 upsweep_compile hsc_env old_hpt this_mod summary
1131 mb_old_linkable = do
1133 -- The old interface is ok if it's in the old HPT
1134 -- a) we're compiling a source file, and the old HPT
1135 -- entry is for a source file
1136 -- b) we're compiling a hs-boot file
1137 -- Case (b) allows an hs-boot file to get the interface of its
1138 -- real source file on the second iteration of the compilation
1139 -- manager, but that does no harm. Otherwise the hs-boot file
1140 -- will always be recompiled
1143 = case lookupModuleEnv old_hpt this_mod of
1145 Just hm_info | isBootSummary summary -> Just iface
1146 | not (mi_boot iface) -> Just iface
1147 | otherwise -> Nothing
1149 iface = hm_iface hm_info
1151 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1155 -- Compilation failed. Compile may still have updated the PCS, tho.
1156 CompErrs -> return Nothing
1158 -- Compilation "succeeded", and may or may not have returned a new
1159 -- linkable (depending on whether compilation was actually performed
1161 CompOK new_details new_iface new_linkable
1162 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1163 hm_details = new_details,
1164 hm_linkable = new_linkable }
1165 return (Just new_info)
1168 -- Filter modules in the HPT
1169 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1170 retainInTopLevelEnvs keep_these hpt
1171 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1173 , let mb_mod_info = lookupModuleEnv hpt mod
1174 , isJust mb_mod_info ]
1176 -- ---------------------------------------------------------------------------
1177 -- Topological sort of the module graph
1180 :: Bool -- Drop hi-boot nodes? (see below)
1184 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1185 -- The resulting list of strongly-connected-components is in topologically
1186 -- sorted order, starting with the module(s) at the bottom of the
1187 -- dependency graph (ie compile them first) and ending with the ones at
1190 -- Drop hi-boot nodes (first boolean arg)?
1192 -- False: treat the hi-boot summaries as nodes of the graph,
1193 -- so the graph must be acyclic
1195 -- True: eliminate the hi-boot nodes, and instead pretend
1196 -- the a source-import of Foo is an import of Foo
1197 -- The resulting graph has no hi-boot nodes, but can by cyclic
1199 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1200 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1201 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1202 = stronglyConnComp (map vertex_fn (reachable graph root))
1204 -- restrict the graph to just those modules reachable from
1205 -- the specified module. We do this by building a graph with
1206 -- the full set of nodes, and determining the reachable set from
1207 -- the specified node.
1208 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1209 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1211 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1212 | otherwise = throwDyn (ProgramError "module does not exist")
1214 moduleGraphNodes :: Bool -> [ModSummary]
1215 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1216 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1218 -- Drop hs-boot nodes by using HsSrcFile as the key
1219 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1220 | otherwise = HsBootFile
1222 -- We use integers as the keys for the SCC algorithm
1223 nodes :: [(ModSummary, Int, [Int])]
1224 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1225 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1226 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) )
1228 , not (isBootSummary s && drop_hs_boot_nodes) ]
1229 -- Drop the hi-boot ones if told to do so
1231 key_map :: NodeMap Int
1232 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1235 lookup_key :: HscSource -> Module -> Maybe Int
1236 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1238 out_edge_keys :: HscSource -> [Module] -> [Int]
1239 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1240 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1241 -- the IsBootInterface parameter True; else False
1244 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1245 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1247 msKey :: ModSummary -> NodeKey
1248 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1250 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1251 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1253 nodeMapElts :: NodeMap a -> [a]
1254 nodeMapElts = eltsFM
1256 -----------------------------------------------------------------------------
1257 -- Downsweep (dependency analysis)
1259 -- Chase downwards from the specified root set, returning summaries
1260 -- for all home modules encountered. Only follow source-import
1263 -- We pass in the previous collection of summaries, which is used as a
1264 -- cache to avoid recalculating a module summary if the source is
1267 -- The returned list of [ModSummary] nodes has one node for each home-package
1268 -- module, plus one for any hs-boot files. The imports of these nodes
1269 -- are all there, including the imports of non-home-package modules.
1272 -> [ModSummary] -- Old summaries
1273 -> [Module] -- Ignore dependencies on these; treat
1274 -- them as if they were package modules
1275 -> Bool -- True <=> allow multiple targets to have
1276 -- the same module name; this is
1277 -- very useful for ghc -M
1278 -> IO (Maybe [ModSummary])
1279 -- The elts of [ModSummary] all have distinct
1280 -- (Modules, IsBoot) identifiers, unless the Bool is true
1281 -- in which case there can be repeats
1282 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1283 = -- catch error messages and return them
1284 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1285 rootSummaries <- mapM getRootSummary roots
1286 let root_map = mkRootMap rootSummaries
1287 checkDuplicates root_map
1288 summs <- loop (concatMap msDeps rootSummaries) root_map
1291 roots = hsc_targets hsc_env
1293 old_summary_map :: NodeMap ModSummary
1294 old_summary_map = mkNodeMap old_summaries
1296 getRootSummary :: Target -> IO ModSummary
1297 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1298 = do exists <- doesFileExist file
1300 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1301 else throwDyn $ mkPlainErrMsg noSrcSpan $
1302 text "can't find file:" <+> text file
1303 getRootSummary (Target (TargetModule modl) maybe_buf)
1304 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1305 (L rootLoc modl) maybe_buf excl_mods
1306 case maybe_summary of
1307 Nothing -> packageModErr modl
1310 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1312 -- In a root module, the filename is allowed to diverge from the module
1313 -- name, so we have to check that there aren't multiple root files
1314 -- defining the same module (otherwise the duplicates will be silently
1315 -- ignored, leading to confusing behaviour).
1316 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1317 checkDuplicates root_map
1318 | allow_dup_roots = return ()
1319 | null dup_roots = return ()
1320 | otherwise = multiRootsErr (head dup_roots)
1322 dup_roots :: [[ModSummary]] -- Each at least of length 2
1323 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1325 loop :: [(Located Module,IsBootInterface)]
1326 -- Work list: process these modules
1327 -> NodeMap [ModSummary]
1328 -- Visited set; the range is a list because
1329 -- the roots can have the same module names
1330 -- if allow_dup_roots is True
1332 -- The result includes the worklist, except
1333 -- for those mentioned in the visited set
1334 loop [] done = return (concat (nodeMapElts done))
1335 loop ((wanted_mod, is_boot) : ss) done
1336 | Just summs <- lookupFM done key
1337 = if isSingleton summs then
1340 do { multiRootsErr summs; return [] }
1341 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1342 is_boot wanted_mod Nothing excl_mods
1344 Nothing -> loop ss done
1345 Just s -> loop (msDeps s ++ ss)
1346 (addToFM done key [s]) }
1348 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1350 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1351 mkRootMap summaries = addListToFM_C (++) emptyFM
1352 [ (msKey s, [s]) | s <- summaries ]
1354 msDeps :: ModSummary -> [(Located Module, IsBootInterface)]
1355 -- (msDeps s) returns the dependencies of the ModSummary s.
1356 -- A wrinkle is that for a {-# SOURCE #-} import we return
1357 -- *both* the hs-boot file
1358 -- *and* the source file
1359 -- as "dependencies". That ensures that the list of all relevant
1360 -- modules always contains B.hs if it contains B.hs-boot.
1361 -- Remember, this pass isn't doing the topological sort. It's
1362 -- just gathering the list of all relevant ModSummaries
1364 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1365 ++ [ (m,False) | m <- ms_imps s ]
1367 -----------------------------------------------------------------------------
1368 -- Summarising modules
1370 -- We have two types of summarisation:
1372 -- * Summarise a file. This is used for the root module(s) passed to
1373 -- cmLoadModules. The file is read, and used to determine the root
1374 -- module name. The module name may differ from the filename.
1376 -- * Summarise a module. We are given a module name, and must provide
1377 -- a summary. The finder is used to locate the file in which the module
1382 -> [ModSummary] -- old summaries
1383 -> FilePath -- source file name
1384 -> Maybe Phase -- start phase
1385 -> Maybe (StringBuffer,ClockTime)
1388 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1389 -- we can use a cached summary if one is available and the
1390 -- source file hasn't changed, But we have to look up the summary
1391 -- by source file, rather than module name as we do in summarise.
1392 | Just old_summary <- findSummaryBySourceFile old_summaries file
1394 let location = ms_location old_summary
1396 -- return the cached summary if the source didn't change
1397 src_timestamp <- case maybe_buf of
1398 Just (_,t) -> return t
1399 Nothing -> getModificationTime file
1400 -- The file exists; we checked in getRootSummary above.
1401 -- If it gets removed subsequently, then this
1402 -- getModificationTime may fail, but that's the right
1405 if ms_hs_date old_summary == src_timestamp
1406 then do -- update the object-file timestamp
1407 obj_timestamp <- getObjTimestamp location False
1408 return old_summary{ ms_obj_date = obj_timestamp }
1416 let dflags = hsc_dflags hsc_env
1418 (dflags', hspp_fn, buf)
1419 <- preprocessFile dflags file mb_phase maybe_buf
1421 (srcimps,the_imps, L _ mod) <- getImports dflags' buf hspp_fn
1423 -- Make a ModLocation for this file
1424 location <- mkHomeModLocation dflags mod file
1426 -- Tell the Finder cache where it is, so that subsequent calls
1427 -- to findModule will find it, even if it's not on any search path
1428 addHomeModuleToFinder hsc_env mod location
1430 src_timestamp <- case maybe_buf of
1431 Just (_,t) -> return t
1432 Nothing -> getModificationTime file
1433 -- getMofificationTime may fail
1435 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1437 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1438 ms_location = location,
1439 ms_hspp_file = Just hspp_fn,
1440 ms_hspp_buf = Just buf,
1441 ms_srcimps = srcimps, ms_imps = the_imps,
1442 ms_hs_date = src_timestamp,
1443 ms_obj_date = obj_timestamp })
1445 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1446 findSummaryBySourceFile summaries file
1447 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1448 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1452 -- Summarise a module, and pick up source and timestamp.
1455 -> NodeMap ModSummary -- Map of old summaries
1456 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1457 -> Located Module -- Imported module to be summarised
1458 -> Maybe (StringBuffer, ClockTime)
1459 -> [Module] -- Modules to exclude
1460 -> IO (Maybe ModSummary) -- Its new summary
1462 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1463 | wanted_mod `elem` excl_mods
1466 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1467 = do -- Find its new timestamp; all the
1468 -- ModSummaries in the old map have valid ml_hs_files
1469 let location = ms_location old_summary
1470 src_fn = expectJust "summariseModule" (ml_hs_file location)
1472 -- check the modification time on the source file, and
1473 -- return the cached summary if it hasn't changed. If the
1474 -- file has disappeared, we need to call the Finder again.
1476 Just (_,t) -> check_timestamp old_summary location src_fn t
1478 m <- System.IO.Error.try (getModificationTime src_fn)
1480 Right t -> check_timestamp old_summary location src_fn t
1481 Left e | isDoesNotExistError e -> find_it
1482 | otherwise -> ioError e
1484 | otherwise = find_it
1486 dflags = hsc_dflags hsc_env
1488 hsc_src = if is_boot then HsBootFile else HsSrcFile
1490 check_timestamp old_summary location src_fn src_timestamp
1491 | ms_hs_date old_summary == src_timestamp = do
1492 -- update the object-file timestamp
1493 obj_timestamp <- getObjTimestamp location is_boot
1494 return (Just old_summary{ ms_obj_date = obj_timestamp })
1496 -- source changed: find and re-summarise. We call the finder
1497 -- again, because the user may have moved the source file.
1498 new_summary location src_fn src_timestamp
1501 -- Don't use the Finder's cache this time. If the module was
1502 -- previously a package module, it may have now appeared on the
1503 -- search path, so we want to consider it to be a home module. If
1504 -- the module was previously a home module, it may have moved.
1505 uncacheModule hsc_env wanted_mod
1506 found <- findModule hsc_env wanted_mod True {-explicit-}
1509 | not (isHomePackage pkg) -> return Nothing
1510 -- Drop external-pkg
1511 | isJust (ml_hs_file location) -> just_found location
1513 err -> noModError dflags loc wanted_mod err
1516 just_found location = do
1517 -- Adjust location to point to the hs-boot source file,
1518 -- hi file, object file, when is_boot says so
1519 let location' | is_boot = addBootSuffixLocn location
1520 | otherwise = location
1521 src_fn = expectJust "summarise2" (ml_hs_file location')
1523 -- Check that it exists
1524 -- It might have been deleted since the Finder last found it
1525 maybe_t <- modificationTimeIfExists src_fn
1527 Nothing -> noHsFileErr loc src_fn
1528 Just t -> new_summary location' src_fn t
1531 new_summary location src_fn src_timestamp
1533 -- Preprocess the source file and get its imports
1534 -- The dflags' contains the OPTIONS pragmas
1535 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1536 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1538 when (mod_name /= wanted_mod) $
1539 throwDyn $ mkPlainErrMsg mod_loc $
1540 text "file name does not match module name"
1541 <+> quotes (ppr mod_name)
1543 -- Find the object timestamp, and return the summary
1544 obj_timestamp <- getObjTimestamp location is_boot
1546 return (Just ( ModSummary { ms_mod = wanted_mod,
1547 ms_hsc_src = hsc_src,
1548 ms_location = location,
1549 ms_hspp_file = Just hspp_fn,
1550 ms_hspp_buf = Just buf,
1551 ms_srcimps = srcimps,
1553 ms_hs_date = src_timestamp,
1554 ms_obj_date = obj_timestamp }))
1557 getObjTimestamp location is_boot
1558 = if is_boot then return Nothing
1559 else modificationTimeIfExists (ml_obj_file location)
1562 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1563 -> IO (DynFlags, FilePath, StringBuffer)
1564 preprocessFile dflags src_fn mb_phase Nothing
1566 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1567 buf <- hGetStringBuffer hspp_fn
1568 return (dflags', hspp_fn, buf)
1570 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1572 -- case we bypass the preprocessing stage?
1574 local_opts = getOptionsFromStringBuffer buf src_fn
1576 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1580 | Just (Unlit _) <- mb_phase = True
1581 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1582 -- note: local_opts is only required if there's no Unlit phase
1583 | dopt Opt_Cpp dflags' = True
1584 | dopt Opt_Pp dflags' = True
1587 when needs_preprocessing $
1588 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1590 return (dflags', src_fn, buf)
1593 -----------------------------------------------------------------------------
1595 -----------------------------------------------------------------------------
1597 noModError :: DynFlags -> SrcSpan -> Module -> FindResult -> IO ab
1598 -- ToDo: we don't have a proper line number for this error
1599 noModError dflags loc wanted_mod err
1600 = throwDyn $ mkPlainErrMsg loc $ cantFindError dflags wanted_mod err
1602 noHsFileErr loc path
1603 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1606 = throwDyn $ mkPlainErrMsg noSrcSpan $
1607 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1609 multiRootsErr :: [ModSummary] -> IO ()
1610 multiRootsErr summs@(summ1:_)
1611 = throwDyn $ mkPlainErrMsg noSrcSpan $
1612 text "module" <+> quotes (ppr mod) <+>
1613 text "is defined in multiple files:" <+>
1614 sep (map text files)
1617 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1619 cyclicModuleErr :: [ModSummary] -> SDoc
1621 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1622 2 (vcat (map show_one ms))
1624 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1625 nest 2 $ ptext SLIT("imports:") <+>
1626 (pp_imps HsBootFile (ms_srcimps ms)
1627 $$ pp_imps HsSrcFile (ms_imps ms))]
1628 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1629 pp_imps src mods = fsep (map (show_mod src) mods)
1632 -- | Inform GHC that the working directory has changed. GHC will flush
1633 -- its cache of module locations, since it may no longer be valid.
1634 -- Note: if you change the working directory, you should also unload
1635 -- the current program (set targets to empty, followed by load).
1636 workingDirectoryChanged :: Session -> IO ()
1637 workingDirectoryChanged s = withSession s $ \hsc_env ->
1638 flushFinderCache (hsc_FC hsc_env)
1640 -- -----------------------------------------------------------------------------
1641 -- inspecting the session
1643 -- | Get the module dependency graph.
1644 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1645 getModuleGraph s = withSession s (return . hsc_mod_graph)
1647 isLoaded :: Session -> Module -> IO Bool
1648 isLoaded s m = withSession s $ \hsc_env ->
1649 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1651 getBindings :: Session -> IO [TyThing]
1652 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1654 getPrintUnqual :: Session -> IO PrintUnqualified
1655 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1657 -- | Container for information about a 'Module'.
1658 data ModuleInfo = ModuleInfo {
1659 minf_type_env :: TypeEnv,
1660 minf_exports :: NameSet,
1661 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1662 minf_instances :: [Instance]
1663 -- ToDo: this should really contain the ModIface too
1665 -- We don't want HomeModInfo here, because a ModuleInfo applies
1666 -- to package modules too.
1668 -- | Request information about a loaded 'Module'
1669 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1670 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1671 let mg = hsc_mod_graph hsc_env
1672 if mdl `elem` map ms_mod mg
1673 then getHomeModuleInfo hsc_env mdl
1675 {- if isHomeModule (hsc_dflags hsc_env) mdl
1677 else -} getPackageModuleInfo hsc_env mdl
1678 -- getPackageModuleInfo will attempt to find the interface, so
1679 -- we don't want to call it for a home module, just in case there
1680 -- was a problem loading the module and the interface doesn't
1681 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1683 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1684 getPackageModuleInfo hsc_env mdl = do
1686 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1688 Nothing -> return Nothing
1690 eps <- readIORef (hsc_EPS hsc_env)
1693 n_list = nameSetToList names
1694 tys = [ ty | name <- n_list,
1695 Just ty <- [lookupTypeEnv pte name] ]
1697 return (Just (ModuleInfo {
1698 minf_type_env = mkTypeEnv tys,
1699 minf_exports = names,
1700 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names mdl,
1701 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1704 -- bogusly different for non-GHCI (ToDo)
1708 getHomeModuleInfo hsc_env mdl =
1709 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1710 Nothing -> return Nothing
1712 let details = hm_details hmi
1713 return (Just (ModuleInfo {
1714 minf_type_env = md_types details,
1715 minf_exports = md_exports details,
1716 minf_rdr_env = mi_globals $! hm_iface hmi,
1717 minf_instances = md_insts details
1720 -- | The list of top-level entities defined in a module
1721 modInfoTyThings :: ModuleInfo -> [TyThing]
1722 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1724 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1725 modInfoTopLevelScope minf
1726 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1728 modInfoExports :: ModuleInfo -> [Name]
1729 modInfoExports minf = nameSetToList $! minf_exports minf
1731 -- | Returns the instances defined by the specified module.
1732 -- Warning: currently unimplemented for package modules.
1733 modInfoInstances :: ModuleInfo -> [Instance]
1734 modInfoInstances = minf_instances
1736 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1737 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1739 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1740 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1742 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1743 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1744 case lookupTypeEnv (minf_type_env minf) name of
1745 Just tyThing -> return (Just tyThing)
1747 eps <- readIORef (hsc_EPS hsc_env)
1748 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1750 isDictonaryId :: Id -> Bool
1752 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1754 -- | Looks up a global name: that is, any top-level name in any
1755 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1756 -- the interactive context, and therefore does not require a preceding
1758 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1759 lookupGlobalName s name = withSession s $ \hsc_env -> do
1760 eps <- readIORef (hsc_EPS hsc_env)
1761 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1763 -- -----------------------------------------------------------------------------
1764 -- Misc exported utils
1766 dataConType :: DataCon -> Type
1767 dataConType dc = idType (dataConWrapId dc)
1769 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1770 pprParenSymName :: NamedThing a => a -> SDoc
1771 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1773 -- ----------------------------------------------------------------------------
1778 -- - Data and Typeable instances for HsSyn.
1780 -- ToDo: check for small transformations that happen to the syntax in
1781 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1783 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1784 -- to get from TyCons, Ids etc. to TH syntax (reify).
1786 -- :browse will use either lm_toplev or inspect lm_interface, depending
1787 -- on whether the module is interpreted or not.
1789 -- This is for reconstructing refactored source code
1790 -- Calls the lexer repeatedly.
1791 -- ToDo: add comment tokens to token stream
1792 getTokenStream :: Session -> Module -> IO [Located Token]
1795 -- -----------------------------------------------------------------------------
1796 -- Interactive evaluation
1800 -- | Set the interactive evaluation context.
1802 -- Setting the context doesn't throw away any bindings; the bindings
1803 -- we've built up in the InteractiveContext simply move to the new
1804 -- module. They always shadow anything in scope in the current context.
1805 setContext :: Session
1806 -> [Module] -- entire top level scope of these modules
1807 -> [Module] -- exports only of these modules
1809 setContext (Session ref) toplevs exports = do
1810 hsc_env <- readIORef ref
1811 let old_ic = hsc_IC hsc_env
1812 hpt = hsc_HPT hsc_env
1814 mapM_ (checkModuleExists hsc_env hpt) exports
1815 export_env <- mkExportEnv hsc_env exports
1816 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1817 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1818 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1819 ic_exports = exports,
1820 ic_rn_gbl_env = all_env }}
1823 -- Make a GlobalRdrEnv based on the exports of the modules only.
1824 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1825 mkExportEnv hsc_env mods = do
1826 stuff <- mapM (getModuleExports hsc_env) mods
1828 (_msgs, mb_name_sets) = unzip stuff
1829 gres = [ nameSetToGlobalRdrEnv name_set mod
1830 | (Just name_set, mod) <- zip mb_name_sets mods ]
1832 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1834 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1835 nameSetToGlobalRdrEnv names mod =
1836 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1837 | name <- nameSetToList names ]
1839 vanillaProv :: Module -> Provenance
1840 -- We're building a GlobalRdrEnv as if the user imported
1841 -- all the specified modules into the global interactive module
1842 vanillaProv mod = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1844 decl = ImpDeclSpec { is_mod = mod, is_as = mod,
1846 is_dloc = srcLocSpan interactiveSrcLoc }
1848 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1849 checkModuleExists hsc_env hpt mod =
1850 case lookupModuleEnv hpt mod of
1851 Just mod_info -> return ()
1852 _not_a_home_module -> do
1853 res <- findPackageModule hsc_env mod True
1855 Found _ _ -> return ()
1856 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1857 throwDyn (CmdLineError (showSDoc msg))
1859 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1860 mkTopLevEnv hpt modl
1861 = case lookupModuleEnv hpt modl of
1863 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1864 ++ showSDoc (pprModule modl)))
1866 case mi_globals (hm_iface details) of
1868 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1869 ++ showSDoc (pprModule modl)))
1870 Just env -> return env
1872 -- | Get the interactive evaluation context, consisting of a pair of the
1873 -- set of modules from which we take the full top-level scope, and the set
1874 -- of modules from which we take just the exports respectively.
1875 getContext :: Session -> IO ([Module],[Module])
1876 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1877 return (ic_toplev_scope ic, ic_exports ic))
1879 -- | Returns 'True' if the specified module is interpreted, and hence has
1880 -- its full top-level scope available.
1881 moduleIsInterpreted :: Session -> Module -> IO Bool
1882 moduleIsInterpreted s modl = withSession s $ \h ->
1883 case lookupModuleEnv (hsc_HPT h) modl of
1884 Just details -> return (isJust (mi_globals (hm_iface details)))
1885 _not_a_home_module -> return False
1887 -- | Looks up an identifier in the current interactive context (for :info)
1888 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
1889 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
1891 -- | Returns all names in scope in the current interactive context
1892 getNamesInScope :: Session -> IO [Name]
1893 getNamesInScope s = withSession s $ \hsc_env -> do
1894 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1896 getRdrNamesInScope :: Session -> IO [RdrName]
1897 getRdrNamesInScope s = withSession s $ \hsc_env -> do
1898 let env = ic_rn_gbl_env (hsc_IC hsc_env)
1899 return (concat (map greToRdrNames (globalRdrEnvElts env)))
1901 -- ToDo: move to RdrName
1902 greToRdrNames :: GlobalRdrElt -> [RdrName]
1903 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
1905 LocalDef -> [unqual]
1906 Imported specs -> concat (map do_spec (map is_decl specs))
1908 occ = nameOccName name
1911 | is_qual decl_spec = [qual]
1912 | otherwise = [unqual,qual]
1913 where qual = Qual (is_as decl_spec) occ
1915 -- | Parses a string as an identifier, and returns the list of 'Name's that
1916 -- the identifier can refer to in the current interactive context.
1917 parseName :: Session -> String -> IO [Name]
1918 parseName s str = withSession s $ \hsc_env -> do
1919 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1920 case maybe_rdr_name of
1921 Nothing -> return []
1922 Just (L _ rdr_name) -> do
1923 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1925 Nothing -> return []
1926 Just ns -> return ns
1927 -- ToDo: should return error messages
1929 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1930 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1931 lookupName :: Session -> Name -> IO (Maybe TyThing)
1932 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
1934 -- -----------------------------------------------------------------------------
1935 -- Getting the type of an expression
1937 -- | Get the type of an expression
1938 exprType :: Session -> String -> IO (Maybe Type)
1939 exprType s expr = withSession s $ \hsc_env -> do
1940 maybe_stuff <- hscTcExpr hsc_env expr
1942 Nothing -> return Nothing
1943 Just ty -> return (Just tidy_ty)
1945 tidy_ty = tidyType emptyTidyEnv ty
1947 -- -----------------------------------------------------------------------------
1948 -- Getting the kind of a type
1950 -- | Get the kind of a type
1951 typeKind :: Session -> String -> IO (Maybe Kind)
1952 typeKind s str = withSession s $ \hsc_env -> do
1953 maybe_stuff <- hscKcType hsc_env str
1955 Nothing -> return Nothing
1956 Just kind -> return (Just kind)
1958 -----------------------------------------------------------------------------
1959 -- cmCompileExpr: compile an expression and deliver an HValue
1961 compileExpr :: Session -> String -> IO (Maybe HValue)
1962 compileExpr s expr = withSession s $ \hsc_env -> do
1963 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1965 Nothing -> return Nothing
1966 Just (new_ic, names, hval) -> do
1968 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1970 case (names,hvals) of
1971 ([n],[hv]) -> return (Just hv)
1972 _ -> panic "compileExpr"
1974 -- -----------------------------------------------------------------------------
1975 -- running a statement interactively
1978 = RunOk [Name] -- ^ names bound by this evaluation
1979 | RunFailed -- ^ statement failed compilation
1980 | RunException Exception -- ^ statement raised an exception
1982 -- | Run a statement in the current interactive context. Statemenet
1983 -- may bind multple values.
1984 runStmt :: Session -> String -> IO RunResult
1985 runStmt (Session ref) expr
1987 hsc_env <- readIORef ref
1989 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1990 -- warnings about the implicit bindings we introduce.
1991 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1992 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1994 maybe_stuff <- hscStmt hsc_env' expr
1997 Nothing -> return RunFailed
1998 Just (new_hsc_env, names, hval) -> do
2000 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2001 either_hvals <- sandboxIO thing_to_run
2003 case either_hvals of
2005 -- on error, keep the *old* interactive context,
2006 -- so that 'it' is not bound to something
2007 -- that doesn't exist.
2008 return (RunException e)
2011 -- Get the newly bound things, and bind them.
2012 -- Don't need to delete any shadowed bindings;
2013 -- the new ones override the old ones.
2014 extendLinkEnv (zip names hvals)
2016 writeIORef ref new_hsc_env
2017 return (RunOk names)
2019 -- When running a computation, we redirect ^C exceptions to the running
2020 -- thread. ToDo: we might want a way to continue even if the target
2021 -- thread doesn't die when it receives the exception... "this thread
2022 -- is not responding".
2023 sandboxIO :: IO a -> IO (Either Exception a)
2024 sandboxIO thing = do
2026 ts <- takeMVar interruptTargetThread
2027 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2028 putMVar interruptTargetThread (child:ts)
2029 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2032 -- This version of sandboxIO runs the expression in a completely new
2033 -- RTS main thread. It is disabled for now because ^C exceptions
2034 -- won't be delivered to the new thread, instead they'll be delivered
2035 -- to the (blocked) GHCi main thread.
2037 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2039 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2040 sandboxIO thing = do
2041 st_thing <- newStablePtr (Exception.try thing)
2042 alloca $ \ p_st_result -> do
2043 stat <- rts_evalStableIO st_thing p_st_result
2044 freeStablePtr st_thing
2046 then do st_result <- peek p_st_result
2047 result <- deRefStablePtr st_result
2048 freeStablePtr st_result
2049 return (Right result)
2051 return (Left (fromIntegral stat))
2053 foreign import "rts_evalStableIO" {- safe -}
2054 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2055 -- more informative than the C type!
2058 -----------------------------------------------------------------------------
2059 -- show a module and it's source/object filenames
2061 showModule :: Session -> ModSummary -> IO String
2062 showModule s mod_summary = withSession s $ \hsc_env -> do
2063 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
2064 Nothing -> panic "missing linkable"
2065 Just mod_info -> return (showModMsg obj_linkable mod_summary)
2067 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))