1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
26 Target(..), TargetId(..), Phase,
33 -- * Loading\/compiling the program
35 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
37 workingDirectoryChanged,
38 checkModule, CheckedModule(..),
39 TypecheckedSource, ParsedSource, RenamedSource,
41 -- * Inspecting the module structure of the program
42 ModuleGraph, ModSummary(..),
47 -- * Inspecting modules
52 modInfoPrintUnqualified,
55 modInfoIsExportedName,
59 -- * Interactive evaluation
60 getBindings, getPrintUnqual,
62 setContext, getContext,
65 getInfo, GetInfoResult,
77 -- * Abstract syntax elements
80 Module, mkModule, pprModule,
87 isImplicitId, isDeadBinder,
88 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
90 isPrimOpId, isFCallId,
91 isDataConWorkId, idDataCon,
92 isBottomingId, isDictonaryId,
94 -- ** Type constructors
96 isClassTyCon, isSynTyCon, isNewTyCon,
98 -- ** Data constructors
103 classSCTheta, classTvsFds,
108 -- ** Types and Kinds
116 module HsSyn, -- ToDo: remove extraneous bits
119 GhcException(..), showGhcException,
129 * inline bits of HscMain here to simplify layering: hscGetInfo,
131 * we need to expose DynFlags, so should parseDynamicFlags really be
132 part of this interface?
133 * what StaticFlags should we expose, if any?
136 #include "HsVersions.h"
139 import qualified Linker
140 import Linker ( HValue, extendLinkEnv )
141 import TcRnDriver ( getModuleContents, tcRnLookupRdrName,
143 import RdrName ( plusGlobalRdrEnv, Provenance(..),
144 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
145 emptyGlobalRdrEnv, mkGlobalRdrEnv )
146 import HscMain ( hscGetInfo, GetInfoResult, hscParseIdentifier,
147 hscStmt, hscTcExpr, hscKcType )
148 import Type ( tidyType )
149 import VarEnv ( emptyTidyEnv )
150 import GHC.Exts ( unsafeCoerce# )
151 import IfaceSyn ( IfaceDecl )
154 import Packages ( initPackages, isHomeModule )
155 import NameSet ( NameSet, nameSetToList, elemNameSet )
156 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName,
159 import Type ( Kind, Type, dropForAlls )
160 import Id ( Id, idType, isImplicitId, isDeadBinder,
161 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
163 isPrimOpId, isFCallId,
164 isDataConWorkId, idDataCon,
166 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon )
167 import Class ( Class, classSCTheta, classTvsFds )
168 import DataCon ( DataCon )
169 import Name ( Name, nameModule )
170 import NameEnv ( nameEnvElts )
171 import InstEnv ( Instance )
173 import DriverPipeline
174 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
175 import GetImports ( getImports )
176 import Packages ( isHomePackage )
178 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
182 import SysTools ( initSysTools, cleanTempFiles )
187 import Bag ( unitBag, emptyBag )
188 import ErrUtils ( showPass, Messages, putMsg, debugTraceMsg,
189 mkPlainErrMsg, pprBagOfErrors )
190 import qualified ErrUtils
192 import StringBuffer ( StringBuffer, hGetStringBuffer )
194 import SysTools ( cleanTempFilesExcept )
195 import BasicTypes ( SuccessFlag(..), succeeded, failed )
196 import TcType ( tcSplitSigmaTy, isDictTy )
197 import FastString ( mkFastString )
199 import Directory ( getModificationTime, doesFileExist )
200 import Maybe ( isJust, isNothing, fromJust )
201 import Maybes ( orElse, expectJust, mapCatMaybes )
202 import List ( partition, nub )
203 import qualified List
204 import Monad ( unless, when )
205 import System ( exitWith, ExitCode(..) )
206 import Time ( ClockTime )
207 import EXCEPTION as Exception hiding (handle)
210 import Prelude hiding (init)
212 -- -----------------------------------------------------------------------------
213 -- Exception handlers
215 -- | Install some default exception handlers and run the inner computation.
216 -- Unless you want to handle exceptions yourself, you should wrap this around
217 -- the top level of your program. The default handlers output the error
218 -- message(s) to stderr and exit cleanly.
219 defaultErrorHandler :: IO a -> IO a
220 defaultErrorHandler inner =
221 -- top-level exception handler: any unrecognised exception is a compiler bug.
222 handle (\exception -> do
225 -- an IO exception probably isn't our fault, so don't panic
226 IOException _ -> putMsg (show exception)
227 AsyncException StackOverflow ->
228 putMsg "stack overflow: use +RTS -K<size> to increase it"
229 _other -> putMsg (show (Panic (show exception)))
230 exitWith (ExitFailure 1)
233 -- program errors: messages with locations attached. Sometimes it is
234 -- convenient to just throw these as exceptions.
235 handleDyn (\dyn -> do printErrs (pprBagOfErrors (unitBag dyn))
236 exitWith (ExitFailure 1)) $
238 -- error messages propagated as exceptions
239 handleDyn (\dyn -> do
242 PhaseFailed _ code -> exitWith code
243 Interrupted -> exitWith (ExitFailure 1)
244 _ -> do putMsg (show (dyn :: GhcException))
245 exitWith (ExitFailure 1)
249 -- | Install a default cleanup handler to remove temporary files
250 -- deposited by a GHC run. This is seperate from
251 -- 'defaultErrorHandler', because you might want to override the error
252 -- handling, but still get the ordinary cleanup behaviour.
253 defaultCleanupHandler :: DynFlags -> IO a -> IO a
254 defaultCleanupHandler dflags inner =
255 -- make sure we clean up after ourselves
256 later (unless (dopt Opt_KeepTmpFiles dflags) $
257 cleanTempFiles dflags)
258 -- exceptions will be blocked while we clean the temporary files,
259 -- so there shouldn't be any difficulty if we receive further
264 -- | Initialises GHC. This must be done /once/ only. Takes the
265 -- command-line arguments. All command-line arguments which aren't
266 -- understood by GHC will be returned.
268 init :: [String] -> IO [String]
271 installSignalHandlers
273 -- Grab the -B option if there is one
274 let (minusB_args, argv1) = partition (prefixMatch "-B") args
275 dflags0 <- initSysTools minusB_args defaultDynFlags
276 writeIORef v_initDynFlags dflags0
278 -- Parse the static flags
279 argv2 <- parseStaticFlags argv1
282 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
283 -- stores the DynFlags between the call to init and subsequent
284 -- calls to newSession.
286 -- | Starts a new session. A session consists of a set of loaded
287 -- modules, a set of options (DynFlags), and an interactive context.
288 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
290 newSession :: GhcMode -> IO Session
292 dflags0 <- readIORef v_initDynFlags
293 dflags <- initDynFlags dflags0
294 env <- newHscEnv dflags{ ghcMode=mode }
298 -- tmp: this breaks the abstraction, but required because DriverMkDepend
299 -- needs to call the Finder. ToDo: untangle this.
300 sessionHscEnv :: Session -> IO HscEnv
301 sessionHscEnv (Session ref) = readIORef ref
303 withSession :: Session -> (HscEnv -> IO a) -> IO a
304 withSession (Session ref) f = do h <- readIORef ref; f h
306 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
307 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
309 -- -----------------------------------------------------------------------------
312 -- | Grabs the DynFlags from the Session
313 getSessionDynFlags :: Session -> IO DynFlags
314 getSessionDynFlags s = withSession s (return . hsc_dflags)
316 -- | Updates the DynFlags in a Session
317 setSessionDynFlags :: Session -> DynFlags -> IO ()
318 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
320 -- | Messages during compilation (eg. warnings and progress messages)
321 -- are reported using this callback. By default, these messages are
322 -- printed to stderr.
323 setMsgHandler :: (String -> IO ()) -> IO ()
324 setMsgHandler = ErrUtils.setMsgHandler
326 -- -----------------------------------------------------------------------------
329 -- ToDo: think about relative vs. absolute file paths. And what
330 -- happens when the current directory changes.
332 -- | Sets the targets for this session. Each target may be a module name
333 -- or a filename. The targets correspond to the set of root modules for
334 -- the program\/library. Unloading the current program is achieved by
335 -- setting the current set of targets to be empty, followed by load.
336 setTargets :: Session -> [Target] -> IO ()
337 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
339 -- | returns the current set of targets
340 getTargets :: Session -> IO [Target]
341 getTargets s = withSession s (return . hsc_targets)
343 -- | Add another target
344 addTarget :: Session -> Target -> IO ()
346 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
349 removeTarget :: Session -> TargetId -> IO ()
350 removeTarget s target_id
351 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
353 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
355 -- Attempts to guess what Target a string refers to. This function implements
356 -- the --make/GHCi command-line syntax for filenames:
358 -- - if the string looks like a Haskell source filename, then interpret
360 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
362 -- - otherwise interpret the string as a module name
364 guessTarget :: String -> Maybe Phase -> IO Target
365 guessTarget file (Just phase)
366 = return (Target (TargetFile file (Just phase)) Nothing)
367 guessTarget file Nothing
368 | isHaskellSrcFilename file
369 = return (Target (TargetFile file Nothing) Nothing)
371 = do exists <- doesFileExist hs_file
373 then return (Target (TargetFile hs_file Nothing) Nothing)
375 exists <- doesFileExist lhs_file
377 then return (Target (TargetFile lhs_file Nothing) Nothing)
379 return (Target (TargetModule (mkModule file)) Nothing)
381 hs_file = file `joinFileExt` "hs"
382 lhs_file = file `joinFileExt` "lhs"
384 -- -----------------------------------------------------------------------------
385 -- Loading the program
387 -- Perform a dependency analysis starting from the current targets
388 -- and update the session with the new module graph.
389 depanal :: Session -> [Module] -> IO (Either Messages ModuleGraph)
390 depanal (Session ref) excluded_mods = do
391 hsc_env <- readIORef ref
393 dflags = hsc_dflags hsc_env
394 gmode = ghcMode (hsc_dflags hsc_env)
395 targets = hsc_targets hsc_env
396 old_graph = hsc_mod_graph hsc_env
398 showPass dflags "Chasing dependencies"
399 when (gmode == BatchCompile) $
400 debugTraceMsg dflags 1 (showSDoc (hcat [
401 text "Chasing modules from: ",
402 hcat (punctuate comma (map pprTarget targets))]))
404 downsweep hsc_env old_graph excluded_mods
407 -- | The result of load.
409 = LoadOk Errors -- ^ all specified targets were loaded successfully.
410 | LoadFailed Errors -- ^ not all modules were loaded.
412 type Errors = [String]
414 data ErrMsg = ErrMsg {
415 errMsgSeverity :: Severity, -- warning, error, etc.
416 errMsgSpans :: [SrcSpan],
417 errMsgShortDoc :: Doc,
418 errMsgExtraInfo :: Doc
425 | LoadDependenciesOf Module
427 -- | Try to load the program. If a Module is supplied, then just
428 -- attempt to load up to this target. If no Module is supplied,
429 -- then try to load all targets.
430 load :: Session -> LoadHowMuch -> IO SuccessFlag
431 load session how_much =
432 loadMsgs session how_much ErrUtils.printErrorsAndWarnings
434 -- | Version of 'load' that takes a callback function to be invoked
435 -- on compiler errors and warnings as they occur during compilation.
436 loadMsgs :: Session -> LoadHowMuch -> (Messages-> IO ()) -> IO SuccessFlag
437 loadMsgs s@(Session ref) how_much msg_act
439 -- Dependency analysis first. Note that this fixes the module graph:
440 -- even if we don't get a fully successful upsweep, the full module
441 -- graph is still retained in the Session. We can tell which modules
442 -- were successfully loaded by inspecting the Session's HPT.
443 mb_graph <- depanal s []
445 Left msgs -> do msg_act msgs; return Failed
446 Right mod_graph -> do
447 hsc_env <- readIORef ref
448 writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
449 loadMsgs2 s how_much msg_act mod_graph
451 loadMsgs2 s@(Session ref) how_much msg_act mod_graph = do
452 hsc_env <- readIORef ref
454 let hpt1 = hsc_HPT hsc_env
455 let dflags = hsc_dflags hsc_env
456 let ghci_mode = ghcMode dflags -- this never changes
457 let verb = verbosity dflags
459 -- The "bad" boot modules are the ones for which we have
460 -- B.hs-boot in the module graph, but no B.hs
461 -- The downsweep should have ensured this does not happen
463 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
464 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
465 not (ms_mod s `elem` all_home_mods)]
466 ASSERT( null bad_boot_mods ) return ()
468 -- mg2_with_srcimps drops the hi-boot nodes, returning a
469 -- graph with cycles. Among other things, it is used for
470 -- backing out partially complete cycles following a failed
471 -- upsweep, and for removing from hpt all the modules
472 -- not in strict downwards closure, during calls to compile.
473 let mg2_with_srcimps :: [SCC ModSummary]
474 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
476 -- check the stability property for each module.
477 stable_mods@(stable_obj,stable_bco)
478 | BatchCompile <- ghci_mode = ([],[])
479 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
481 -- prune bits of the HPT which are definitely redundant now,
483 pruned_hpt = pruneHomePackageTable hpt1
484 (flattenSCCs mg2_with_srcimps)
489 debugTraceMsg dflags 2 (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
490 text "Stable BCO:" <+> ppr stable_bco))
492 -- Unload any modules which are going to be re-linked this time around.
493 let stable_linkables = [ linkable
494 | m <- stable_obj++stable_bco,
495 Just hmi <- [lookupModuleEnv pruned_hpt m],
496 Just linkable <- [hm_linkable hmi] ]
497 unload hsc_env stable_linkables
499 -- We could at this point detect cycles which aren't broken by
500 -- a source-import, and complain immediately, but it seems better
501 -- to let upsweep_mods do this, so at least some useful work gets
502 -- done before the upsweep is abandoned.
503 --hPutStrLn stderr "after tsort:\n"
504 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
506 -- Now do the upsweep, calling compile for each module in
507 -- turn. Final result is version 3 of everything.
509 -- Topologically sort the module graph, this time including hi-boot
510 -- nodes, and possibly just including the portion of the graph
511 -- reachable from the module specified in the 2nd argument to load.
512 -- This graph should be cycle-free.
513 -- If we're restricting the upsweep to a portion of the graph, we
514 -- also want to retain everything that is still stable.
515 let full_mg :: [SCC ModSummary]
516 full_mg = topSortModuleGraph False mod_graph Nothing
518 maybe_top_mod = case how_much of
520 LoadDependenciesOf m -> Just m
523 partial_mg0 :: [SCC ModSummary]
524 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
526 -- LoadDependenciesOf m: we want the upsweep to stop just
527 -- short of the specified module (unless the specified module
530 | LoadDependenciesOf mod <- how_much
531 = ASSERT( case last partial_mg0 of
532 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
533 List.init partial_mg0
539 | AcyclicSCC ms <- full_mg,
540 ms_mod ms `elem` stable_obj++stable_bco,
541 ms_mod ms `notElem` [ ms_mod ms' |
542 AcyclicSCC ms' <- partial_mg ] ]
544 mg = stable_mg ++ partial_mg
546 -- clean up between compilations
547 let cleanup = cleanTempFilesExcept dflags
548 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
550 (upsweep_ok, hsc_env1, modsUpswept)
551 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
552 pruned_hpt stable_mods cleanup msg_act mg
554 -- Make modsDone be the summaries for each home module now
555 -- available; this should equal the domain of hpt3.
556 -- Get in in a roughly top .. bottom order (hence reverse).
558 let modsDone = reverse modsUpswept
560 -- Try and do linking in some form, depending on whether the
561 -- upsweep was completely or only partially successful.
563 if succeeded upsweep_ok
566 -- Easy; just relink it all.
567 do debugTraceMsg dflags 2 "Upsweep completely successful."
569 -- Clean up after ourselves
570 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
572 -- Issue a warning for the confusing case where the user
573 -- said '-o foo' but we're not going to do any linking.
574 -- We attempt linking if either (a) one of the modules is
575 -- called Main, or (b) the user said -no-hs-main, indicating
576 -- that main() is going to come from somewhere else.
578 let ofile = outputFile dflags
579 let no_hs_main = dopt Opt_NoHsMain dflags
580 let mb_main_mod = mainModIs dflags
582 main_mod = mb_main_mod `orElse` "Main"
584 = any ((==main_mod).moduleUserString.ms_mod)
586 do_linking = a_root_is_Main || no_hs_main
588 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
589 debugTraceMsg dflags 1 ("Warning: output was redirected with -o, " ++
590 "but no output will be generated\n" ++
591 "because there is no " ++ main_mod ++ " module.")
593 -- link everything together
594 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
596 loadFinish Succeeded linkresult ref hsc_env1
599 -- Tricky. We need to back out the effects of compiling any
600 -- half-done cycles, both so as to clean up the top level envs
601 -- and to avoid telling the interactive linker to link them.
602 do debugTraceMsg dflags 2 "Upsweep partially successful."
605 = map ms_mod modsDone
606 let mods_to_zap_names
607 = findPartiallyCompletedCycles modsDone_names
610 = filter ((`notElem` mods_to_zap_names).ms_mod)
613 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
616 -- Clean up after ourselves
617 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
619 -- there should be no Nothings where linkables should be, now
620 ASSERT(all (isJust.hm_linkable)
621 (moduleEnvElts (hsc_HPT hsc_env))) do
623 -- Link everything together
624 linkresult <- link ghci_mode dflags False hpt4
626 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
627 loadFinish Failed linkresult ref hsc_env4
629 -- Finish up after a load.
631 -- If the link failed, unload everything and return.
632 loadFinish all_ok Failed ref hsc_env
633 = do unload hsc_env []
634 writeIORef ref $! discardProg hsc_env
637 -- Empty the interactive context and set the module context to the topmost
638 -- newly loaded module, or the Prelude if none were loaded.
639 loadFinish all_ok Succeeded ref hsc_env
640 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
644 -- Forget the current program, but retain the persistent info in HscEnv
645 discardProg :: HscEnv -> HscEnv
647 = hsc_env { hsc_mod_graph = emptyMG,
648 hsc_IC = emptyInteractiveContext,
649 hsc_HPT = emptyHomePackageTable }
651 -- used to fish out the preprocess output files for the purposes of
652 -- cleaning up. The preprocessed file *might* be the same as the
653 -- source file, but that doesn't do any harm.
654 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
656 -- -----------------------------------------------------------------------------
660 CheckedModule { parsedSource :: ParsedSource,
661 renamedSource :: Maybe RenamedSource,
662 typecheckedSource :: Maybe TypecheckedSource,
663 checkedModuleInfo :: Maybe ModuleInfo
665 -- ToDo: improvements that could be made here:
666 -- if the module succeeded renaming but not typechecking,
667 -- we can still get back the GlobalRdrEnv and exports, so
668 -- perhaps the ModuleInfo should be split up into separate
669 -- fields within CheckedModule.
671 type ParsedSource = Located (HsModule RdrName)
672 type RenamedSource = HsGroup Name
673 type TypecheckedSource = LHsBinds Id
675 -- | This is the way to get access to parsed and typechecked source code
676 -- for a module. 'checkModule' loads all the dependencies of the specified
677 -- module in the Session, and then attempts to typecheck the module. If
678 -- successful, it returns the abstract syntax for the module.
679 checkModule :: Session -> Module -> (Messages -> IO ())
680 -> IO (Maybe CheckedModule)
681 checkModule session@(Session ref) mod msg_act = do
682 -- load up the dependencies first
683 r <- loadMsgs session (LoadDependenciesOf mod) msg_act
684 if (failed r) then return Nothing else do
686 -- now parse & typecheck the module
687 hsc_env <- readIORef ref
688 let mg = hsc_mod_graph hsc_env
689 case [ ms | ms <- mg, ms_mod ms == mod ] of
692 -- Add in the OPTIONS from the source file This is nasty:
693 -- we've done this once already, in the compilation manager
694 -- It might be better to cache the flags in the
695 -- ml_hspp_file field, say
696 let dflags0 = hsc_dflags hsc_env
697 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
698 opts = getOptionsFromStringBuffer hspp_buf
699 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
700 if (not (null leftovers))
701 then do let filename = fromJust (ml_hs_file (ms_location ms))
702 msg_act (optionsErrorMsgs leftovers opts filename)
706 r <- hscFileCheck hsc_env{hsc_dflags=dflags1} msg_act ms
710 HscChecked parsed renamed Nothing ->
711 return (Just (CheckedModule {
712 parsedSource = parsed,
713 renamedSource = renamed,
714 typecheckedSource = Nothing,
715 checkedModuleInfo = Nothing }))
716 HscChecked parsed renamed
717 (Just (tc_binds, rdr_env, details)) -> do
718 let minf = ModuleInfo {
719 minf_type_env = md_types details,
720 minf_exports = md_exports details,
721 minf_rdr_env = Just rdr_env,
722 minf_instances = md_insts details
724 return (Just (CheckedModule {
725 parsedSource = parsed,
726 renamedSource = renamed,
727 typecheckedSource = Just tc_binds,
728 checkedModuleInfo = Just minf }))
730 -- ---------------------------------------------------------------------------
733 unload :: HscEnv -> [Linkable] -> IO ()
734 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
735 = case ghcMode (hsc_dflags hsc_env) of
736 BatchCompile -> return ()
737 JustTypecheck -> return ()
739 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
741 Interactive -> panic "unload: no interpreter"
743 other -> panic "unload: strange mode"
745 -- -----------------------------------------------------------------------------
749 Stability tells us which modules definitely do not need to be recompiled.
750 There are two main reasons for having stability:
752 - avoid doing a complete upsweep of the module graph in GHCi when
753 modules near the bottom of the tree have not changed.
755 - to tell GHCi when it can load object code: we can only load object code
756 for a module when we also load object code fo all of the imports of the
757 module. So we need to know that we will definitely not be recompiling
758 any of these modules, and we can use the object code.
760 NB. stability is of no importance to BatchCompile at all, only Interactive.
761 (ToDo: what about JustTypecheck?)
763 The stability check is as follows. Both stableObject and
764 stableBCO are used during the upsweep phase later.
767 stable m = stableObject m || stableBCO m
770 all stableObject (imports m)
771 && old linkable does not exist, or is == on-disk .o
772 && date(on-disk .o) > date(.hs)
775 all stable (imports m)
776 && date(BCO) > date(.hs)
779 These properties embody the following ideas:
781 - if a module is stable:
782 - if it has been compiled in a previous pass (present in HPT)
783 then it does not need to be compiled or re-linked.
784 - if it has not been compiled in a previous pass,
785 then we only need to read its .hi file from disk and
786 link it to produce a ModDetails.
788 - if a modules is not stable, we will definitely be at least
789 re-linking, and possibly re-compiling it during the upsweep.
790 All non-stable modules can (and should) therefore be unlinked
793 - Note that objects are only considered stable if they only depend
794 on other objects. We can't link object code against byte code.
798 :: HomePackageTable -- HPT from last compilation
799 -> [SCC ModSummary] -- current module graph (cyclic)
800 -> [Module] -- all home modules
801 -> ([Module], -- stableObject
802 [Module]) -- stableBCO
804 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
806 checkSCC (stable_obj, stable_bco) scc0
807 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
808 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
809 | otherwise = (stable_obj, stable_bco)
811 scc = flattenSCC scc0
812 scc_mods = map ms_mod scc
813 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
815 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
816 -- all imports outside the current SCC, but in the home pkg
818 stable_obj_imps = map (`elem` stable_obj) scc_allimps
819 stable_bco_imps = map (`elem` stable_bco) scc_allimps
826 and (zipWith (||) stable_obj_imps stable_bco_imps)
830 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
834 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
836 Just hmi | Just l <- hm_linkable hmi
837 -> isObjectLinkable l && t == linkableTime l
838 -- why '>=' rather than '>' above? If the filesystem stores
839 -- times to the nearset second, we may occasionally find that
840 -- the object & source have the same modification time,
841 -- especially if the source was automatically generated
842 -- and compiled. Using >= is slightly unsafe, but it matches
846 = case lookupModuleEnv hpt (ms_mod ms) of
848 Just hmi | Just l <- hm_linkable hmi ->
849 not (isObjectLinkable l) &&
850 linkableTime l >= ms_hs_date ms
852 ms_allimps :: ModSummary -> [Module]
853 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
855 -- -----------------------------------------------------------------------------
856 -- Prune the HomePackageTable
858 -- Before doing an upsweep, we can throw away:
860 -- - For non-stable modules:
861 -- - all ModDetails, all linked code
862 -- - all unlinked code that is out of date with respect to
865 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
866 -- space at the end of the upsweep, because the topmost ModDetails of the
867 -- old HPT holds on to the entire type environment from the previous
870 pruneHomePackageTable
873 -> ([Module],[Module])
876 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
877 = mapModuleEnv prune hpt
879 | is_stable modl = hmi'
880 | otherwise = hmi'{ hm_details = emptyModDetails }
882 modl = mi_module (hm_iface hmi)
883 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
884 = hmi{ hm_linkable = Nothing }
887 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
889 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
891 is_stable m = m `elem` stable_obj || m `elem` stable_bco
893 -- -----------------------------------------------------------------------------
895 -- Return (names of) all those in modsDone who are part of a cycle
896 -- as defined by theGraph.
897 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
898 findPartiallyCompletedCycles modsDone theGraph
902 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
903 chew ((CyclicSCC vs):rest)
904 = let names_in_this_cycle = nub (map ms_mod vs)
906 = nub ([done | done <- modsDone,
907 done `elem` names_in_this_cycle])
908 chewed_rest = chew rest
910 if notNull mods_in_this_cycle
911 && length mods_in_this_cycle < length names_in_this_cycle
912 then mods_in_this_cycle ++ chewed_rest
915 -- -----------------------------------------------------------------------------
918 -- This is where we compile each module in the module graph, in a pass
919 -- from the bottom to the top of the graph.
921 -- There better had not be any cyclic groups here -- we check for them.
924 :: HscEnv -- Includes initially-empty HPT
925 -> HomePackageTable -- HPT from last time round (pruned)
926 -> ([Module],[Module]) -- stable modules (see checkStability)
927 -> IO () -- How to clean up unwanted tmp files
928 -> (Messages -> IO ()) -- Compiler error message callback
929 -> [SCC ModSummary] -- Mods to do (the worklist)
931 HscEnv, -- With an updated HPT
932 [ModSummary]) -- Mods which succeeded
934 upsweep hsc_env old_hpt stable_mods cleanup msg_act mods
935 = upsweep' hsc_env old_hpt stable_mods cleanup msg_act mods 1 (length mods)
937 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
939 = return (Succeeded, hsc_env, [])
941 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
943 = do putMsg (showSDoc (cyclicModuleErr ms))
944 return (Failed, hsc_env, [])
946 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
947 (AcyclicSCC mod:mods) mod_index nmods
948 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
949 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
950 -- (moduleEnvElts (hsc_HPT hsc_env)))
952 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods msg_act mod
955 cleanup -- Remove unwanted tmp files between compilations
958 Nothing -> return (Failed, hsc_env, [])
960 { let this_mod = ms_mod mod
962 -- Add new info to hsc_env
963 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
965 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
967 -- Space-saving: delete the old HPT entry
968 -- for mod BUT if mod is a hs-boot
969 -- node, don't delete it. For the
970 -- interface, the HPT entry is probaby for the
971 -- main Haskell source file. Deleting it
972 -- would force .. (what?? --SDM)
973 old_hpt1 | isBootSummary mod = old_hpt
974 | otherwise = delModuleEnv old_hpt this_mod
976 ; (restOK, hsc_env2, modOKs)
977 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
978 msg_act mods (mod_index+1) nmods
979 ; return (restOK, hsc_env2, mod:modOKs)
983 -- Compile a single module. Always produce a Linkable for it if
984 -- successful. If no compilation happened, return the old Linkable.
985 upsweep_mod :: HscEnv
987 -> ([Module],[Module])
988 -> (Messages -> IO ())
990 -> Int -- index of module
991 -> Int -- total number of modules
992 -> IO (Maybe HomeModInfo) -- Nothing => Failed
994 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) msg_act summary mod_index nmods
997 this_mod = ms_mod summary
998 mb_obj_date = ms_obj_date summary
999 obj_fn = ml_obj_file (ms_location summary)
1000 hs_date = ms_hs_date summary
1002 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1003 compile_it = upsweep_compile hsc_env old_hpt this_mod
1004 msg_act summary mod_index nmods
1006 case ghcMode (hsc_dflags hsc_env) of
1009 -- Batch-compilating is easy: just check whether we have
1010 -- an up-to-date object file. If we do, then the compiler
1011 -- needs to do a recompilation check.
1012 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1014 findObjectLinkable this_mod obj_fn obj_date
1015 compile_it (Just linkable)
1022 _ | is_stable_obj, isJust old_hmi ->
1024 -- object is stable, and we have an entry in the
1025 -- old HPT: nothing to do
1027 | is_stable_obj, isNothing old_hmi -> do
1029 findObjectLinkable this_mod obj_fn
1030 (expectJust "upseep1" mb_obj_date)
1031 compile_it (Just linkable)
1032 -- object is stable, but we need to load the interface
1033 -- off disk to make a HMI.
1036 ASSERT(isJust old_hmi) -- must be in the old_hpt
1038 -- BCO is stable: nothing to do
1040 | Just hmi <- old_hmi,
1041 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1042 linkableTime l >= ms_hs_date summary ->
1044 -- we have an old BCO that is up to date with respect
1045 -- to the source: do a recompilation check as normal.
1049 -- no existing code at all: we must recompile.
1051 is_stable_obj = this_mod `elem` stable_obj
1052 is_stable_bco = this_mod `elem` stable_bco
1054 old_hmi = lookupModuleEnv old_hpt this_mod
1056 -- Run hsc to compile a module
1057 upsweep_compile hsc_env old_hpt this_mod msg_act summary
1059 mb_old_linkable = do
1061 -- The old interface is ok if it's in the old HPT
1062 -- a) we're compiling a source file, and the old HPT
1063 -- entry is for a source file
1064 -- b) we're compiling a hs-boot file
1065 -- Case (b) allows an hs-boot file to get the interface of its
1066 -- real source file on the second iteration of the compilation
1067 -- manager, but that does no harm. Otherwise the hs-boot file
1068 -- will always be recompiled
1071 = case lookupModuleEnv old_hpt this_mod of
1073 Just hm_info | isBootSummary summary -> Just iface
1074 | not (mi_boot iface) -> Just iface
1075 | otherwise -> Nothing
1077 iface = hm_iface hm_info
1079 compresult <- compile hsc_env msg_act summary mb_old_linkable mb_old_iface
1083 -- Compilation failed. Compile may still have updated the PCS, tho.
1084 CompErrs -> return Nothing
1086 -- Compilation "succeeded", and may or may not have returned a new
1087 -- linkable (depending on whether compilation was actually performed
1089 CompOK new_details new_iface new_linkable
1090 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1091 hm_details = new_details,
1092 hm_linkable = new_linkable }
1093 return (Just new_info)
1096 -- Filter modules in the HPT
1097 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1098 retainInTopLevelEnvs keep_these hpt
1099 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1101 , let mb_mod_info = lookupModuleEnv hpt mod
1102 , isJust mb_mod_info ]
1104 -- ---------------------------------------------------------------------------
1105 -- Topological sort of the module graph
1108 :: Bool -- Drop hi-boot nodes? (see below)
1112 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1113 -- The resulting list of strongly-connected-components is in topologically
1114 -- sorted order, starting with the module(s) at the bottom of the
1115 -- dependency graph (ie compile them first) and ending with the ones at
1118 -- Drop hi-boot nodes (first boolean arg)?
1120 -- False: treat the hi-boot summaries as nodes of the graph,
1121 -- so the graph must be acyclic
1123 -- True: eliminate the hi-boot nodes, and instead pretend
1124 -- the a source-import of Foo is an import of Foo
1125 -- The resulting graph has no hi-boot nodes, but can by cyclic
1127 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1128 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1129 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1130 = stronglyConnComp (map vertex_fn (reachable graph root))
1132 -- restrict the graph to just those modules reachable from
1133 -- the specified module. We do this by building a graph with
1134 -- the full set of nodes, and determining the reachable set from
1135 -- the specified node.
1136 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1137 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1139 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1140 | otherwise = throwDyn (ProgramError "module does not exist")
1142 moduleGraphNodes :: Bool -> [ModSummary]
1143 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1144 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1146 -- Drop hs-boot nodes by using HsSrcFile as the key
1147 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1148 | otherwise = HsBootFile
1150 -- We use integers as the keys for the SCC algorithm
1151 nodes :: [(ModSummary, Int, [Int])]
1152 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1153 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1154 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) )
1156 , not (isBootSummary s && drop_hs_boot_nodes) ]
1157 -- Drop the hi-boot ones if told to do so
1159 key_map :: NodeMap Int
1160 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1163 lookup_key :: HscSource -> Module -> Maybe Int
1164 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1166 out_edge_keys :: HscSource -> [Module] -> [Int]
1167 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1168 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1169 -- the IsBootInterface parameter True; else False
1172 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1173 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1175 msKey :: ModSummary -> NodeKey
1176 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1178 emptyNodeMap :: NodeMap a
1179 emptyNodeMap = emptyFM
1181 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1182 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1184 nodeMapElts :: NodeMap a -> [a]
1185 nodeMapElts = eltsFM
1187 -- -----------------------------------------------------------------
1188 -- The unlinked image
1190 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1191 -- binaries (byte code or object code). Even when it links bytecode
1192 -- it keeps the unlinked version so it can re-link it later without
1195 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1197 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1198 findModuleLinkable_maybe lis mod
1199 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1202 many -> pprPanic "findModuleLinkable" (ppr mod)
1204 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1205 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1207 -----------------------------------------------------------------------------
1208 -- Downsweep (dependency analysis)
1210 -- Chase downwards from the specified root set, returning summaries
1211 -- for all home modules encountered. Only follow source-import
1214 -- We pass in the previous collection of summaries, which is used as a
1215 -- cache to avoid recalculating a module summary if the source is
1218 -- The returned list of [ModSummary] nodes has one node for each home-package
1219 -- module, plus one for any hs-boot files. The imports of these nodes
1220 -- are all there, including the imports of non-home-package modules.
1223 -> [ModSummary] -- Old summaries
1224 -> [Module] -- Ignore dependencies on these; treat them as
1225 -- if they were package modules
1226 -> IO (Either Messages [ModSummary])
1227 downsweep hsc_env old_summaries excl_mods
1228 = -- catch error messages and return them
1229 handleDyn (\err_msg -> return (Left (emptyBag, unitBag err_msg))) $ do
1230 rootSummaries <- mapM getRootSummary roots
1231 checkDuplicates rootSummaries
1232 summs <- loop (concatMap msDeps rootSummaries) (mkNodeMap rootSummaries)
1233 return (Right summs)
1235 roots = hsc_targets hsc_env
1237 old_summary_map :: NodeMap ModSummary
1238 old_summary_map = mkNodeMap old_summaries
1240 getRootSummary :: Target -> IO ModSummary
1241 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1242 = do exists <- doesFileExist file
1244 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1245 else throwDyn $ mkPlainErrMsg noSrcSpan $
1246 text "can't find file:" <+> text file
1247 getRootSummary (Target (TargetModule modl) maybe_buf)
1248 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1249 (L rootLoc modl) maybe_buf excl_mods
1250 case maybe_summary of
1251 Nothing -> packageModErr modl
1254 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1256 -- In a root module, the filename is allowed to diverge from the module
1257 -- name, so we have to check that there aren't multiple root files
1258 -- defining the same module (otherwise the duplicates will be silently
1259 -- ignored, leading to confusing behaviour).
1260 checkDuplicates :: [ModSummary] -> IO ()
1261 checkDuplicates summaries = mapM_ check summaries
1266 many -> multiRootsErr modl many
1267 where modl = ms_mod summ
1269 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1270 | summ' <- summaries, ms_mod summ' == modl ]
1272 loop :: [(Located Module,IsBootInterface)]
1273 -- Work list: process these modules
1274 -> NodeMap ModSummary
1277 -- The result includes the worklist, except
1278 -- for those mentioned in the visited set
1279 loop [] done = return (nodeMapElts done)
1280 loop ((wanted_mod, is_boot) : ss) done
1281 | key `elemFM` done = loop ss done
1282 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1283 is_boot wanted_mod Nothing excl_mods
1285 Nothing -> loop ss done
1286 Just s -> loop (msDeps s ++ ss)
1287 (addToFM done key s) }
1289 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1291 msDeps :: ModSummary -> [(Located Module, IsBootInterface)]
1292 -- (msDeps s) returns the dependencies of the ModSummary s.
1293 -- A wrinkle is that for a {-# SOURCE #-} import we return
1294 -- *both* the hs-boot file
1295 -- *and* the source file
1296 -- as "dependencies". That ensures that the list of all relevant
1297 -- modules always contains B.hs if it contains B.hs-boot.
1298 -- Remember, this pass isn't doing the topological sort. It's
1299 -- just gathering the list of all relevant ModSummaries
1301 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1302 ++ [ (m,False) | m <- ms_imps s ]
1304 -----------------------------------------------------------------------------
1305 -- Summarising modules
1307 -- We have two types of summarisation:
1309 -- * Summarise a file. This is used for the root module(s) passed to
1310 -- cmLoadModules. The file is read, and used to determine the root
1311 -- module name. The module name may differ from the filename.
1313 -- * Summarise a module. We are given a module name, and must provide
1314 -- a summary. The finder is used to locate the file in which the module
1319 -> [ModSummary] -- old summaries
1320 -> FilePath -- source file name
1321 -> Maybe Phase -- start phase
1322 -> Maybe (StringBuffer,ClockTime)
1325 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1326 -- we can use a cached summary if one is available and the
1327 -- source file hasn't changed, But we have to look up the summary
1328 -- by source file, rather than module name as we do in summarise.
1329 | Just old_summary <- findSummaryBySourceFile old_summaries file
1331 let location = ms_location old_summary
1333 -- return the cached summary if the source didn't change
1334 src_timestamp <- case maybe_buf of
1335 Just (_,t) -> return t
1336 Nothing -> getModificationTime file
1338 if ms_hs_date old_summary == src_timestamp
1339 then do -- update the object-file timestamp
1340 obj_timestamp <- getObjTimestamp location False
1341 return old_summary{ ms_obj_date = obj_timestamp }
1349 let dflags = hsc_dflags hsc_env
1351 (dflags', hspp_fn, buf)
1352 <- preprocessFile dflags file mb_phase maybe_buf
1354 (srcimps,the_imps, L _ mod) <- getImports dflags' buf hspp_fn
1356 -- Make a ModLocation for this file
1357 location <- mkHomeModLocation dflags mod file
1359 -- Tell the Finder cache where it is, so that subsequent calls
1360 -- to findModule will find it, even if it's not on any search path
1361 addHomeModuleToFinder hsc_env mod location
1363 src_timestamp <- case maybe_buf of
1364 Just (_,t) -> return t
1365 Nothing -> getModificationTime file
1367 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1369 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1370 ms_location = location,
1371 ms_hspp_file = Just hspp_fn,
1372 ms_hspp_buf = Just buf,
1373 ms_srcimps = srcimps, ms_imps = the_imps,
1374 ms_hs_date = src_timestamp,
1375 ms_obj_date = obj_timestamp })
1377 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1378 findSummaryBySourceFile summaries file
1379 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1380 fromJust (ml_hs_file (ms_location ms)) == file ] of
1384 -- Summarise a module, and pick up source and timestamp.
1387 -> NodeMap ModSummary -- Map of old summaries
1388 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1389 -> Located Module -- Imported module to be summarised
1390 -> Maybe (StringBuffer, ClockTime)
1391 -> [Module] -- Modules to exclude
1392 -> IO (Maybe ModSummary) -- Its new summary
1394 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1395 | wanted_mod `elem` excl_mods
1398 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1399 = do -- Find its new timestamp; all the
1400 -- ModSummaries in the old map have valid ml_hs_files
1401 let location = ms_location old_summary
1402 src_fn = expectJust "summariseModule" (ml_hs_file location)
1404 -- return the cached summary if the source didn't change
1405 src_timestamp <- case maybe_buf of
1406 Just (_,t) -> return t
1407 Nothing -> getModificationTime src_fn
1409 if ms_hs_date old_summary == src_timestamp
1410 then do -- update the object-file timestamp
1411 obj_timestamp <- getObjTimestamp location is_boot
1412 return (Just old_summary{ ms_obj_date = obj_timestamp })
1414 -- source changed: re-summarise
1415 new_summary location src_fn maybe_buf src_timestamp
1418 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1421 | not (isHomePackage pkg) -> return Nothing
1422 -- Drop external-pkg
1423 | isJust (ml_hs_file location) -> just_found location
1425 err -> noModError dflags loc wanted_mod err
1428 dflags = hsc_dflags hsc_env
1430 hsc_src = if is_boot then HsBootFile else HsSrcFile
1432 just_found location = do
1433 -- Adjust location to point to the hs-boot source file,
1434 -- hi file, object file, when is_boot says so
1435 let location' | is_boot = addBootSuffixLocn location
1436 | otherwise = location
1437 src_fn = expectJust "summarise2" (ml_hs_file location')
1439 -- Check that it exists
1440 -- It might have been deleted since the Finder last found it
1441 maybe_t <- modificationTimeIfExists src_fn
1443 Nothing -> noHsFileErr loc src_fn
1444 Just t -> new_summary location' src_fn Nothing t
1447 new_summary location src_fn maybe_bug src_timestamp
1449 -- Preprocess the source file and get its imports
1450 -- The dflags' contains the OPTIONS pragmas
1451 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1452 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1454 when (mod_name /= wanted_mod) $
1455 throwDyn $ mkPlainErrMsg mod_loc $
1456 text "file name does not match module name"
1457 <+> quotes (ppr mod_name)
1459 -- Find the object timestamp, and return the summary
1460 obj_timestamp <- getObjTimestamp location is_boot
1462 return (Just ( ModSummary { ms_mod = wanted_mod,
1463 ms_hsc_src = hsc_src,
1464 ms_location = location,
1465 ms_hspp_file = Just hspp_fn,
1466 ms_hspp_buf = Just buf,
1467 ms_srcimps = srcimps,
1469 ms_hs_date = src_timestamp,
1470 ms_obj_date = obj_timestamp }))
1473 getObjTimestamp location is_boot
1474 = if is_boot then return Nothing
1475 else modificationTimeIfExists (ml_obj_file location)
1478 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1479 -> IO (DynFlags, FilePath, StringBuffer)
1480 preprocessFile dflags src_fn mb_phase Nothing
1482 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1483 buf <- hGetStringBuffer hspp_fn
1484 return (dflags', hspp_fn, buf)
1486 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1488 -- case we bypass the preprocessing stage?
1490 local_opts = getOptionsFromStringBuffer buf
1492 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1496 | Just (Unlit _) <- mb_phase = True
1497 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1498 -- note: local_opts is only required if there's no Unlit phase
1499 | dopt Opt_Cpp dflags' = True
1500 | dopt Opt_Pp dflags' = True
1503 when needs_preprocessing $
1504 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1506 return (dflags', src_fn, buf)
1509 -----------------------------------------------------------------------------
1511 -----------------------------------------------------------------------------
1513 noModError :: DynFlags -> SrcSpan -> Module -> FindResult -> IO ab
1514 -- ToDo: we don't have a proper line number for this error
1515 noModError dflags loc wanted_mod err
1516 = throwDyn $ mkPlainErrMsg loc $ cantFindError dflags wanted_mod err
1518 noHsFileErr loc path
1519 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1522 = throwDyn $ mkPlainErrMsg noSrcSpan $
1523 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1525 multiRootsErr mod files
1526 = throwDyn $ mkPlainErrMsg noSrcSpan $
1527 text "module" <+> quotes (ppr mod) <+>
1528 text "is defined in multiple files:" <+>
1529 sep (map text files)
1531 cyclicModuleErr :: [ModSummary] -> SDoc
1533 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1534 2 (vcat (map show_one ms))
1536 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1537 nest 2 $ ptext SLIT("imports:") <+>
1538 (pp_imps HsBootFile (ms_srcimps ms)
1539 $$ pp_imps HsSrcFile (ms_imps ms))]
1540 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1541 pp_imps src mods = fsep (map (show_mod src) mods)
1544 -- | Inform GHC that the working directory has changed. GHC will flush
1545 -- its cache of module locations, since it may no longer be valid.
1546 -- Note: if you change the working directory, you should also unload
1547 -- the current program (set targets to empty, followed by load).
1548 workingDirectoryChanged :: Session -> IO ()
1549 workingDirectoryChanged s = withSession s $ \hsc_env ->
1550 flushFinderCache (hsc_FC hsc_env)
1552 -- -----------------------------------------------------------------------------
1553 -- inspecting the session
1555 -- | Get the module dependency graph.
1556 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1557 getModuleGraph s = withSession s (return . hsc_mod_graph)
1559 isLoaded :: Session -> Module -> IO Bool
1560 isLoaded s m = withSession s $ \hsc_env ->
1561 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1563 getBindings :: Session -> IO [TyThing]
1564 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1566 getPrintUnqual :: Session -> IO PrintUnqualified
1567 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1569 -- | Container for information about a 'Module'.
1570 data ModuleInfo = ModuleInfo {
1571 minf_type_env :: TypeEnv,
1572 minf_exports :: NameSet,
1573 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1574 minf_instances :: [Instance]
1575 -- ToDo: this should really contain the ModIface too
1577 -- We don't want HomeModInfo here, because a ModuleInfo applies
1578 -- to package modules too.
1580 -- | Request information about a loaded 'Module'
1581 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1582 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1583 let mg = hsc_mod_graph hsc_env
1584 if mdl `elem` map ms_mod mg
1585 then getHomeModuleInfo hsc_env mdl
1587 if isHomeModule (hsc_dflags hsc_env) mdl
1589 else getPackageModuleInfo hsc_env mdl
1590 -- getPackageModuleInfo will attempt to find the interface, so
1591 -- we don't want to call it for a home module, just in case there
1592 -- was a problem loading the module and the interface doesn't
1593 -- exist... hence the isHomeModule test here.
1595 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1596 getPackageModuleInfo hsc_env mdl = do
1598 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1600 Nothing -> return Nothing
1602 eps <- readIORef (hsc_EPS hsc_env)
1605 n_list = nameSetToList names
1606 tys = [ ty | name <- n_list,
1607 Just ty <- [lookupTypeEnv pte name] ]
1609 return (Just (ModuleInfo {
1610 minf_type_env = mkTypeEnv tys,
1611 minf_exports = names,
1612 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names mdl,
1613 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1616 -- bogusly different for non-GHCI (ToDo)
1620 getHomeModuleInfo hsc_env mdl =
1621 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1622 Nothing -> return Nothing
1624 let details = hm_details hmi
1625 return (Just (ModuleInfo {
1626 minf_type_env = md_types details,
1627 minf_exports = md_exports details,
1628 minf_rdr_env = mi_globals $! hm_iface hmi,
1629 minf_instances = md_insts details
1632 -- | The list of top-level entities defined in a module
1633 modInfoTyThings :: ModuleInfo -> [TyThing]
1634 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1636 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1637 modInfoTopLevelScope minf
1638 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1640 modInfoExports :: ModuleInfo -> [Name]
1641 modInfoExports minf = nameSetToList $! minf_exports minf
1643 -- | Returns the instances defined by the specified module.
1644 -- Warning: currently unimplemented for package modules.
1645 modInfoInstances :: ModuleInfo -> [Instance]
1646 modInfoInstances = minf_instances
1648 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1649 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1651 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1652 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1654 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1655 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1656 case lookupTypeEnv (minf_type_env minf) name of
1657 Just tyThing -> return (Just tyThing)
1659 eps <- readIORef (hsc_EPS hsc_env)
1660 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1662 isDictonaryId :: Id -> Bool
1664 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1666 -- | Looks up a global name: that is, any top-level name in any
1667 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1668 -- the interactive context, and therefore does not require a preceding
1670 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1671 lookupGlobalName s name = withSession s $ \hsc_env -> do
1672 eps <- readIORef (hsc_EPS hsc_env)
1673 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1679 | BinaryCode FilePath
1681 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1682 -- - typechecked syntax includes extra dictionary translation and
1683 -- AbsBinds which need to be translated back into something closer to
1684 -- the original source.
1687 -- - Data and Typeable instances for HsSyn.
1690 -- - things that aren't in the output of the renamer:
1691 -- - the export list
1695 -- - things that aren't in the output of the typechecker right now:
1696 -- - the export list
1698 -- - type signatures
1699 -- - type/data/newtype declarations
1700 -- - class declarations
1702 -- - extra things in the typechecker's output:
1703 -- - default methods are turned into top-level decls.
1704 -- - dictionary bindings
1706 -- ToDo: check for small transformations that happen to the syntax in
1707 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1709 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1710 -- to get from TyCons, Ids etc. to TH syntax (reify).
1712 -- :browse will use either lm_toplev or inspect lm_interface, depending
1713 -- on whether the module is interpreted or not.
1715 -- This is for reconstructing refactored source code
1716 -- Calls the lexer repeatedly.
1717 -- ToDo: add comment tokens to token stream
1718 getTokenStream :: Session -> Module -> IO [Located Token]
1721 -- -----------------------------------------------------------------------------
1722 -- Interactive evaluation
1726 -- | Set the interactive evaluation context.
1728 -- Setting the context doesn't throw away any bindings; the bindings
1729 -- we've built up in the InteractiveContext simply move to the new
1730 -- module. They always shadow anything in scope in the current context.
1731 setContext :: Session
1732 -> [Module] -- entire top level scope of these modules
1733 -> [Module] -- exports only of these modules
1735 setContext (Session ref) toplevs exports = do
1736 hsc_env <- readIORef ref
1737 let old_ic = hsc_IC hsc_env
1738 hpt = hsc_HPT hsc_env
1740 mapM_ (checkModuleExists hsc_env hpt) exports
1741 export_env <- mkExportEnv hsc_env exports
1742 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1743 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1744 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1745 ic_exports = exports,
1746 ic_rn_gbl_env = all_env } }
1748 -- Make a GlobalRdrEnv based on the exports of the modules only.
1749 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1750 mkExportEnv hsc_env mods = do
1751 stuff <- mapM (getModuleExports hsc_env) mods
1753 (_msgs, mb_name_sets) = unzip stuff
1754 gres = [ nameSetToGlobalRdrEnv name_set mod
1755 | (Just name_set, mod) <- zip mb_name_sets mods ]
1757 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1759 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1760 nameSetToGlobalRdrEnv names mod =
1761 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1762 | name <- nameSetToList names ]
1764 vanillaProv :: Module -> Provenance
1765 -- We're building a GlobalRdrEnv as if the user imported
1766 -- all the specified modules into the global interactive module
1767 vanillaProv mod = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1769 decl = ImpDeclSpec { is_mod = mod, is_as = mod,
1771 is_dloc = srcLocSpan interactiveSrcLoc }
1773 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1774 checkModuleExists hsc_env hpt mod =
1775 case lookupModuleEnv hpt mod of
1776 Just mod_info -> return ()
1777 _not_a_home_module -> do
1778 res <- findPackageModule hsc_env mod True
1780 Found _ _ -> return ()
1781 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1782 throwDyn (CmdLineError (showSDoc msg))
1784 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1785 mkTopLevEnv hpt modl
1786 = case lookupModuleEnv hpt modl of
1788 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1789 ++ showSDoc (pprModule modl)))
1791 case mi_globals (hm_iface details) of
1793 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1794 ++ showSDoc (pprModule modl)))
1795 Just env -> return env
1797 -- | Get the interactive evaluation context, consisting of a pair of the
1798 -- set of modules from which we take the full top-level scope, and the set
1799 -- of modules from which we take just the exports respectively.
1800 getContext :: Session -> IO ([Module],[Module])
1801 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1802 return (ic_toplev_scope ic, ic_exports ic))
1804 -- | Returns 'True' if the specified module is interpreted, and hence has
1805 -- its full top-level scope available.
1806 moduleIsInterpreted :: Session -> Module -> IO Bool
1807 moduleIsInterpreted s modl = withSession s $ \h ->
1808 case lookupModuleEnv (hsc_HPT h) modl of
1809 Just details -> return (isJust (mi_globals (hm_iface details)))
1810 _not_a_home_module -> return False
1812 -- | Looks up an identifier in the current interactive context (for :info)
1813 {-# DEPRECATED getInfo "we should be using parseName/lookupName instead" #-}
1814 getInfo :: Session -> String -> IO [GetInfoResult]
1815 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1817 -- | Returns all names in scope in the current interactive context
1818 getNamesInScope :: Session -> IO [Name]
1819 getNamesInScope s = withSession s $ \hsc_env -> do
1820 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1822 -- | Parses a string as an identifier, and returns the list of 'Name's that
1823 -- the identifier can refer to in the current interactive context.
1824 parseName :: Session -> String -> IO [Name]
1825 parseName s str = withSession s $ \hsc_env -> do
1826 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1827 case maybe_rdr_name of
1828 Nothing -> return []
1829 Just (L _ rdr_name) -> do
1830 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1832 Nothing -> return []
1833 Just ns -> return ns
1834 -- ToDo: should return error messages
1836 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1837 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1838 lookupName :: Session -> Name -> IO (Maybe TyThing)
1839 lookupName s name = withSession s $ \hsc_env -> do
1840 case lookupTypeEnv (ic_type_env (hsc_IC hsc_env)) name of
1841 Just tt -> return (Just tt)
1843 eps <- readIORef (hsc_EPS hsc_env)
1844 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1846 -- -----------------------------------------------------------------------------
1847 -- Getting the type of an expression
1849 -- | Get the type of an expression
1850 exprType :: Session -> String -> IO (Maybe Type)
1851 exprType s expr = withSession s $ \hsc_env -> do
1852 maybe_stuff <- hscTcExpr hsc_env expr
1854 Nothing -> return Nothing
1855 Just ty -> return (Just tidy_ty)
1857 tidy_ty = tidyType emptyTidyEnv ty
1858 dflags = hsc_dflags hsc_env
1860 -- -----------------------------------------------------------------------------
1861 -- Getting the kind of a type
1863 -- | Get the kind of a type
1864 typeKind :: Session -> String -> IO (Maybe Kind)
1865 typeKind s str = withSession s $ \hsc_env -> do
1866 maybe_stuff <- hscKcType hsc_env str
1868 Nothing -> return Nothing
1869 Just kind -> return (Just kind)
1871 -----------------------------------------------------------------------------
1872 -- cmCompileExpr: compile an expression and deliver an HValue
1874 compileExpr :: Session -> String -> IO (Maybe HValue)
1875 compileExpr s expr = withSession s $ \hsc_env -> do
1876 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1878 Nothing -> return Nothing
1879 Just (new_ic, names, hval) -> do
1881 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1883 case (names,hvals) of
1884 ([n],[hv]) -> return (Just hv)
1885 _ -> panic "compileExpr"
1887 -- -----------------------------------------------------------------------------
1888 -- running a statement interactively
1891 = RunOk [Name] -- ^ names bound by this evaluation
1892 | RunFailed -- ^ statement failed compilation
1893 | RunException Exception -- ^ statement raised an exception
1895 -- | Run a statement in the current interactive context. Statemenet
1896 -- may bind multple values.
1897 runStmt :: Session -> String -> IO RunResult
1898 runStmt (Session ref) expr
1900 hsc_env <- readIORef ref
1902 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1903 -- warnings about the implicit bindings we introduce.
1904 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1905 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1907 maybe_stuff <- hscStmt hsc_env' expr
1910 Nothing -> return RunFailed
1911 Just (new_hsc_env, names, hval) -> do
1913 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1914 either_hvals <- sandboxIO thing_to_run
1916 case either_hvals of
1918 -- on error, keep the *old* interactive context,
1919 -- so that 'it' is not bound to something
1920 -- that doesn't exist.
1921 return (RunException e)
1924 -- Get the newly bound things, and bind them.
1925 -- Don't need to delete any shadowed bindings;
1926 -- the new ones override the old ones.
1927 extendLinkEnv (zip names hvals)
1929 writeIORef ref new_hsc_env
1930 return (RunOk names)
1933 -- We run the statement in a "sandbox" to protect the rest of the
1934 -- system from anything the expression might do. For now, this
1935 -- consists of just wrapping it in an exception handler, but see below
1936 -- for another version.
1938 sandboxIO :: IO a -> IO (Either Exception a)
1939 sandboxIO thing = Exception.try thing
1942 -- This version of sandboxIO runs the expression in a completely new
1943 -- RTS main thread. It is disabled for now because ^C exceptions
1944 -- won't be delivered to the new thread, instead they'll be delivered
1945 -- to the (blocked) GHCi main thread.
1947 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1949 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1950 sandboxIO thing = do
1951 st_thing <- newStablePtr (Exception.try thing)
1952 alloca $ \ p_st_result -> do
1953 stat <- rts_evalStableIO st_thing p_st_result
1954 freeStablePtr st_thing
1956 then do st_result <- peek p_st_result
1957 result <- deRefStablePtr st_result
1958 freeStablePtr st_result
1959 return (Right result)
1961 return (Left (fromIntegral stat))
1963 foreign import "rts_evalStableIO" {- safe -}
1964 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1965 -- more informative than the C type!
1968 -- ---------------------------------------------------------------------------
1969 -- cmBrowseModule: get all the TyThings defined in a module
1971 {-# DEPRECATED browseModule "we should be using getModuleInfo instead" #-}
1972 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1973 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1974 mb_decls <- getModuleContents hsc_env modl exports_only
1976 Nothing -> return [] -- An error of some kind
1977 Just ds -> return ds
1980 -----------------------------------------------------------------------------
1981 -- show a module and it's source/object filenames
1983 showModule :: Session -> ModSummary -> IO String
1984 showModule s mod_summary = withSession s $ \hsc_env -> do
1985 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1986 Nothing -> panic "missing linkable"
1987 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1989 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))