1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
26 Target(..), TargetId(..),
33 -- * Loading\/compiling the program
35 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
37 workingDirectoryChanged,
38 checkModule, CheckedModule(..),
40 -- * Inspecting the module structure of the program
41 ModuleGraph, ModSummary(..),
46 -- * Inspecting modules
53 -- * Interactive evaluation
54 getBindings, getPrintUnqual,
56 setContext, getContext,
59 getInfo, GetInfoResult,
70 -- * Abstract syntax elements
73 Module, mkModule, pprModule,
80 isImplicitId, isDeadBinder,
81 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
83 isPrimOpId, isFCallId,
84 isDataConWorkId, idDataCon,
85 isBottomingId, isDictonaryId,
87 -- ** Type constructors
89 isClassTyCon, isSynTyCon, isNewTyCon,
91 -- ** Data constructors
96 classSCTheta, classTvsFds,
106 GhcException(..), showGhcException,
116 * return error messages rather than printing them.
117 * inline bits of HscMain here to simplify layering: hscGetInfo,
119 * implement second argument to load.
120 * we need to expose DynFlags, so should parseDynamicFlags really be
121 part of this interface?
122 * what StaticFlags should we expose, if any?
125 #include "HsVersions.h"
128 import qualified Linker
129 import Linker ( HValue, extendLinkEnv )
130 import NameEnv ( lookupNameEnv )
131 import TcRnDriver ( mkExportEnv, getModuleContents, tcRnLookupRdrName )
132 import RdrName ( plusGlobalRdrEnv )
133 import HscMain ( hscGetInfo, GetInfoResult, hscParseIdentifier,
134 hscStmt, hscTcExpr, hscKcType )
135 import Type ( tidyType )
136 import VarEnv ( emptyTidyEnv )
137 import GHC.Exts ( unsafeCoerce# )
138 import IfaceSyn ( IfaceDecl )
141 import Packages ( initPackages )
142 import NameSet ( NameSet, nameSetToList )
143 import RdrName ( GlobalRdrEnv )
144 import HsSyn ( HsModule, LHsBinds )
145 import Type ( Kind, Type, dropForAlls )
146 import Id ( Id, idType, isImplicitId, isDeadBinder,
147 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
149 isPrimOpId, isFCallId,
150 isDataConWorkId, idDataCon,
152 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon )
153 import Class ( Class, classSCTheta, classTvsFds )
154 import DataCon ( DataCon )
155 import Name ( Name, getName, nameModule_maybe )
156 import RdrName ( RdrName, gre_name, globalRdrEnvElts )
157 import NameEnv ( nameEnvElts )
158 import SrcLoc ( Located(..) )
159 import DriverPipeline
160 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
161 import GetImports ( getImports )
162 import Packages ( isHomePackage )
164 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
168 import SysTools ( initSysTools, cleanTempFiles )
173 import ErrUtils ( showPass, Messages, putMsg, debugTraceMsg )
174 import qualified ErrUtils
176 import StringBuffer ( StringBuffer, hGetStringBuffer )
178 import SysTools ( cleanTempFilesExcept )
179 import BasicTypes ( SuccessFlag(..), succeeded, failed )
180 import Maybes ( orElse, expectJust, mapCatMaybes )
181 import TcType ( tcSplitSigmaTy, isDictTy )
183 import Directory ( getModificationTime, doesFileExist )
184 import Maybe ( isJust, isNothing, fromJust, fromMaybe, catMaybes )
185 import Maybes ( expectJust )
186 import List ( partition, nub )
187 import qualified List
188 import Monad ( unless, when, foldM )
189 import System ( exitWith, ExitCode(..) )
190 import Time ( ClockTime )
191 import EXCEPTION as Exception hiding (handle)
194 import Prelude hiding (init)
196 -- -----------------------------------------------------------------------------
197 -- Exception handlers
199 -- | Install some default exception handlers and run the inner computation.
200 -- Unless you want to handle exceptions yourself, you should wrap this around
201 -- the top level of your program. The default handlers output the error
202 -- message(s) to stderr and exit cleanly.
203 defaultErrorHandler :: IO a -> IO a
204 defaultErrorHandler inner =
205 -- top-level exception handler: any unrecognised exception is a compiler bug.
206 handle (\exception -> do
209 -- an IO exception probably isn't our fault, so don't panic
210 IOException _ -> putMsg (show exception)
211 AsyncException StackOverflow ->
212 putMsg "stack overflow: use +RTS -K<size> to increase it"
213 _other -> putMsg (show (Panic (show exception)))
214 exitWith (ExitFailure 1)
217 -- all error messages are propagated as exceptions
218 handleDyn (\dyn -> do
221 PhaseFailed _ code -> exitWith code
222 Interrupted -> exitWith (ExitFailure 1)
223 _ -> do putMsg (show (dyn :: GhcException))
224 exitWith (ExitFailure 1)
228 -- | Install a default cleanup handler to remove temporary files
229 -- deposited by a GHC run. This is seperate from
230 -- 'defaultErrorHandler', because you might want to override the error
231 -- handling, but still get the ordinary cleanup behaviour.
232 defaultCleanupHandler :: DynFlags -> IO a -> IO a
233 defaultCleanupHandler dflags inner =
234 -- make sure we clean up after ourselves
235 later (unless (dopt Opt_KeepTmpFiles dflags) $
236 cleanTempFiles dflags)
237 -- exceptions will be blocked while we clean the temporary files,
238 -- so there shouldn't be any difficulty if we receive further
243 -- | Initialises GHC. This must be done /once/ only. Takes the
244 -- command-line arguments. All command-line arguments which aren't
245 -- understood by GHC will be returned.
247 init :: [String] -> IO [String]
250 installSignalHandlers
252 -- Grab the -B option if there is one
253 let (minusB_args, argv1) = partition (prefixMatch "-B") args
254 dflags0 <- initSysTools minusB_args defaultDynFlags
255 writeIORef v_initDynFlags dflags0
257 -- Parse the static flags
258 argv2 <- parseStaticFlags argv1
261 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
262 -- stores the DynFlags between the call to init and subsequent
263 -- calls to newSession.
265 -- | Starts a new session. A session consists of a set of loaded
266 -- modules, a set of options (DynFlags), and an interactive context.
267 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
269 newSession :: GhcMode -> IO Session
271 dflags0 <- readIORef v_initDynFlags
272 dflags <- initDynFlags dflags0
273 env <- newHscEnv dflags{ ghcMode=mode }
277 -- tmp: this breaks the abstraction, but required because DriverMkDepend
278 -- needs to call the Finder. ToDo: untangle this.
279 sessionHscEnv :: Session -> IO HscEnv
280 sessionHscEnv (Session ref) = readIORef ref
282 withSession :: Session -> (HscEnv -> IO a) -> IO a
283 withSession (Session ref) f = do h <- readIORef ref; f h
285 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
286 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
288 -- -----------------------------------------------------------------------------
291 -- | Grabs the DynFlags from the Session
292 getSessionDynFlags :: Session -> IO DynFlags
293 getSessionDynFlags s = withSession s (return . hsc_dflags)
295 -- | Updates the DynFlags in a Session
296 setSessionDynFlags :: Session -> DynFlags -> IO ()
297 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
299 -- | Messages during compilation (eg. warnings and progress messages)
300 -- are reported using this callback. By default, these messages are
301 -- printed to stderr.
302 setMsgHandler :: (String -> IO ()) -> IO ()
303 setMsgHandler = ErrUtils.setMsgHandler
305 -- -----------------------------------------------------------------------------
308 -- ToDo: think about relative vs. absolute file paths. And what
309 -- happens when the current directory changes.
311 -- | Sets the targets for this session. Each target may be a module name
312 -- or a filename. The targets correspond to the set of root modules for
313 -- the program\/library. Unloading the current program is achieved by
314 -- setting the current set of targets to be empty, followed by load.
315 setTargets :: Session -> [Target] -> IO ()
316 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
318 -- | returns the current set of targets
319 getTargets :: Session -> IO [Target]
320 getTargets s = withSession s (return . hsc_targets)
322 -- | Add another target
323 addTarget :: Session -> Target -> IO ()
325 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
328 removeTarget :: Session -> TargetId -> IO ()
329 removeTarget s target_id
330 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
332 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
334 -- Attempts to guess what Target a string refers to. This function implements
335 -- the --make/GHCi command-line syntax for filenames:
337 -- - if the string looks like a Haskell source filename, then interpret
339 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
341 -- - otherwise interpret the string as a module name
343 guessTarget :: String -> IO Target
345 | isHaskellSrcFilename file
346 = return (Target (TargetFile file) Nothing)
348 = do exists <- doesFileExist hs_file
349 if exists then return (Target (TargetFile hs_file) Nothing) else do
350 exists <- doesFileExist lhs_file
351 if exists then return (Target (TargetFile lhs_file) Nothing) else do
352 return (Target (TargetModule (mkModule file)) Nothing)
354 hs_file = file ++ ".hs"
355 lhs_file = file ++ ".lhs"
357 -- -----------------------------------------------------------------------------
358 -- Loading the program
360 -- Perform a dependency analysis starting from the current targets
361 -- and update the session with the new module graph.
362 depanal :: Session -> [Module] -> IO ()
363 depanal (Session ref) excluded_mods = do
364 hsc_env <- readIORef ref
366 dflags = hsc_dflags hsc_env
367 gmode = ghcMode (hsc_dflags hsc_env)
368 targets = hsc_targets hsc_env
369 old_graph = hsc_mod_graph hsc_env
371 showPass dflags "Chasing dependencies"
372 when (gmode == BatchCompile) $
373 debugTraceMsg dflags 1 (showSDoc (hcat [
374 text "Chasing modules from: ",
375 hcat (punctuate comma (map pprTarget targets))]))
377 graph <- downsweep hsc_env old_graph excluded_mods
378 writeIORef ref hsc_env{ hsc_mod_graph=graph }
381 -- | The result of load.
383 = LoadOk Errors -- ^ all specified targets were loaded successfully.
384 | LoadFailed Errors -- ^ not all modules were loaded.
386 type Errors = [String]
388 data ErrMsg = ErrMsg {
389 errMsgSeverity :: Severity, -- warning, error, etc.
390 errMsgSpans :: [SrcSpan],
391 errMsgShortDoc :: Doc,
392 errMsgExtraInfo :: Doc
399 | LoadDependenciesOf Module
401 -- | Try to load the program. If a Module is supplied, then just
402 -- attempt to load up to this target. If no Module is supplied,
403 -- then try to load all targets.
404 load :: Session -> LoadHowMuch -> IO SuccessFlag
405 load session how_much =
406 loadMsgs session how_much ErrUtils.printErrorsAndWarnings
408 -- | Version of 'load' that takes a callback function to be invoked
409 -- on compiler errors and warnings as they occur during compilation.
410 loadMsgs :: Session -> LoadHowMuch -> (Messages-> IO ()) -> IO SuccessFlag
411 loadMsgs s@(Session ref) how_much msg_act
413 -- Dependency analysis first. Note that this fixes the module graph:
414 -- even if we don't get a fully successful upsweep, the full module
415 -- graph is still retained in the Session. We can tell which modules
416 -- were successfully loaded by inspecting the Session's HPT.
419 hsc_env <- readIORef ref
421 let hpt1 = hsc_HPT hsc_env
422 let dflags = hsc_dflags hsc_env
423 let mod_graph = hsc_mod_graph hsc_env
425 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
426 let verb = verbosity dflags
428 -- The "bad" boot modules are the ones for which we have
429 -- B.hs-boot in the module graph, but no B.hs
430 -- The downsweep should have ensured this does not happen
432 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
433 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
434 not (ms_mod s `elem` all_home_mods)]
435 ASSERT( null bad_boot_mods ) return ()
437 -- mg2_with_srcimps drops the hi-boot nodes, returning a
438 -- graph with cycles. Among other things, it is used for
439 -- backing out partially complete cycles following a failed
440 -- upsweep, and for removing from hpt all the modules
441 -- not in strict downwards closure, during calls to compile.
442 let mg2_with_srcimps :: [SCC ModSummary]
443 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
445 -- check the stability property for each module.
446 stable_mods@(stable_obj,stable_bco)
447 | BatchCompile <- ghci_mode = ([],[])
448 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
450 -- prune bits of the HPT which are definitely redundant now,
452 pruned_hpt = pruneHomePackageTable hpt1
453 (flattenSCCs mg2_with_srcimps)
458 debugTraceMsg dflags 2 (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
459 text "Stable BCO:" <+> ppr stable_bco))
461 -- Unload any modules which are going to be re-linked this time around.
462 let stable_linkables = [ linkable
463 | m <- stable_obj++stable_bco,
464 Just hmi <- [lookupModuleEnv pruned_hpt m],
465 Just linkable <- [hm_linkable hmi] ]
466 unload hsc_env stable_linkables
468 -- We could at this point detect cycles which aren't broken by
469 -- a source-import, and complain immediately, but it seems better
470 -- to let upsweep_mods do this, so at least some useful work gets
471 -- done before the upsweep is abandoned.
472 --hPutStrLn stderr "after tsort:\n"
473 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
475 -- Now do the upsweep, calling compile for each module in
476 -- turn. Final result is version 3 of everything.
478 -- Topologically sort the module graph, this time including hi-boot
479 -- nodes, and possibly just including the portion of the graph
480 -- reachable from the module specified in the 2nd argument to load.
481 -- This graph should be cycle-free.
482 -- If we're restricting the upsweep to a portion of the graph, we
483 -- also want to retain everything that is still stable.
484 let full_mg :: [SCC ModSummary]
485 full_mg = topSortModuleGraph False mod_graph Nothing
487 maybe_top_mod = case how_much of
489 LoadDependenciesOf m -> Just m
492 partial_mg0 :: [SCC ModSummary]
493 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
495 -- LoadDependenciesOf m: we want the upsweep to stop just
496 -- short of the specified module (unless the specified module
499 | LoadDependenciesOf mod <- how_much
500 = ASSERT( case last partial_mg0 of
501 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
502 List.init partial_mg0
508 | AcyclicSCC ms <- full_mg,
509 ms_mod ms `elem` stable_obj++stable_bco,
510 ms_mod ms `notElem` [ ms_mod ms' |
511 AcyclicSCC ms' <- partial_mg ] ]
513 mg = stable_mg ++ partial_mg
515 -- clean up between compilations
516 let cleanup = cleanTempFilesExcept dflags
517 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
519 (upsweep_ok, hsc_env1, modsUpswept)
520 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
521 pruned_hpt stable_mods cleanup msg_act mg
523 -- Make modsDone be the summaries for each home module now
524 -- available; this should equal the domain of hpt3.
525 -- Get in in a roughly top .. bottom order (hence reverse).
527 let modsDone = reverse modsUpswept
529 -- Try and do linking in some form, depending on whether the
530 -- upsweep was completely or only partially successful.
532 if succeeded upsweep_ok
535 -- Easy; just relink it all.
536 do debugTraceMsg dflags 2 "Upsweep completely successful."
538 -- Clean up after ourselves
539 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
541 -- Issue a warning for the confusing case where the user
542 -- said '-o foo' but we're not going to do any linking.
543 -- We attempt linking if either (a) one of the modules is
544 -- called Main, or (b) the user said -no-hs-main, indicating
545 -- that main() is going to come from somewhere else.
547 let ofile = outputFile dflags
548 let no_hs_main = dopt Opt_NoHsMain dflags
549 let mb_main_mod = mainModIs dflags
551 main_mod = mb_main_mod `orElse` "Main"
553 = any ((==main_mod).moduleUserString.ms_mod)
555 do_linking = a_root_is_Main || no_hs_main
557 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
558 debugTraceMsg dflags 1 ("Warning: output was redirected with -o, " ++
559 "but no output will be generated\n" ++
560 "because there is no " ++ main_mod ++ " module.")
562 -- link everything together
563 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
565 loadFinish Succeeded linkresult ref hsc_env1
568 -- Tricky. We need to back out the effects of compiling any
569 -- half-done cycles, both so as to clean up the top level envs
570 -- and to avoid telling the interactive linker to link them.
571 do debugTraceMsg dflags 2 "Upsweep partially successful."
574 = map ms_mod modsDone
575 let mods_to_zap_names
576 = findPartiallyCompletedCycles modsDone_names
579 = filter ((`notElem` mods_to_zap_names).ms_mod)
582 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
585 -- Clean up after ourselves
586 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
588 -- there should be no Nothings where linkables should be, now
589 ASSERT(all (isJust.hm_linkable)
590 (moduleEnvElts (hsc_HPT hsc_env))) do
592 -- Link everything together
593 linkresult <- link ghci_mode dflags False hpt4
595 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
596 loadFinish Failed linkresult ref hsc_env4
598 -- Finish up after a load.
600 -- If the link failed, unload everything and return.
601 loadFinish all_ok Failed ref hsc_env
602 = do unload hsc_env []
603 writeIORef ref $! discardProg hsc_env
606 -- Empty the interactive context and set the module context to the topmost
607 -- newly loaded module, or the Prelude if none were loaded.
608 loadFinish all_ok Succeeded ref hsc_env
609 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
613 -- Forget the current program, but retain the persistent info in HscEnv
614 discardProg :: HscEnv -> HscEnv
616 = hsc_env { hsc_mod_graph = emptyMG,
617 hsc_IC = emptyInteractiveContext,
618 hsc_HPT = emptyHomePackageTable }
620 -- used to fish out the preprocess output files for the purposes of
621 -- cleaning up. The preprocessed file *might* be the same as the
622 -- source file, but that doesn't do any harm.
623 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
625 -- -----------------------------------------------------------------------------
629 CheckedModule { parsedSource :: ParsedSource,
630 -- ToDo: renamedSource
631 typecheckedSource :: Maybe TypecheckedSource,
632 checkedModuleInfo :: Maybe ModuleInfo
635 type ParsedSource = Located (HsModule RdrName)
636 type TypecheckedSource = LHsBinds Id
638 -- | This is the way to get access to parsed and typechecked source code
639 -- for a module. 'checkModule' loads all the dependencies of the specified
640 -- module in the Session, and then attempts to typecheck the module. If
641 -- successful, it returns the abstract syntax for the module.
642 checkModule :: Session -> Module -> (Messages -> IO ())
643 -> IO (Maybe CheckedModule)
644 checkModule session@(Session ref) mod msg_act = do
645 -- load up the dependencies first
646 r <- loadMsgs session (LoadDependenciesOf mod) msg_act
647 if (failed r) then return Nothing else do
649 -- now parse & typecheck the module
650 hsc_env <- readIORef ref
651 let mg = hsc_mod_graph hsc_env
652 case [ ms | ms <- mg, ms_mod ms == mod ] of
655 r <- hscFileCheck hsc_env msg_act ms
659 HscChecked parsed Nothing ->
660 return (Just (CheckedModule parsed Nothing Nothing))
661 HscChecked parsed (Just (tc_binds, rdr_env, details)) -> do
662 let minf = ModuleInfo {
663 minf_details = details,
664 minf_rdr_env = Just rdr_env
666 return (Just (CheckedModule {
667 parsedSource = parsed,
668 typecheckedSource = Just tc_binds,
669 checkedModuleInfo = Just minf }))
671 -- ---------------------------------------------------------------------------
674 unload :: HscEnv -> [Linkable] -> IO ()
675 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
676 = case ghcMode (hsc_dflags hsc_env) of
677 BatchCompile -> return ()
678 JustTypecheck -> return ()
680 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
682 Interactive -> panic "unload: no interpreter"
684 other -> panic "unload: strange mode"
686 -- -----------------------------------------------------------------------------
690 Stability tells us which modules definitely do not need to be recompiled.
691 There are two main reasons for having stability:
693 - avoid doing a complete upsweep of the module graph in GHCi when
694 modules near the bottom of the tree have not changed.
696 - to tell GHCi when it can load object code: we can only load object code
697 for a module when we also load object code fo all of the imports of the
698 module. So we need to know that we will definitely not be recompiling
699 any of these modules, and we can use the object code.
701 NB. stability is of no importance to BatchCompile at all, only Interactive.
702 (ToDo: what about JustTypecheck?)
704 The stability check is as follows. Both stableObject and
705 stableBCO are used during the upsweep phase later.
708 stable m = stableObject m || stableBCO m
711 all stableObject (imports m)
712 && old linkable does not exist, or is == on-disk .o
713 && date(on-disk .o) > date(.hs)
716 all stable (imports m)
717 && date(BCO) > date(.hs)
720 These properties embody the following ideas:
722 - if a module is stable:
723 - if it has been compiled in a previous pass (present in HPT)
724 then it does not need to be compiled or re-linked.
725 - if it has not been compiled in a previous pass,
726 then we only need to read its .hi file from disk and
727 link it to produce a ModDetails.
729 - if a modules is not stable, we will definitely be at least
730 re-linking, and possibly re-compiling it during the upsweep.
731 All non-stable modules can (and should) therefore be unlinked
734 - Note that objects are only considered stable if they only depend
735 on other objects. We can't link object code against byte code.
739 :: HomePackageTable -- HPT from last compilation
740 -> [SCC ModSummary] -- current module graph (cyclic)
741 -> [Module] -- all home modules
742 -> ([Module], -- stableObject
743 [Module]) -- stableBCO
745 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
747 checkSCC (stable_obj, stable_bco) scc0
748 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
749 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
750 | otherwise = (stable_obj, stable_bco)
752 scc = flattenSCC scc0
753 scc_mods = map ms_mod scc
754 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
756 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
757 -- all imports outside the current SCC, but in the home pkg
759 stable_obj_imps = map (`elem` stable_obj) scc_allimps
760 stable_bco_imps = map (`elem` stable_bco) scc_allimps
767 and (zipWith (||) stable_obj_imps stable_bco_imps)
771 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
775 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
777 Just hmi | Just l <- hm_linkable hmi
778 -> isObjectLinkable l && t == linkableTime l
779 -- why '>=' rather than '>' above? If the filesystem stores
780 -- times to the nearset second, we may occasionally find that
781 -- the object & source have the same modification time,
782 -- especially if the source was automatically generated
783 -- and compiled. Using >= is slightly unsafe, but it matches
787 = case lookupModuleEnv hpt (ms_mod ms) of
789 Just hmi | Just l <- hm_linkable hmi ->
790 not (isObjectLinkable l) &&
791 linkableTime l >= ms_hs_date ms
793 ms_allimps :: ModSummary -> [Module]
794 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
796 -- -----------------------------------------------------------------------------
797 -- Prune the HomePackageTable
799 -- Before doing an upsweep, we can throw away:
801 -- - For non-stable modules:
802 -- - all ModDetails, all linked code
803 -- - all unlinked code that is out of date with respect to
806 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
807 -- space at the end of the upsweep, because the topmost ModDetails of the
808 -- old HPT holds on to the entire type environment from the previous
811 pruneHomePackageTable
814 -> ([Module],[Module])
817 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
818 = mapModuleEnv prune hpt
820 | is_stable modl = hmi'
821 | otherwise = hmi'{ hm_details = emptyModDetails }
823 modl = mi_module (hm_iface hmi)
824 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
825 = hmi{ hm_linkable = Nothing }
828 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
830 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
832 is_stable m = m `elem` stable_obj || m `elem` stable_bco
834 -- -----------------------------------------------------------------------------
836 -- Return (names of) all those in modsDone who are part of a cycle
837 -- as defined by theGraph.
838 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
839 findPartiallyCompletedCycles modsDone theGraph
843 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
844 chew ((CyclicSCC vs):rest)
845 = let names_in_this_cycle = nub (map ms_mod vs)
847 = nub ([done | done <- modsDone,
848 done `elem` names_in_this_cycle])
849 chewed_rest = chew rest
851 if notNull mods_in_this_cycle
852 && length mods_in_this_cycle < length names_in_this_cycle
853 then mods_in_this_cycle ++ chewed_rest
856 -- -----------------------------------------------------------------------------
859 -- This is where we compile each module in the module graph, in a pass
860 -- from the bottom to the top of the graph.
862 -- There better had not be any cyclic groups here -- we check for them.
865 :: HscEnv -- Includes initially-empty HPT
866 -> HomePackageTable -- HPT from last time round (pruned)
867 -> ([Module],[Module]) -- stable modules (see checkStability)
868 -> IO () -- How to clean up unwanted tmp files
869 -> (Messages -> IO ()) -- Compiler error message callback
870 -> [SCC ModSummary] -- Mods to do (the worklist)
872 HscEnv, -- With an updated HPT
873 [ModSummary]) -- Mods which succeeded
875 upsweep hsc_env old_hpt stable_mods cleanup msg_act
877 = return (Succeeded, hsc_env, [])
879 upsweep hsc_env old_hpt stable_mods cleanup msg_act
881 = do putMsg (showSDoc (cyclicModuleErr ms))
882 return (Failed, hsc_env, [])
884 upsweep hsc_env old_hpt stable_mods cleanup msg_act
885 (AcyclicSCC mod:mods)
886 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
887 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
888 -- (moduleEnvElts (hsc_HPT hsc_env)))
890 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods msg_act mod
892 cleanup -- Remove unwanted tmp files between compilations
895 Nothing -> return (Failed, hsc_env, [])
897 { let this_mod = ms_mod mod
899 -- Add new info to hsc_env
900 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
902 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
904 -- Space-saving: delete the old HPT entry
905 -- for mod BUT if mod is a hs-boot
906 -- node, don't delete it. For the
907 -- interface, the HPT entry is probaby for the
908 -- main Haskell source file. Deleting it
909 -- would force .. (what?? --SDM)
910 old_hpt1 | isBootSummary mod = old_hpt
911 | otherwise = delModuleEnv old_hpt this_mod
913 ; (restOK, hsc_env2, modOKs)
914 <- upsweep hsc_env1 old_hpt1 stable_mods cleanup
916 ; return (restOK, hsc_env2, mod:modOKs)
920 -- Compile a single module. Always produce a Linkable for it if
921 -- successful. If no compilation happened, return the old Linkable.
922 upsweep_mod :: HscEnv
924 -> ([Module],[Module])
925 -> (Messages -> IO ())
927 -> IO (Maybe HomeModInfo) -- Nothing => Failed
929 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) msg_act summary
932 this_mod = ms_mod summary
933 mb_obj_date = ms_obj_date summary
934 obj_fn = ml_obj_file (ms_location summary)
935 hs_date = ms_hs_date summary
937 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
938 compile_it = upsweep_compile hsc_env old_hpt this_mod
941 case ghcMode (hsc_dflags hsc_env) of
944 -- Batch-compilating is easy: just check whether we have
945 -- an up-to-date object file. If we do, then the compiler
946 -- needs to do a recompilation check.
947 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
949 findObjectLinkable this_mod obj_fn obj_date
950 compile_it (Just linkable)
957 _ | is_stable_obj, isJust old_hmi ->
959 -- object is stable, and we have an entry in the
960 -- old HPT: nothing to do
962 | is_stable_obj, isNothing old_hmi -> do
964 findObjectLinkable this_mod obj_fn
965 (expectJust "upseep1" mb_obj_date)
966 compile_it (Just linkable)
967 -- object is stable, but we need to load the interface
968 -- off disk to make a HMI.
971 ASSERT(isJust old_hmi) -- must be in the old_hpt
973 -- BCO is stable: nothing to do
975 | Just hmi <- old_hmi,
976 Just l <- hm_linkable hmi, not (isObjectLinkable l),
977 linkableTime l >= ms_hs_date summary ->
979 -- we have an old BCO that is up to date with respect
980 -- to the source: do a recompilation check as normal.
984 -- no existing code at all: we must recompile.
986 is_stable_obj = this_mod `elem` stable_obj
987 is_stable_bco = this_mod `elem` stable_bco
989 old_hmi = lookupModuleEnv old_hpt this_mod
991 -- Run hsc to compile a module
992 upsweep_compile hsc_env old_hpt this_mod msg_act summary mb_old_linkable = do
994 -- The old interface is ok if it's in the old HPT
995 -- a) we're compiling a source file, and the old HPT
996 -- entry is for a source file
997 -- b) we're compiling a hs-boot file
998 -- Case (b) allows an hs-boot file to get the interface of its
999 -- real source file on the second iteration of the compilation
1000 -- manager, but that does no harm. Otherwise the hs-boot file
1001 -- will always be recompiled
1004 = case lookupModuleEnv old_hpt this_mod of
1006 Just hm_info | isBootSummary summary -> Just iface
1007 | not (mi_boot iface) -> Just iface
1008 | otherwise -> Nothing
1010 iface = hm_iface hm_info
1012 compresult <- compile hsc_env msg_act summary mb_old_linkable mb_old_iface
1015 -- Compilation failed. Compile may still have updated the PCS, tho.
1016 CompErrs -> return Nothing
1018 -- Compilation "succeeded", and may or may not have returned a new
1019 -- linkable (depending on whether compilation was actually performed
1021 CompOK new_details new_iface new_linkable
1022 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1023 hm_details = new_details,
1024 hm_linkable = new_linkable }
1025 return (Just new_info)
1028 -- Filter modules in the HPT
1029 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1030 retainInTopLevelEnvs keep_these hpt
1031 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1033 , let mb_mod_info = lookupModuleEnv hpt mod
1034 , isJust mb_mod_info ]
1036 -- ---------------------------------------------------------------------------
1037 -- Topological sort of the module graph
1040 :: Bool -- Drop hi-boot nodes? (see below)
1044 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1045 -- The resulting list of strongly-connected-components is in topologically
1046 -- sorted order, starting with the module(s) at the bottom of the
1047 -- dependency graph (ie compile them first) and ending with the ones at
1050 -- Drop hi-boot nodes (first boolean arg)?
1052 -- False: treat the hi-boot summaries as nodes of the graph,
1053 -- so the graph must be acyclic
1055 -- True: eliminate the hi-boot nodes, and instead pretend
1056 -- the a source-import of Foo is an import of Foo
1057 -- The resulting graph has no hi-boot nodes, but can by cyclic
1059 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1060 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1061 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1062 = stronglyConnComp (map vertex_fn (reachable graph root))
1064 -- restrict the graph to just those modules reachable from
1065 -- the specified module. We do this by building a graph with
1066 -- the full set of nodes, and determining the reachable set from
1067 -- the specified node.
1068 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1069 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1071 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1072 | otherwise = throwDyn (ProgramError "module does not exist")
1074 moduleGraphNodes :: Bool -> [ModSummary]
1075 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1076 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1078 -- Drop hs-boot nodes by using HsSrcFile as the key
1079 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1080 | otherwise = HsBootFile
1082 -- We use integers as the keys for the SCC algorithm
1083 nodes :: [(ModSummary, Int, [Int])]
1084 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1085 out_edge_keys hs_boot_key (ms_srcimps s) ++
1086 out_edge_keys HsSrcFile (ms_imps s) )
1088 , not (isBootSummary s && drop_hs_boot_nodes) ]
1089 -- Drop the hi-boot ones if told to do so
1091 key_map :: NodeMap Int
1092 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1095 lookup_key :: HscSource -> Module -> Maybe Int
1096 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1098 out_edge_keys :: HscSource -> [Module] -> [Int]
1099 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1100 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1101 -- the IsBootInterface parameter True; else False
1104 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1105 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1107 msKey :: ModSummary -> NodeKey
1108 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1110 emptyNodeMap :: NodeMap a
1111 emptyNodeMap = emptyFM
1113 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1114 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1116 nodeMapElts :: NodeMap a -> [a]
1117 nodeMapElts = eltsFM
1119 -- -----------------------------------------------------------------
1120 -- The unlinked image
1122 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1123 -- binaries (byte code or object code). Even when it links bytecode
1124 -- it keeps the unlinked version so it can re-link it later without
1127 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1129 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1130 findModuleLinkable_maybe lis mod
1131 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1134 many -> pprPanic "findModuleLinkable" (ppr mod)
1136 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1137 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1139 -----------------------------------------------------------------------------
1140 -- Downsweep (dependency analysis)
1142 -- Chase downwards from the specified root set, returning summaries
1143 -- for all home modules encountered. Only follow source-import
1146 -- We pass in the previous collection of summaries, which is used as a
1147 -- cache to avoid recalculating a module summary if the source is
1150 -- The returned list of [ModSummary] nodes has one node for each home-package
1151 -- module, plus one for any hs-boot files. The imports of these nodes
1152 -- are all there, including the imports of non-home-package modules.
1155 -> [ModSummary] -- Old summaries
1156 -> [Module] -- Ignore dependencies on these; treat them as
1157 -- if they were package modules
1159 downsweep hsc_env old_summaries excl_mods
1160 = do rootSummaries <- mapM getRootSummary roots
1161 checkDuplicates rootSummaries
1162 loop (concatMap msDeps rootSummaries)
1163 (mkNodeMap rootSummaries)
1165 roots = hsc_targets hsc_env
1167 old_summary_map :: NodeMap ModSummary
1168 old_summary_map = mkNodeMap old_summaries
1170 getRootSummary :: Target -> IO ModSummary
1171 getRootSummary (Target (TargetFile file) maybe_buf)
1172 = do exists <- doesFileExist file
1173 if exists then summariseFile hsc_env file maybe_buf else do
1174 throwDyn (CmdLineError ("can't find file: " ++ file))
1175 getRootSummary (Target (TargetModule modl) maybe_buf)
1176 = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False
1177 modl maybe_buf excl_mods
1178 case maybe_summary of
1179 Nothing -> packageModErr modl
1182 -- In a root module, the filename is allowed to diverge from the module
1183 -- name, so we have to check that there aren't multiple root files
1184 -- defining the same module (otherwise the duplicates will be silently
1185 -- ignored, leading to confusing behaviour).
1186 checkDuplicates :: [ModSummary] -> IO ()
1187 checkDuplicates summaries = mapM_ check summaries
1192 many -> multiRootsErr modl many
1193 where modl = ms_mod summ
1195 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1196 | summ' <- summaries, ms_mod summ' == modl ]
1198 loop :: [(FilePath,Module,IsBootInterface)]
1199 -- Work list: process these modules
1200 -> NodeMap ModSummary
1203 -- The result includes the worklist, except
1204 -- for those mentioned in the visited set
1205 loop [] done = return (nodeMapElts done)
1206 loop ((cur_path, wanted_mod, is_boot) : ss) done
1207 | key `elemFM` done = loop ss done
1208 | otherwise = do { mb_s <- summarise hsc_env old_summary_map
1209 (Just cur_path) is_boot
1210 wanted_mod Nothing excl_mods
1212 Nothing -> loop ss done
1213 Just s -> loop (msDeps s ++ ss)
1214 (addToFM done key s) }
1216 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1218 msDeps :: ModSummary -> [(FilePath, -- Importing module
1219 Module, -- Imported module
1220 IsBootInterface)] -- {-# SOURCE #-} import or not
1221 -- (msDeps s) returns the dependencies of the ModSummary s.
1222 -- A wrinkle is that for a {-# SOURCE #-} import we return
1223 -- *both* the hs-boot file
1224 -- *and* the source file
1225 -- as "dependencies". That ensures that the list of all relevant
1226 -- modules always contains B.hs if it contains B.hs-boot.
1227 -- Remember, this pass isn't doing the topological sort. It's
1228 -- just gathering the list of all relevant ModSummaries
1229 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1230 ++ [(f,m,False) | m <- ms_imps s]
1232 f = msHsFilePath s -- Keep the importing module for error reporting
1235 -----------------------------------------------------------------------------
1236 -- Summarising modules
1238 -- We have two types of summarisation:
1240 -- * Summarise a file. This is used for the root module(s) passed to
1241 -- cmLoadModules. The file is read, and used to determine the root
1242 -- module name. The module name may differ from the filename.
1244 -- * Summarise a module. We are given a module name, and must provide
1245 -- a summary. The finder is used to locate the file in which the module
1248 summariseFile :: HscEnv -> FilePath
1249 -> Maybe (StringBuffer,ClockTime)
1251 -- Used for Haskell source only, I think
1252 -- We know the file name, and we know it exists,
1253 -- but we don't necessarily know the module name (might differ)
1254 summariseFile hsc_env file maybe_buf
1255 = do let dflags = hsc_dflags hsc_env
1257 (dflags', hspp_fn, buf)
1258 <- preprocessFile dflags file maybe_buf
1260 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1262 -- Make a ModLocation for this file
1263 location <- mkHomeModLocation dflags mod file
1265 -- Tell the Finder cache where it is, so that subsequent calls
1266 -- to findModule will find it, even if it's not on any search path
1267 addHomeModuleToFinder hsc_env mod location
1269 src_timestamp <- case maybe_buf of
1270 Just (_,t) -> return t
1271 Nothing -> getModificationTime file
1273 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1275 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1276 ms_location = location,
1277 ms_hspp_file = Just hspp_fn,
1278 ms_hspp_buf = Just buf,
1279 ms_srcimps = srcimps, ms_imps = the_imps,
1280 ms_hs_date = src_timestamp,
1281 ms_obj_date = obj_timestamp })
1283 -- Summarise a module, and pick up source and timestamp.
1285 -> NodeMap ModSummary -- Map of old summaries
1286 -> Maybe FilePath -- Importing module (for error messages)
1287 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1288 -> Module -- Imported module to be summarised
1289 -> Maybe (StringBuffer, ClockTime)
1290 -> [Module] -- Modules to exclude
1291 -> IO (Maybe ModSummary) -- Its new summary
1293 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1294 | wanted_mod `elem` excl_mods
1297 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1298 = do -- Find its new timestamp; all the
1299 -- ModSummaries in the old map have valid ml_hs_files
1300 let location = ms_location old_summary
1301 src_fn = expectJust "summarise" (ml_hs_file location)
1303 -- return the cached summary if the source didn't change
1304 src_timestamp <- case maybe_buf of
1305 Just (_,t) -> return t
1306 Nothing -> getModificationTime src_fn
1308 if ms_hs_date old_summary == src_timestamp
1309 then do -- update the object-file timestamp
1310 obj_timestamp <- getObjTimestamp location is_boot
1311 return (Just old_summary{ ms_obj_date = obj_timestamp })
1313 -- source changed: re-summarise
1314 new_summary location src_fn maybe_buf src_timestamp
1317 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1320 | not (isHomePackage pkg) -> return Nothing
1321 -- Drop external-pkg
1322 | isJust (ml_hs_file location) -> just_found location
1324 err -> noModError dflags cur_mod wanted_mod err
1327 dflags = hsc_dflags hsc_env
1329 hsc_src = if is_boot then HsBootFile else HsSrcFile
1331 just_found location = do
1332 -- Adjust location to point to the hs-boot source file,
1333 -- hi file, object file, when is_boot says so
1334 let location' | is_boot = addBootSuffixLocn location
1335 | otherwise = location
1336 src_fn = expectJust "summarise2" (ml_hs_file location')
1338 -- Check that it exists
1339 -- It might have been deleted since the Finder last found it
1340 maybe_t <- modificationTimeIfExists src_fn
1342 Nothing -> noHsFileErr cur_mod src_fn
1343 Just t -> new_summary location' src_fn Nothing t
1346 new_summary location src_fn maybe_bug src_timestamp
1348 -- Preprocess the source file and get its imports
1349 -- The dflags' contains the OPTIONS pragmas
1350 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1351 (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1353 when (mod_name /= wanted_mod) $
1354 throwDyn (ProgramError
1355 (showSDoc (text src_fn
1356 <> text ": file name does not match module name"
1357 <+> quotes (ppr mod_name))))
1359 -- Find the object timestamp, and return the summary
1360 obj_timestamp <- getObjTimestamp location is_boot
1362 return (Just ( ModSummary { ms_mod = wanted_mod,
1363 ms_hsc_src = hsc_src,
1364 ms_location = location,
1365 ms_hspp_file = Just hspp_fn,
1366 ms_hspp_buf = Just buf,
1367 ms_srcimps = srcimps,
1369 ms_hs_date = src_timestamp,
1370 ms_obj_date = obj_timestamp }))
1373 getObjTimestamp location is_boot
1374 = if is_boot then return Nothing
1375 else modificationTimeIfExists (ml_obj_file location)
1378 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1379 -> IO (DynFlags, FilePath, StringBuffer)
1380 preprocessFile dflags src_fn Nothing
1382 (dflags', hspp_fn) <- preprocess dflags src_fn
1383 buf <- hGetStringBuffer hspp_fn
1384 return (dflags', hspp_fn, buf)
1386 preprocessFile dflags src_fn (Just (buf, time))
1388 -- case we bypass the preprocessing stage?
1390 local_opts = getOptionsFromStringBuffer buf
1392 (dflags', errs) <- parseDynamicFlags dflags local_opts
1396 | Unlit _ <- startPhase src_fn = True
1397 -- note: local_opts is only required if there's no Unlit phase
1398 | dopt Opt_Cpp dflags' = True
1399 | dopt Opt_Pp dflags' = True
1402 when needs_preprocessing $
1403 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1405 return (dflags', src_fn, buf)
1408 -----------------------------------------------------------------------------
1410 -----------------------------------------------------------------------------
1412 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1413 -- ToDo: we don't have a proper line number for this error
1414 noModError dflags cur_mod wanted_mod err
1415 = throwDyn $ ProgramError $ showSDoc $
1416 vcat [cantFindError dflags wanted_mod err,
1417 nest 2 (parens (pp_where cur_mod))]
1419 noHsFileErr cur_mod path
1420 = throwDyn $ CmdLineError $ showSDoc $
1421 vcat [text "Can't find" <+> text path,
1422 nest 2 (parens (pp_where cur_mod))]
1424 pp_where Nothing = text "one of the roots of the dependency analysis"
1425 pp_where (Just p) = text "imported from" <+> text p
1428 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1429 quotes (ppr mod) <+>
1430 text "is a package module")))
1432 multiRootsErr mod files
1433 = throwDyn (ProgramError (showSDoc (
1434 text "module" <+> quotes (ppr mod) <+>
1435 text "is defined in multiple files:" <+>
1436 sep (map text files))))
1438 cyclicModuleErr :: [ModSummary] -> SDoc
1440 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1441 2 (vcat (map show_one ms))
1443 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1444 nest 2 $ ptext SLIT("imports:") <+>
1445 (pp_imps HsBootFile (ms_srcimps ms)
1446 $$ pp_imps HsSrcFile (ms_imps ms))]
1447 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1448 pp_imps src mods = fsep (map (show_mod src) mods)
1451 -- | Inform GHC that the working directory has changed. GHC will flush
1452 -- its cache of module locations, since it may no longer be valid.
1453 -- Note: if you change the working directory, you should also unload
1454 -- the current program (set targets to empty, followed by load).
1455 workingDirectoryChanged :: Session -> IO ()
1456 workingDirectoryChanged s = withSession s $ \hsc_env ->
1457 flushFinderCache (hsc_FC hsc_env)
1459 -- -----------------------------------------------------------------------------
1460 -- inspecting the session
1462 -- | Get the module dependency graph.
1463 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1464 getModuleGraph s = withSession s (return . hsc_mod_graph)
1466 isLoaded :: Session -> Module -> IO Bool
1467 isLoaded s m = withSession s $ \hsc_env ->
1468 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1470 getBindings :: Session -> IO [TyThing]
1471 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1473 getPrintUnqual :: Session -> IO PrintUnqualified
1474 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1477 -- | Parses a string as an identifier, and returns the list of 'Name's that
1478 -- the identifier can refer to in the current interactive context.
1479 parseName :: Session -> String -> IO [Name]
1480 parseName s str = withSession s $ \hsc_env -> do
1481 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1482 case maybe_rdr_name of
1483 Nothing -> return []
1484 Just (L _ rdr_name) -> do
1485 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1487 Nothing -> return []
1488 Just ns -> return ns
1489 -- ToDo: should return error messages
1492 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1493 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1494 lookupName :: Session -> Name -> IO (Maybe TyThing)
1495 lookupName s name = withSession s $ \hsc_env -> do
1496 case lookupTypeEnv (ic_type_env (hsc_IC hsc_env)) name of
1497 Just tt -> return (Just tt)
1499 eps <- readIORef (hsc_EPS hsc_env)
1500 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1502 -- | Container for information about a 'Module'.
1503 data ModuleInfo = ModuleInfo {
1504 minf_details :: ModDetails,
1505 minf_rdr_env :: Maybe GlobalRdrEnv
1507 -- ToDo: this should really contain the ModIface too
1508 -- We don't want HomeModInfo here, because a ModuleInfo applies
1509 -- to package modules too.
1511 -- | Request information about a loaded 'Module'
1512 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1513 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1514 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1515 Nothing -> return Nothing
1517 return (Just (ModuleInfo {
1518 minf_details = hm_details hmi,
1519 minf_rdr_env = mi_globals $! hm_iface hmi
1522 -- ToDo: we should be able to call getModuleInfo on a package module,
1523 -- even one that isn't loaded yet.
1525 -- | The list of top-level entities defined in a module
1526 modInfoTyThings :: ModuleInfo -> [TyThing]
1527 modInfoTyThings minf = typeEnvElts (md_types (minf_details minf))
1529 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1530 modInfoTopLevelScope minf
1531 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1533 modInfoExports :: ModuleInfo -> [Name]
1534 modInfoExports minf = nameSetToList $! (md_exports $! minf_details minf)
1536 isDictonaryId :: Id -> Bool
1538 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1544 | BinaryCode FilePath
1546 type TypecheckedCode = HsTypecheckedGroup
1547 type RenamedCode = [HsGroup Name]
1549 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1550 -- - typechecked syntax includes extra dictionary translation and
1551 -- AbsBinds which need to be translated back into something closer to
1552 -- the original source.
1553 -- - renamed syntax currently doesn't exist in a single blob, since
1554 -- renaming and typechecking are interleaved at splice points. We'd
1555 -- need a restriction that there are no splices in the source module.
1558 -- - Data and Typeable instances for HsSyn.
1561 -- - things that aren't in the output of the renamer:
1562 -- - the export list
1566 -- - things that aren't in the output of the typechecker right now:
1567 -- - the export list
1569 -- - type signatures
1570 -- - type/data/newtype declarations
1571 -- - class declarations
1573 -- - extra things in the typechecker's output:
1574 -- - default methods are turned into top-level decls.
1575 -- - dictionary bindings
1577 -- ToDo: check for small transformations that happen to the syntax in
1578 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1580 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1581 -- to get from TyCons, Ids etc. to TH syntax (reify).
1583 -- :browse will use either lm_toplev or inspect lm_interface, depending
1584 -- on whether the module is interpreted or not.
1586 -- various abstract syntax types (perhaps IfaceBlah)
1590 -- This is for reconstructing refactored source code
1591 -- Calls the lexer repeatedly.
1592 -- ToDo: add comment tokens to token stream
1593 getTokenStream :: Session -> Module -> IO [Located Token]
1596 -- -----------------------------------------------------------------------------
1597 -- Interactive evaluation
1601 -- | Set the interactive evaluation context.
1603 -- Setting the context doesn't throw away any bindings; the bindings
1604 -- we've built up in the InteractiveContext simply move to the new
1605 -- module. They always shadow anything in scope in the current context.
1606 setContext :: Session
1607 -> [Module] -- entire top level scope of these modules
1608 -> [Module] -- exports only of these modules
1610 setContext (Session ref) toplevs exports = do
1611 hsc_env <- readIORef ref
1612 let old_ic = hsc_IC hsc_env
1613 hpt = hsc_HPT hsc_env
1615 mapM_ (checkModuleExists hsc_env hpt) exports
1616 export_env <- mkExportEnv hsc_env exports
1617 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1618 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1619 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1620 ic_exports = exports,
1621 ic_rn_gbl_env = all_env } }
1623 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1624 checkModuleExists hsc_env hpt mod =
1625 case lookupModuleEnv hpt mod of
1626 Just mod_info -> return ()
1627 _not_a_home_module -> do
1628 res <- findPackageModule hsc_env mod True
1630 Found _ _ -> return ()
1631 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1632 throwDyn (CmdLineError (showSDoc msg))
1634 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1635 mkTopLevEnv hpt modl
1636 = case lookupModuleEnv hpt modl of
1638 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1639 ++ showSDoc (pprModule modl)))
1641 case mi_globals (hm_iface details) of
1643 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1644 ++ showSDoc (pprModule modl)))
1645 Just env -> return env
1647 -- | Get the interactive evaluation context, consisting of a pair of the
1648 -- set of modules from which we take the full top-level scope, and the set
1649 -- of modules from which we take just the exports respectively.
1650 getContext :: Session -> IO ([Module],[Module])
1651 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1652 return (ic_toplev_scope ic, ic_exports ic))
1654 -- | Returns 'True' if the specified module is interpreted, and hence has
1655 -- its full top-level scope available.
1656 moduleIsInterpreted :: Session -> Module -> IO Bool
1657 moduleIsInterpreted s modl = withSession s $ \h ->
1658 case lookupModuleEnv (hsc_HPT h) modl of
1659 Just details -> return (isJust (mi_globals (hm_iface details)))
1660 _not_a_home_module -> return False
1662 -- | Looks up an identifier in the current interactive context (for :info)
1663 {-# DEPRECATED getInfo "we should be using parseName/lookupName instead" #-}
1664 getInfo :: Session -> String -> IO [GetInfoResult]
1665 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1667 -- | Returns all names in scope in the current interactive context
1668 getNamesInScope :: Session -> IO [Name]
1669 getNamesInScope s = withSession s $ \hsc_env -> do
1670 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1672 -- -----------------------------------------------------------------------------
1673 -- Getting the type of an expression
1675 -- | Get the type of an expression
1676 exprType :: Session -> String -> IO (Maybe Type)
1677 exprType s expr = withSession s $ \hsc_env -> do
1678 maybe_stuff <- hscTcExpr hsc_env expr
1680 Nothing -> return Nothing
1681 Just ty -> return (Just tidy_ty)
1683 tidy_ty = tidyType emptyTidyEnv ty
1684 dflags = hsc_dflags hsc_env
1686 -- -----------------------------------------------------------------------------
1687 -- Getting the kind of a type
1689 -- | Get the kind of a type
1690 typeKind :: Session -> String -> IO (Maybe Kind)
1691 typeKind s str = withSession s $ \hsc_env -> do
1692 maybe_stuff <- hscKcType hsc_env str
1694 Nothing -> return Nothing
1695 Just kind -> return (Just kind)
1697 -----------------------------------------------------------------------------
1698 -- cmCompileExpr: compile an expression and deliver an HValue
1700 compileExpr :: Session -> String -> IO (Maybe HValue)
1701 compileExpr s expr = withSession s $ \hsc_env -> do
1702 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1704 Nothing -> return Nothing
1705 Just (new_ic, names, hval) -> do
1707 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1709 case (names,hvals) of
1710 ([n],[hv]) -> return (Just hv)
1711 _ -> panic "compileExpr"
1713 -- -----------------------------------------------------------------------------
1714 -- running a statement interactively
1717 = RunOk [Name] -- ^ names bound by this evaluation
1718 | RunFailed -- ^ statement failed compilation
1719 | RunException Exception -- ^ statement raised an exception
1721 -- | Run a statement in the current interactive context. Statemenet
1722 -- may bind multple values.
1723 runStmt :: Session -> String -> IO RunResult
1724 runStmt (Session ref) expr
1726 hsc_env <- readIORef ref
1728 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1729 -- warnings about the implicit bindings we introduce.
1730 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1731 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1733 maybe_stuff <- hscStmt hsc_env' expr
1736 Nothing -> return RunFailed
1737 Just (new_hsc_env, names, hval) -> do
1739 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1740 either_hvals <- sandboxIO thing_to_run
1742 case either_hvals of
1744 -- on error, keep the *old* interactive context,
1745 -- so that 'it' is not bound to something
1746 -- that doesn't exist.
1747 return (RunException e)
1750 -- Get the newly bound things, and bind them.
1751 -- Don't need to delete any shadowed bindings;
1752 -- the new ones override the old ones.
1753 extendLinkEnv (zip names hvals)
1755 writeIORef ref new_hsc_env
1756 return (RunOk names)
1759 -- We run the statement in a "sandbox" to protect the rest of the
1760 -- system from anything the expression might do. For now, this
1761 -- consists of just wrapping it in an exception handler, but see below
1762 -- for another version.
1764 sandboxIO :: IO a -> IO (Either Exception a)
1765 sandboxIO thing = Exception.try thing
1768 -- This version of sandboxIO runs the expression in a completely new
1769 -- RTS main thread. It is disabled for now because ^C exceptions
1770 -- won't be delivered to the new thread, instead they'll be delivered
1771 -- to the (blocked) GHCi main thread.
1773 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1775 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1776 sandboxIO thing = do
1777 st_thing <- newStablePtr (Exception.try thing)
1778 alloca $ \ p_st_result -> do
1779 stat <- rts_evalStableIO st_thing p_st_result
1780 freeStablePtr st_thing
1782 then do st_result <- peek p_st_result
1783 result <- deRefStablePtr st_result
1784 freeStablePtr st_result
1785 return (Right result)
1787 return (Left (fromIntegral stat))
1789 foreign import "rts_evalStableIO" {- safe -}
1790 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1791 -- more informative than the C type!
1794 -- ---------------------------------------------------------------------------
1795 -- cmBrowseModule: get all the TyThings defined in a module
1797 {-# DEPRECATED browseModule "we should be using getModuleInfo instead" #-}
1798 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1799 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1800 mb_decls <- getModuleContents hsc_env modl exports_only
1802 Nothing -> return [] -- An error of some kind
1803 Just ds -> return ds
1806 -----------------------------------------------------------------------------
1807 -- show a module and it's source/object filenames
1809 showModule :: Session -> ModSummary -> IO String
1810 showModule s mod_summary = withSession s $ \hsc_env -> do
1811 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1812 Nothing -> panic "missing linkable"
1813 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1815 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))