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,
60 PrintUnqualified, alwaysQualify,
62 -- * Interactive evaluation
63 getBindings, getPrintUnqual,
65 setContext, getContext,
79 -- * Abstract syntax elements
82 Module, mkModule, pprModule,
86 nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
91 isImplicitId, isDeadBinder,
92 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
94 isPrimOpId, isFCallId, isClassOpId_maybe,
95 isDataConWorkId, idDataCon,
96 isBottomingId, isDictonaryId,
97 recordSelectorFieldLabel,
99 -- ** Type constructors
101 tyConTyVars, tyConDataCons,
102 isClassTyCon, isSynTyCon, isNewTyCon,
105 -- ** Data constructors
107 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
108 dataConIsInfix, isVanillaDataCon,
110 StrictnessMark(..), isMarkedStrict,
114 classMethods, classSCTheta, classTvsFds,
119 instanceDFunId, pprInstance,
121 -- ** Types and Kinds
122 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
125 ThetaType, pprThetaArrow,
131 module HsSyn, -- ToDo: remove extraneous bits
135 defaultFixity, maxPrecedence,
139 -- ** Source locations
143 GhcException(..), showGhcException,
153 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
154 * we need to expose DynFlags, so should parseDynamicFlags really be
155 part of this interface?
156 * what StaticFlags should we expose, if any?
159 #include "HsVersions.h"
162 import qualified Linker
163 import Linker ( HValue, extendLinkEnv )
164 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
165 tcRnLookupName, getModuleExports )
166 import RdrName ( plusGlobalRdrEnv, Provenance(..),
167 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
168 emptyGlobalRdrEnv, mkGlobalRdrEnv )
169 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
170 import Type ( tidyType )
171 import VarEnv ( emptyTidyEnv )
172 import GHC.Exts ( unsafeCoerce# )
175 import Packages ( initPackages, isHomeModule )
176 import NameSet ( NameSet, nameSetToList, elemNameSet )
177 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName,
180 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
181 pprThetaArrow, pprParendType, splitForAllTys,
183 import Id ( Id, idType, isImplicitId, isDeadBinder,
184 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
185 isRecordSelector, recordSelectorFieldLabel,
186 isPrimOpId, isFCallId, isClassOpId_maybe,
187 isDataConWorkId, idDataCon,
189 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
190 tyConTyVars, tyConDataCons, getSynTyConDefn )
191 import Class ( Class, classSCTheta, classTvsFds, classMethods )
192 import FunDeps ( pprFundeps )
193 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
194 dataConFieldLabels, dataConStrictMarks,
195 dataConIsInfix, isVanillaDataCon )
196 import Name ( Name, nameModule, NamedThing(..), nameParent_maybe,
198 import OccName ( parenSymOcc )
199 import NameEnv ( nameEnvElts )
200 import InstEnv ( Instance, instanceDFunId, pprInstance )
202 import DriverPipeline
203 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
204 import GetImports ( getImports )
205 import Packages ( isHomePackage )
207 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
211 import SysTools ( initSysTools, cleanTempFiles )
216 import Bag ( unitBag, emptyBag )
217 import ErrUtils ( showPass, Messages, putMsg, debugTraceMsg,
218 mkPlainErrMsg, pprBagOfErrors )
219 import qualified ErrUtils
221 import StringBuffer ( StringBuffer, hGetStringBuffer )
223 import SysTools ( cleanTempFilesExcept )
225 import TcType ( tcSplitSigmaTy, isDictTy )
226 import FastString ( mkFastString )
228 import Directory ( getModificationTime, doesFileExist )
229 import Maybe ( isJust, isNothing, fromJust )
230 import Maybes ( orElse, expectJust, mapCatMaybes )
231 import List ( partition, nub )
232 import qualified List
233 import Monad ( unless, when )
234 import System ( exitWith, ExitCode(..) )
235 import Time ( ClockTime )
236 import EXCEPTION as Exception hiding (handle)
239 import Prelude hiding (init)
241 -- -----------------------------------------------------------------------------
242 -- Exception handlers
244 -- | Install some default exception handlers and run the inner computation.
245 -- Unless you want to handle exceptions yourself, you should wrap this around
246 -- the top level of your program. The default handlers output the error
247 -- message(s) to stderr and exit cleanly.
248 defaultErrorHandler :: IO a -> IO a
249 defaultErrorHandler inner =
250 -- top-level exception handler: any unrecognised exception is a compiler bug.
251 handle (\exception -> do
254 -- an IO exception probably isn't our fault, so don't panic
255 IOException _ -> putMsg (show exception)
256 AsyncException StackOverflow ->
257 putMsg "stack overflow: use +RTS -K<size> to increase it"
258 _other -> putMsg (show (Panic (show exception)))
259 exitWith (ExitFailure 1)
262 -- program errors: messages with locations attached. Sometimes it is
263 -- convenient to just throw these as exceptions.
264 handleDyn (\dyn -> do printErrs (pprBagOfErrors (unitBag dyn))
265 exitWith (ExitFailure 1)) $
267 -- error messages propagated as exceptions
268 handleDyn (\dyn -> do
271 PhaseFailed _ code -> exitWith code
272 Interrupted -> exitWith (ExitFailure 1)
273 _ -> do putMsg (show (dyn :: GhcException))
274 exitWith (ExitFailure 1)
278 -- | Install a default cleanup handler to remove temporary files
279 -- deposited by a GHC run. This is seperate from
280 -- 'defaultErrorHandler', because you might want to override the error
281 -- handling, but still get the ordinary cleanup behaviour.
282 defaultCleanupHandler :: DynFlags -> IO a -> IO a
283 defaultCleanupHandler dflags inner =
284 -- make sure we clean up after ourselves
285 later (unless (dopt Opt_KeepTmpFiles dflags) $
286 cleanTempFiles dflags)
287 -- exceptions will be blocked while we clean the temporary files,
288 -- so there shouldn't be any difficulty if we receive further
293 -- | Initialises GHC. This must be done /once/ only. Takes the
294 -- command-line arguments. All command-line arguments which aren't
295 -- understood by GHC will be returned.
297 init :: [String] -> IO [String]
300 installSignalHandlers
302 -- Grab the -B option if there is one
303 let (minusB_args, argv1) = partition (prefixMatch "-B") args
304 dflags0 <- initSysTools minusB_args defaultDynFlags
305 writeIORef v_initDynFlags dflags0
307 -- Parse the static flags
308 argv2 <- parseStaticFlags argv1
311 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
312 -- stores the DynFlags between the call to init and subsequent
313 -- calls to newSession.
315 -- | Starts a new session. A session consists of a set of loaded
316 -- modules, a set of options (DynFlags), and an interactive context.
317 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
319 newSession :: GhcMode -> IO Session
321 dflags0 <- readIORef v_initDynFlags
322 dflags <- initDynFlags dflags0
323 env <- newHscEnv dflags{ ghcMode=mode }
327 -- tmp: this breaks the abstraction, but required because DriverMkDepend
328 -- needs to call the Finder. ToDo: untangle this.
329 sessionHscEnv :: Session -> IO HscEnv
330 sessionHscEnv (Session ref) = readIORef ref
332 withSession :: Session -> (HscEnv -> IO a) -> IO a
333 withSession (Session ref) f = do h <- readIORef ref; f h
335 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
336 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
338 -- -----------------------------------------------------------------------------
341 -- | Grabs the DynFlags from the Session
342 getSessionDynFlags :: Session -> IO DynFlags
343 getSessionDynFlags s = withSession s (return . hsc_dflags)
345 -- | Updates the DynFlags in a Session
346 setSessionDynFlags :: Session -> DynFlags -> IO ()
347 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
349 -- | Messages during compilation (eg. warnings and progress messages)
350 -- are reported using this callback. By default, these messages are
351 -- printed to stderr.
352 setMsgHandler :: (String -> IO ()) -> IO ()
353 setMsgHandler = ErrUtils.setMsgHandler
355 -- -----------------------------------------------------------------------------
358 -- ToDo: think about relative vs. absolute file paths. And what
359 -- happens when the current directory changes.
361 -- | Sets the targets for this session. Each target may be a module name
362 -- or a filename. The targets correspond to the set of root modules for
363 -- the program\/library. Unloading the current program is achieved by
364 -- setting the current set of targets to be empty, followed by load.
365 setTargets :: Session -> [Target] -> IO ()
366 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
368 -- | returns the current set of targets
369 getTargets :: Session -> IO [Target]
370 getTargets s = withSession s (return . hsc_targets)
372 -- | Add another target
373 addTarget :: Session -> Target -> IO ()
375 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
378 removeTarget :: Session -> TargetId -> IO ()
379 removeTarget s target_id
380 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
382 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
384 -- Attempts to guess what Target a string refers to. This function implements
385 -- the --make/GHCi command-line syntax for filenames:
387 -- - if the string looks like a Haskell source filename, then interpret
389 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
391 -- - otherwise interpret the string as a module name
393 guessTarget :: String -> Maybe Phase -> IO Target
394 guessTarget file (Just phase)
395 = return (Target (TargetFile file (Just phase)) Nothing)
396 guessTarget file Nothing
397 | isHaskellSrcFilename file
398 = return (Target (TargetFile file Nothing) Nothing)
400 = do exists <- doesFileExist hs_file
402 then return (Target (TargetFile hs_file Nothing) Nothing)
404 exists <- doesFileExist lhs_file
406 then return (Target (TargetFile lhs_file Nothing) Nothing)
408 return (Target (TargetModule (mkModule file)) Nothing)
410 hs_file = file `joinFileExt` "hs"
411 lhs_file = file `joinFileExt` "lhs"
413 -- -----------------------------------------------------------------------------
414 -- Loading the program
416 -- Perform a dependency analysis starting from the current targets
417 -- and update the session with the new module graph.
418 depanal :: Session -> [Module] -> IO (Either Messages ModuleGraph)
419 depanal (Session ref) excluded_mods = do
420 hsc_env <- readIORef ref
422 dflags = hsc_dflags hsc_env
423 gmode = ghcMode (hsc_dflags hsc_env)
424 targets = hsc_targets hsc_env
425 old_graph = hsc_mod_graph hsc_env
427 showPass dflags "Chasing dependencies"
428 when (gmode == BatchCompile) $
429 debugTraceMsg dflags 1 (showSDoc (hcat [
430 text "Chasing modules from: ",
431 hcat (punctuate comma (map pprTarget targets))]))
433 r <- downsweep hsc_env old_graph excluded_mods
435 Right mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
440 -- | The result of load.
442 = LoadOk Errors -- ^ all specified targets were loaded successfully.
443 | LoadFailed Errors -- ^ not all modules were loaded.
445 type Errors = [String]
447 data ErrMsg = ErrMsg {
448 errMsgSeverity :: Severity, -- warning, error, etc.
449 errMsgSpans :: [SrcSpan],
450 errMsgShortDoc :: Doc,
451 errMsgExtraInfo :: Doc
458 | LoadDependenciesOf Module
460 -- | Try to load the program. If a Module is supplied, then just
461 -- attempt to load up to this target. If no Module is supplied,
462 -- then try to load all targets.
463 load :: Session -> LoadHowMuch -> IO SuccessFlag
464 load session how_much =
465 loadMsgs session how_much ErrUtils.printErrorsAndWarnings
467 -- | Version of 'load' that takes a callback function to be invoked
468 -- on compiler errors and warnings as they occur during compilation.
469 loadMsgs :: Session -> LoadHowMuch -> (Messages-> IO ()) -> IO SuccessFlag
470 loadMsgs s@(Session ref) how_much msg_act
472 -- Dependency analysis first. Note that this fixes the module graph:
473 -- even if we don't get a fully successful upsweep, the full module
474 -- graph is still retained in the Session. We can tell which modules
475 -- were successfully loaded by inspecting the Session's HPT.
476 mb_graph <- depanal s []
478 Left msgs -> do msg_act msgs; return Failed
479 Right mod_graph -> loadMsgs2 s how_much msg_act mod_graph
481 loadMsgs2 s@(Session ref) how_much msg_act mod_graph = do
482 hsc_env <- readIORef ref
484 let hpt1 = hsc_HPT hsc_env
485 let dflags = hsc_dflags hsc_env
486 let ghci_mode = ghcMode dflags -- this never changes
488 -- The "bad" boot modules are the ones for which we have
489 -- B.hs-boot in the module graph, but no B.hs
490 -- The downsweep should have ensured this does not happen
492 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
494 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
495 not (ms_mod s `elem` all_home_mods)]
497 ASSERT( null bad_boot_mods ) return ()
499 -- mg2_with_srcimps drops the hi-boot nodes, returning a
500 -- graph with cycles. Among other things, it is used for
501 -- backing out partially complete cycles following a failed
502 -- upsweep, and for removing from hpt all the modules
503 -- not in strict downwards closure, during calls to compile.
504 let mg2_with_srcimps :: [SCC ModSummary]
505 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
507 -- check the stability property for each module.
508 stable_mods@(stable_obj,stable_bco)
509 | BatchCompile <- ghci_mode = ([],[])
510 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
512 -- prune bits of the HPT which are definitely redundant now,
514 pruned_hpt = pruneHomePackageTable hpt1
515 (flattenSCCs mg2_with_srcimps)
520 debugTraceMsg dflags 2 (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
521 text "Stable BCO:" <+> ppr stable_bco))
523 -- Unload any modules which are going to be re-linked this time around.
524 let stable_linkables = [ linkable
525 | m <- stable_obj++stable_bco,
526 Just hmi <- [lookupModuleEnv pruned_hpt m],
527 Just linkable <- [hm_linkable hmi] ]
528 unload hsc_env stable_linkables
530 -- We could at this point detect cycles which aren't broken by
531 -- a source-import, and complain immediately, but it seems better
532 -- to let upsweep_mods do this, so at least some useful work gets
533 -- done before the upsweep is abandoned.
534 --hPutStrLn stderr "after tsort:\n"
535 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
537 -- Now do the upsweep, calling compile for each module in
538 -- turn. Final result is version 3 of everything.
540 -- Topologically sort the module graph, this time including hi-boot
541 -- nodes, and possibly just including the portion of the graph
542 -- reachable from the module specified in the 2nd argument to load.
543 -- This graph should be cycle-free.
544 -- If we're restricting the upsweep to a portion of the graph, we
545 -- also want to retain everything that is still stable.
546 let full_mg :: [SCC ModSummary]
547 full_mg = topSortModuleGraph False mod_graph Nothing
549 maybe_top_mod = case how_much of
551 LoadDependenciesOf m -> Just m
554 partial_mg0 :: [SCC ModSummary]
555 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
557 -- LoadDependenciesOf m: we want the upsweep to stop just
558 -- short of the specified module (unless the specified module
561 | LoadDependenciesOf mod <- how_much
562 = ASSERT( case last partial_mg0 of
563 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
564 List.init partial_mg0
570 | AcyclicSCC ms <- full_mg,
571 ms_mod ms `elem` stable_obj++stable_bco,
572 ms_mod ms `notElem` [ ms_mod ms' |
573 AcyclicSCC ms' <- partial_mg ] ]
575 mg = stable_mg ++ partial_mg
577 -- clean up between compilations
578 let cleanup = cleanTempFilesExcept dflags
579 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
581 (upsweep_ok, hsc_env1, modsUpswept)
582 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
583 pruned_hpt stable_mods cleanup msg_act mg
585 -- Make modsDone be the summaries for each home module now
586 -- available; this should equal the domain of hpt3.
587 -- Get in in a roughly top .. bottom order (hence reverse).
589 let modsDone = reverse modsUpswept
591 -- Try and do linking in some form, depending on whether the
592 -- upsweep was completely or only partially successful.
594 if succeeded upsweep_ok
597 -- Easy; just relink it all.
598 do debugTraceMsg dflags 2 "Upsweep completely successful."
600 -- Clean up after ourselves
601 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
603 -- Issue a warning for the confusing case where the user
604 -- said '-o foo' but we're not going to do any linking.
605 -- We attempt linking if either (a) one of the modules is
606 -- called Main, or (b) the user said -no-hs-main, indicating
607 -- that main() is going to come from somewhere else.
609 let ofile = outputFile dflags
610 let no_hs_main = dopt Opt_NoHsMain dflags
611 let mb_main_mod = mainModIs dflags
613 main_mod = mb_main_mod `orElse` "Main"
615 = any ((==main_mod).moduleUserString.ms_mod)
617 do_linking = a_root_is_Main || no_hs_main
619 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
620 debugTraceMsg dflags 1 ("Warning: output was redirected with -o, " ++
621 "but no output will be generated\n" ++
622 "because there is no " ++ main_mod ++ " module.")
624 -- link everything together
625 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
627 loadFinish Succeeded linkresult ref hsc_env1
630 -- Tricky. We need to back out the effects of compiling any
631 -- half-done cycles, both so as to clean up the top level envs
632 -- and to avoid telling the interactive linker to link them.
633 do debugTraceMsg dflags 2 "Upsweep partially successful."
636 = map ms_mod modsDone
637 let mods_to_zap_names
638 = findPartiallyCompletedCycles modsDone_names
641 = filter ((`notElem` mods_to_zap_names).ms_mod)
644 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
647 -- Clean up after ourselves
648 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
650 -- there should be no Nothings where linkables should be, now
651 ASSERT(all (isJust.hm_linkable)
652 (moduleEnvElts (hsc_HPT hsc_env))) do
654 -- Link everything together
655 linkresult <- link ghci_mode dflags False hpt4
657 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
658 loadFinish Failed linkresult ref hsc_env4
660 -- Finish up after a load.
662 -- If the link failed, unload everything and return.
663 loadFinish all_ok Failed ref hsc_env
664 = do unload hsc_env []
665 writeIORef ref $! discardProg hsc_env
668 -- Empty the interactive context and set the module context to the topmost
669 -- newly loaded module, or the Prelude if none were loaded.
670 loadFinish all_ok Succeeded ref hsc_env
671 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
675 -- Forget the current program, but retain the persistent info in HscEnv
676 discardProg :: HscEnv -> HscEnv
678 = hsc_env { hsc_mod_graph = emptyMG,
679 hsc_IC = emptyInteractiveContext,
680 hsc_HPT = emptyHomePackageTable }
682 -- used to fish out the preprocess output files for the purposes of
683 -- cleaning up. The preprocessed file *might* be the same as the
684 -- source file, but that doesn't do any harm.
685 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
687 -- -----------------------------------------------------------------------------
691 CheckedModule { parsedSource :: ParsedSource,
692 renamedSource :: Maybe RenamedSource,
693 typecheckedSource :: Maybe TypecheckedSource,
694 checkedModuleInfo :: Maybe ModuleInfo
696 -- ToDo: improvements that could be made here:
697 -- if the module succeeded renaming but not typechecking,
698 -- we can still get back the GlobalRdrEnv and exports, so
699 -- perhaps the ModuleInfo should be split up into separate
700 -- fields within CheckedModule.
702 type ParsedSource = Located (HsModule RdrName)
703 type RenamedSource = HsGroup Name
704 type TypecheckedSource = LHsBinds Id
707 -- - things that aren't in the output of the renamer:
710 -- - things that aren't in the output of the typechecker right now:
714 -- - type/data/newtype declarations
715 -- - class declarations
717 -- - extra things in the typechecker's output:
718 -- - default methods are turned into top-level decls.
719 -- - dictionary bindings
722 -- | This is the way to get access to parsed and typechecked source code
723 -- for a module. 'checkModule' loads all the dependencies of the specified
724 -- module in the Session, and then attempts to typecheck the module. If
725 -- successful, it returns the abstract syntax for the module.
726 checkModule :: Session -> Module -> (Messages -> IO ())
727 -> IO (Maybe CheckedModule)
728 checkModule session@(Session ref) mod msg_act = do
729 -- load up the dependencies first
730 r <- loadMsgs session (LoadDependenciesOf mod) msg_act
731 if (failed r) then return Nothing else do
733 -- now parse & typecheck the module
734 hsc_env <- readIORef ref
735 let mg = hsc_mod_graph hsc_env
736 case [ ms | ms <- mg, ms_mod ms == mod ] of
739 -- Add in the OPTIONS from the source file This is nasty:
740 -- we've done this once already, in the compilation manager
741 -- It might be better to cache the flags in the
742 -- ml_hspp_file field, say
743 let dflags0 = hsc_dflags hsc_env
744 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
745 opts = getOptionsFromStringBuffer hspp_buf
746 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
747 if (not (null leftovers))
748 then do let filename = fromJust (ml_hs_file (ms_location ms))
749 msg_act (optionsErrorMsgs leftovers opts filename)
753 r <- hscFileCheck hsc_env{hsc_dflags=dflags1} msg_act ms
757 HscChecked parsed renamed Nothing ->
758 return (Just (CheckedModule {
759 parsedSource = parsed,
760 renamedSource = renamed,
761 typecheckedSource = Nothing,
762 checkedModuleInfo = Nothing }))
763 HscChecked parsed renamed
764 (Just (tc_binds, rdr_env, details)) -> do
765 let minf = ModuleInfo {
766 minf_type_env = md_types details,
767 minf_exports = md_exports details,
768 minf_rdr_env = Just rdr_env,
769 minf_instances = md_insts details
771 return (Just (CheckedModule {
772 parsedSource = parsed,
773 renamedSource = renamed,
774 typecheckedSource = Just tc_binds,
775 checkedModuleInfo = Just minf }))
779 -- ---------------------------------------------------------------------------
782 unload :: HscEnv -> [Linkable] -> IO ()
783 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
784 = case ghcMode (hsc_dflags hsc_env) of
785 BatchCompile -> return ()
786 JustTypecheck -> return ()
788 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
790 Interactive -> panic "unload: no interpreter"
792 other -> panic "unload: strange mode"
794 -- -----------------------------------------------------------------------------
798 Stability tells us which modules definitely do not need to be recompiled.
799 There are two main reasons for having stability:
801 - avoid doing a complete upsweep of the module graph in GHCi when
802 modules near the bottom of the tree have not changed.
804 - to tell GHCi when it can load object code: we can only load object code
805 for a module when we also load object code fo all of the imports of the
806 module. So we need to know that we will definitely not be recompiling
807 any of these modules, and we can use the object code.
809 NB. stability is of no importance to BatchCompile at all, only Interactive.
810 (ToDo: what about JustTypecheck?)
812 The stability check is as follows. Both stableObject and
813 stableBCO are used during the upsweep phase later.
816 stable m = stableObject m || stableBCO m
819 all stableObject (imports m)
820 && old linkable does not exist, or is == on-disk .o
821 && date(on-disk .o) > date(.hs)
824 all stable (imports m)
825 && date(BCO) > date(.hs)
828 These properties embody the following ideas:
830 - if a module is stable:
831 - if it has been compiled in a previous pass (present in HPT)
832 then it does not need to be compiled or re-linked.
833 - if it has not been compiled in a previous pass,
834 then we only need to read its .hi file from disk and
835 link it to produce a ModDetails.
837 - if a modules is not stable, we will definitely be at least
838 re-linking, and possibly re-compiling it during the upsweep.
839 All non-stable modules can (and should) therefore be unlinked
842 - Note that objects are only considered stable if they only depend
843 on other objects. We can't link object code against byte code.
847 :: HomePackageTable -- HPT from last compilation
848 -> [SCC ModSummary] -- current module graph (cyclic)
849 -> [Module] -- all home modules
850 -> ([Module], -- stableObject
851 [Module]) -- stableBCO
853 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
855 checkSCC (stable_obj, stable_bco) scc0
856 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
857 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
858 | otherwise = (stable_obj, stable_bco)
860 scc = flattenSCC scc0
861 scc_mods = map ms_mod scc
862 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
864 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
865 -- all imports outside the current SCC, but in the home pkg
867 stable_obj_imps = map (`elem` stable_obj) scc_allimps
868 stable_bco_imps = map (`elem` stable_bco) scc_allimps
875 and (zipWith (||) stable_obj_imps stable_bco_imps)
879 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
883 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
884 Just hmi | Just l <- hm_linkable hmi
885 -> isObjectLinkable l && t == linkableTime l
887 -- why '>=' rather than '>' above? If the filesystem stores
888 -- times to the nearset second, we may occasionally find that
889 -- the object & source have the same modification time,
890 -- especially if the source was automatically generated
891 -- and compiled. Using >= is slightly unsafe, but it matches
895 = case lookupModuleEnv hpt (ms_mod ms) of
896 Just hmi | Just l <- hm_linkable hmi ->
897 not (isObjectLinkable l) &&
898 linkableTime l >= ms_hs_date ms
901 ms_allimps :: ModSummary -> [Module]
902 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
904 -- -----------------------------------------------------------------------------
905 -- Prune the HomePackageTable
907 -- Before doing an upsweep, we can throw away:
909 -- - For non-stable modules:
910 -- - all ModDetails, all linked code
911 -- - all unlinked code that is out of date with respect to
914 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
915 -- space at the end of the upsweep, because the topmost ModDetails of the
916 -- old HPT holds on to the entire type environment from the previous
919 pruneHomePackageTable
922 -> ([Module],[Module])
925 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
926 = mapModuleEnv prune hpt
928 | is_stable modl = hmi'
929 | otherwise = hmi'{ hm_details = emptyModDetails }
931 modl = mi_module (hm_iface hmi)
932 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
933 = hmi{ hm_linkable = Nothing }
936 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
938 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
940 is_stable m = m `elem` stable_obj || m `elem` stable_bco
942 -- -----------------------------------------------------------------------------
944 -- Return (names of) all those in modsDone who are part of a cycle
945 -- as defined by theGraph.
946 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
947 findPartiallyCompletedCycles modsDone theGraph
951 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
952 chew ((CyclicSCC vs):rest)
953 = let names_in_this_cycle = nub (map ms_mod vs)
955 = nub ([done | done <- modsDone,
956 done `elem` names_in_this_cycle])
957 chewed_rest = chew rest
959 if notNull mods_in_this_cycle
960 && length mods_in_this_cycle < length names_in_this_cycle
961 then mods_in_this_cycle ++ chewed_rest
964 -- -----------------------------------------------------------------------------
967 -- This is where we compile each module in the module graph, in a pass
968 -- from the bottom to the top of the graph.
970 -- There better had not be any cyclic groups here -- we check for them.
973 :: HscEnv -- Includes initially-empty HPT
974 -> HomePackageTable -- HPT from last time round (pruned)
975 -> ([Module],[Module]) -- stable modules (see checkStability)
976 -> IO () -- How to clean up unwanted tmp files
977 -> (Messages -> IO ()) -- Compiler error message callback
978 -> [SCC ModSummary] -- Mods to do (the worklist)
980 HscEnv, -- With an updated HPT
981 [ModSummary]) -- Mods which succeeded
983 upsweep hsc_env old_hpt stable_mods cleanup msg_act mods
984 = upsweep' hsc_env old_hpt stable_mods cleanup msg_act mods 1 (length mods)
986 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
988 = return (Succeeded, hsc_env, [])
990 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
992 = do putMsg (showSDoc (cyclicModuleErr ms))
993 return (Failed, hsc_env, [])
995 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
996 (AcyclicSCC mod:mods) mod_index nmods
997 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
998 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
999 -- (moduleEnvElts (hsc_HPT hsc_env)))
1001 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods msg_act mod
1004 cleanup -- Remove unwanted tmp files between compilations
1007 Nothing -> return (Failed, hsc_env, [])
1009 { let this_mod = ms_mod mod
1011 -- Add new info to hsc_env
1012 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
1014 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1016 -- Space-saving: delete the old HPT entry
1017 -- for mod BUT if mod is a hs-boot
1018 -- node, don't delete it. For the
1019 -- interface, the HPT entry is probaby for the
1020 -- main Haskell source file. Deleting it
1021 -- would force .. (what?? --SDM)
1022 old_hpt1 | isBootSummary mod = old_hpt
1023 | otherwise = delModuleEnv old_hpt this_mod
1025 ; (restOK, hsc_env2, modOKs)
1026 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1027 msg_act mods (mod_index+1) nmods
1028 ; return (restOK, hsc_env2, mod:modOKs)
1032 -- Compile a single module. Always produce a Linkable for it if
1033 -- successful. If no compilation happened, return the old Linkable.
1034 upsweep_mod :: HscEnv
1036 -> ([Module],[Module])
1037 -> (Messages -> IO ())
1039 -> Int -- index of module
1040 -> Int -- total number of modules
1041 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1043 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) msg_act summary mod_index nmods
1046 this_mod = ms_mod summary
1047 mb_obj_date = ms_obj_date summary
1048 obj_fn = ml_obj_file (ms_location summary)
1049 hs_date = ms_hs_date summary
1051 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1052 compile_it = upsweep_compile hsc_env old_hpt this_mod
1053 msg_act summary mod_index nmods
1055 case ghcMode (hsc_dflags hsc_env) of
1058 -- Batch-compilating is easy: just check whether we have
1059 -- an up-to-date object file. If we do, then the compiler
1060 -- needs to do a recompilation check.
1061 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1063 findObjectLinkable this_mod obj_fn obj_date
1064 compile_it (Just linkable)
1071 _ | is_stable_obj, isJust old_hmi ->
1073 -- object is stable, and we have an entry in the
1074 -- old HPT: nothing to do
1076 | is_stable_obj, isNothing old_hmi -> do
1078 findObjectLinkable this_mod obj_fn
1079 (expectJust "upseep1" mb_obj_date)
1080 compile_it (Just linkable)
1081 -- object is stable, but we need to load the interface
1082 -- off disk to make a HMI.
1085 ASSERT(isJust old_hmi) -- must be in the old_hpt
1087 -- BCO is stable: nothing to do
1089 | Just hmi <- old_hmi,
1090 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1091 linkableTime l >= ms_hs_date summary ->
1093 -- we have an old BCO that is up to date with respect
1094 -- to the source: do a recompilation check as normal.
1098 -- no existing code at all: we must recompile.
1100 is_stable_obj = this_mod `elem` stable_obj
1101 is_stable_bco = this_mod `elem` stable_bco
1103 old_hmi = lookupModuleEnv old_hpt this_mod
1105 -- Run hsc to compile a module
1106 upsweep_compile hsc_env old_hpt this_mod msg_act summary
1108 mb_old_linkable = do
1110 -- The old interface is ok if it's in the old HPT
1111 -- a) we're compiling a source file, and the old HPT
1112 -- entry is for a source file
1113 -- b) we're compiling a hs-boot file
1114 -- Case (b) allows an hs-boot file to get the interface of its
1115 -- real source file on the second iteration of the compilation
1116 -- manager, but that does no harm. Otherwise the hs-boot file
1117 -- will always be recompiled
1120 = case lookupModuleEnv old_hpt this_mod of
1122 Just hm_info | isBootSummary summary -> Just iface
1123 | not (mi_boot iface) -> Just iface
1124 | otherwise -> Nothing
1126 iface = hm_iface hm_info
1128 compresult <- compile hsc_env msg_act summary mb_old_linkable mb_old_iface
1132 -- Compilation failed. Compile may still have updated the PCS, tho.
1133 CompErrs -> return Nothing
1135 -- Compilation "succeeded", and may or may not have returned a new
1136 -- linkable (depending on whether compilation was actually performed
1138 CompOK new_details new_iface new_linkable
1139 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1140 hm_details = new_details,
1141 hm_linkable = new_linkable }
1142 return (Just new_info)
1145 -- Filter modules in the HPT
1146 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1147 retainInTopLevelEnvs keep_these hpt
1148 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1150 , let mb_mod_info = lookupModuleEnv hpt mod
1151 , isJust mb_mod_info ]
1153 -- ---------------------------------------------------------------------------
1154 -- Topological sort of the module graph
1157 :: Bool -- Drop hi-boot nodes? (see below)
1161 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1162 -- The resulting list of strongly-connected-components is in topologically
1163 -- sorted order, starting with the module(s) at the bottom of the
1164 -- dependency graph (ie compile them first) and ending with the ones at
1167 -- Drop hi-boot nodes (first boolean arg)?
1169 -- False: treat the hi-boot summaries as nodes of the graph,
1170 -- so the graph must be acyclic
1172 -- True: eliminate the hi-boot nodes, and instead pretend
1173 -- the a source-import of Foo is an import of Foo
1174 -- The resulting graph has no hi-boot nodes, but can by cyclic
1176 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1177 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1178 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1179 = stronglyConnComp (map vertex_fn (reachable graph root))
1181 -- restrict the graph to just those modules reachable from
1182 -- the specified module. We do this by building a graph with
1183 -- the full set of nodes, and determining the reachable set from
1184 -- the specified node.
1185 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1186 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1188 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1189 | otherwise = throwDyn (ProgramError "module does not exist")
1191 moduleGraphNodes :: Bool -> [ModSummary]
1192 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1193 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1195 -- Drop hs-boot nodes by using HsSrcFile as the key
1196 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1197 | otherwise = HsBootFile
1199 -- We use integers as the keys for the SCC algorithm
1200 nodes :: [(ModSummary, Int, [Int])]
1201 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1202 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1203 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) )
1205 , not (isBootSummary s && drop_hs_boot_nodes) ]
1206 -- Drop the hi-boot ones if told to do so
1208 key_map :: NodeMap Int
1209 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1212 lookup_key :: HscSource -> Module -> Maybe Int
1213 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1215 out_edge_keys :: HscSource -> [Module] -> [Int]
1216 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1217 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1218 -- the IsBootInterface parameter True; else False
1221 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1222 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1224 msKey :: ModSummary -> NodeKey
1225 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1227 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1228 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1230 nodeMapElts :: NodeMap a -> [a]
1231 nodeMapElts = eltsFM
1233 -----------------------------------------------------------------------------
1234 -- Downsweep (dependency analysis)
1236 -- Chase downwards from the specified root set, returning summaries
1237 -- for all home modules encountered. Only follow source-import
1240 -- We pass in the previous collection of summaries, which is used as a
1241 -- cache to avoid recalculating a module summary if the source is
1244 -- The returned list of [ModSummary] nodes has one node for each home-package
1245 -- module, plus one for any hs-boot files. The imports of these nodes
1246 -- are all there, including the imports of non-home-package modules.
1249 -> [ModSummary] -- Old summaries
1250 -> [Module] -- Ignore dependencies on these; treat them as
1251 -- if they were package modules
1252 -> IO (Either Messages [ModSummary])
1253 downsweep hsc_env old_summaries excl_mods
1254 = -- catch error messages and return them
1255 handleDyn (\err_msg -> return (Left (emptyBag, unitBag err_msg))) $ do
1256 rootSummaries <- mapM getRootSummary roots
1257 checkDuplicates rootSummaries
1258 summs <- loop (concatMap msDeps rootSummaries) (mkNodeMap rootSummaries)
1259 return (Right summs)
1261 roots = hsc_targets hsc_env
1263 old_summary_map :: NodeMap ModSummary
1264 old_summary_map = mkNodeMap old_summaries
1266 getRootSummary :: Target -> IO ModSummary
1267 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1268 = do exists <- doesFileExist file
1270 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1271 else throwDyn $ mkPlainErrMsg noSrcSpan $
1272 text "can't find file:" <+> text file
1273 getRootSummary (Target (TargetModule modl) maybe_buf)
1274 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1275 (L rootLoc modl) maybe_buf excl_mods
1276 case maybe_summary of
1277 Nothing -> packageModErr modl
1280 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1282 -- In a root module, the filename is allowed to diverge from the module
1283 -- name, so we have to check that there aren't multiple root files
1284 -- defining the same module (otherwise the duplicates will be silently
1285 -- ignored, leading to confusing behaviour).
1286 checkDuplicates :: [ModSummary] -> IO ()
1287 checkDuplicates summaries = mapM_ check summaries
1292 many -> multiRootsErr modl many
1293 where modl = ms_mod summ
1295 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1296 | summ' <- summaries, ms_mod summ' == modl ]
1298 loop :: [(Located Module,IsBootInterface)]
1299 -- Work list: process these modules
1300 -> NodeMap ModSummary
1303 -- The result includes the worklist, except
1304 -- for those mentioned in the visited set
1305 loop [] done = return (nodeMapElts done)
1306 loop ((wanted_mod, is_boot) : ss) done
1307 | key `elemFM` done = loop ss done
1308 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1309 is_boot wanted_mod Nothing excl_mods
1311 Nothing -> loop ss done
1312 Just s -> loop (msDeps s ++ ss)
1313 (addToFM done key s) }
1315 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1317 msDeps :: ModSummary -> [(Located Module, IsBootInterface)]
1318 -- (msDeps s) returns the dependencies of the ModSummary s.
1319 -- A wrinkle is that for a {-# SOURCE #-} import we return
1320 -- *both* the hs-boot file
1321 -- *and* the source file
1322 -- as "dependencies". That ensures that the list of all relevant
1323 -- modules always contains B.hs if it contains B.hs-boot.
1324 -- Remember, this pass isn't doing the topological sort. It's
1325 -- just gathering the list of all relevant ModSummaries
1327 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1328 ++ [ (m,False) | m <- ms_imps s ]
1330 -----------------------------------------------------------------------------
1331 -- Summarising modules
1333 -- We have two types of summarisation:
1335 -- * Summarise a file. This is used for the root module(s) passed to
1336 -- cmLoadModules. The file is read, and used to determine the root
1337 -- module name. The module name may differ from the filename.
1339 -- * Summarise a module. We are given a module name, and must provide
1340 -- a summary. The finder is used to locate the file in which the module
1345 -> [ModSummary] -- old summaries
1346 -> FilePath -- source file name
1347 -> Maybe Phase -- start phase
1348 -> Maybe (StringBuffer,ClockTime)
1351 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1352 -- we can use a cached summary if one is available and the
1353 -- source file hasn't changed, But we have to look up the summary
1354 -- by source file, rather than module name as we do in summarise.
1355 | Just old_summary <- findSummaryBySourceFile old_summaries file
1357 let location = ms_location old_summary
1359 -- return the cached summary if the source didn't change
1360 src_timestamp <- case maybe_buf of
1361 Just (_,t) -> return t
1362 Nothing -> getModificationTime file
1364 if ms_hs_date old_summary == src_timestamp
1365 then do -- update the object-file timestamp
1366 obj_timestamp <- getObjTimestamp location False
1367 return old_summary{ ms_obj_date = obj_timestamp }
1375 let dflags = hsc_dflags hsc_env
1377 (dflags', hspp_fn, buf)
1378 <- preprocessFile dflags file mb_phase maybe_buf
1380 (srcimps,the_imps, L _ mod) <- getImports dflags' buf hspp_fn
1382 -- Make a ModLocation for this file
1383 location <- mkHomeModLocation dflags mod file
1385 -- Tell the Finder cache where it is, so that subsequent calls
1386 -- to findModule will find it, even if it's not on any search path
1387 addHomeModuleToFinder hsc_env mod location
1389 src_timestamp <- case maybe_buf of
1390 Just (_,t) -> return t
1391 Nothing -> getModificationTime file
1393 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1395 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1396 ms_location = location,
1397 ms_hspp_file = Just hspp_fn,
1398 ms_hspp_buf = Just buf,
1399 ms_srcimps = srcimps, ms_imps = the_imps,
1400 ms_hs_date = src_timestamp,
1401 ms_obj_date = obj_timestamp })
1403 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1404 findSummaryBySourceFile summaries file
1405 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1406 fromJust (ml_hs_file (ms_location ms)) == file ] of
1410 -- Summarise a module, and pick up source and timestamp.
1413 -> NodeMap ModSummary -- Map of old summaries
1414 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1415 -> Located Module -- Imported module to be summarised
1416 -> Maybe (StringBuffer, ClockTime)
1417 -> [Module] -- Modules to exclude
1418 -> IO (Maybe ModSummary) -- Its new summary
1420 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1421 | wanted_mod `elem` excl_mods
1424 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1425 = do -- Find its new timestamp; all the
1426 -- ModSummaries in the old map have valid ml_hs_files
1427 let location = ms_location old_summary
1428 src_fn = expectJust "summariseModule" (ml_hs_file location)
1430 -- return the cached summary if the source didn't change
1431 src_timestamp <- case maybe_buf of
1432 Just (_,t) -> return t
1433 Nothing -> getModificationTime src_fn
1435 if ms_hs_date old_summary == src_timestamp
1436 then do -- update the object-file timestamp
1437 obj_timestamp <- getObjTimestamp location is_boot
1438 return (Just old_summary{ ms_obj_date = obj_timestamp })
1440 -- source changed: re-summarise
1441 new_summary location src_fn maybe_buf src_timestamp
1444 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1447 | not (isHomePackage pkg) -> return Nothing
1448 -- Drop external-pkg
1449 | isJust (ml_hs_file location) -> just_found location
1451 err -> noModError dflags loc wanted_mod err
1454 dflags = hsc_dflags hsc_env
1456 hsc_src = if is_boot then HsBootFile else HsSrcFile
1458 just_found location = do
1459 -- Adjust location to point to the hs-boot source file,
1460 -- hi file, object file, when is_boot says so
1461 let location' | is_boot = addBootSuffixLocn location
1462 | otherwise = location
1463 src_fn = expectJust "summarise2" (ml_hs_file location')
1465 -- Check that it exists
1466 -- It might have been deleted since the Finder last found it
1467 maybe_t <- modificationTimeIfExists src_fn
1469 Nothing -> noHsFileErr loc src_fn
1470 Just t -> new_summary location' src_fn Nothing t
1473 new_summary location src_fn maybe_bug src_timestamp
1475 -- Preprocess the source file and get its imports
1476 -- The dflags' contains the OPTIONS pragmas
1477 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1478 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1480 when (mod_name /= wanted_mod) $
1481 throwDyn $ mkPlainErrMsg mod_loc $
1482 text "file name does not match module name"
1483 <+> quotes (ppr mod_name)
1485 -- Find the object timestamp, and return the summary
1486 obj_timestamp <- getObjTimestamp location is_boot
1488 return (Just ( ModSummary { ms_mod = wanted_mod,
1489 ms_hsc_src = hsc_src,
1490 ms_location = location,
1491 ms_hspp_file = Just hspp_fn,
1492 ms_hspp_buf = Just buf,
1493 ms_srcimps = srcimps,
1495 ms_hs_date = src_timestamp,
1496 ms_obj_date = obj_timestamp }))
1499 getObjTimestamp location is_boot
1500 = if is_boot then return Nothing
1501 else modificationTimeIfExists (ml_obj_file location)
1504 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1505 -> IO (DynFlags, FilePath, StringBuffer)
1506 preprocessFile dflags src_fn mb_phase Nothing
1508 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1509 buf <- hGetStringBuffer hspp_fn
1510 return (dflags', hspp_fn, buf)
1512 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1514 -- case we bypass the preprocessing stage?
1516 local_opts = getOptionsFromStringBuffer buf
1518 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1522 | Just (Unlit _) <- mb_phase = True
1523 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1524 -- note: local_opts is only required if there's no Unlit phase
1525 | dopt Opt_Cpp dflags' = True
1526 | dopt Opt_Pp dflags' = True
1529 when needs_preprocessing $
1530 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1532 return (dflags', src_fn, buf)
1535 -----------------------------------------------------------------------------
1537 -----------------------------------------------------------------------------
1539 noModError :: DynFlags -> SrcSpan -> Module -> FindResult -> IO ab
1540 -- ToDo: we don't have a proper line number for this error
1541 noModError dflags loc wanted_mod err
1542 = throwDyn $ mkPlainErrMsg loc $ cantFindError dflags wanted_mod err
1544 noHsFileErr loc path
1545 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1548 = throwDyn $ mkPlainErrMsg noSrcSpan $
1549 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1551 multiRootsErr mod files
1552 = throwDyn $ mkPlainErrMsg noSrcSpan $
1553 text "module" <+> quotes (ppr mod) <+>
1554 text "is defined in multiple files:" <+>
1555 sep (map text files)
1557 cyclicModuleErr :: [ModSummary] -> SDoc
1559 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1560 2 (vcat (map show_one ms))
1562 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1563 nest 2 $ ptext SLIT("imports:") <+>
1564 (pp_imps HsBootFile (ms_srcimps ms)
1565 $$ pp_imps HsSrcFile (ms_imps ms))]
1566 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1567 pp_imps src mods = fsep (map (show_mod src) mods)
1570 -- | Inform GHC that the working directory has changed. GHC will flush
1571 -- its cache of module locations, since it may no longer be valid.
1572 -- Note: if you change the working directory, you should also unload
1573 -- the current program (set targets to empty, followed by load).
1574 workingDirectoryChanged :: Session -> IO ()
1575 workingDirectoryChanged s = withSession s $ \hsc_env ->
1576 flushFinderCache (hsc_FC hsc_env)
1578 -- -----------------------------------------------------------------------------
1579 -- inspecting the session
1581 -- | Get the module dependency graph.
1582 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1583 getModuleGraph s = withSession s (return . hsc_mod_graph)
1585 isLoaded :: Session -> Module -> IO Bool
1586 isLoaded s m = withSession s $ \hsc_env ->
1587 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1589 getBindings :: Session -> IO [TyThing]
1590 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1592 getPrintUnqual :: Session -> IO PrintUnqualified
1593 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1595 -- | Container for information about a 'Module'.
1596 data ModuleInfo = ModuleInfo {
1597 minf_type_env :: TypeEnv,
1598 minf_exports :: NameSet,
1599 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1600 minf_instances :: [Instance]
1601 -- ToDo: this should really contain the ModIface too
1603 -- We don't want HomeModInfo here, because a ModuleInfo applies
1604 -- to package modules too.
1606 -- | Request information about a loaded 'Module'
1607 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1608 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1609 let mg = hsc_mod_graph hsc_env
1610 if mdl `elem` map ms_mod mg
1611 then getHomeModuleInfo hsc_env mdl
1613 if isHomeModule (hsc_dflags hsc_env) mdl
1615 else getPackageModuleInfo hsc_env mdl
1616 -- getPackageModuleInfo will attempt to find the interface, so
1617 -- we don't want to call it for a home module, just in case there
1618 -- was a problem loading the module and the interface doesn't
1619 -- exist... hence the isHomeModule test here.
1621 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1622 getPackageModuleInfo hsc_env mdl = do
1624 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1626 Nothing -> return Nothing
1628 eps <- readIORef (hsc_EPS hsc_env)
1631 n_list = nameSetToList names
1632 tys = [ ty | name <- n_list,
1633 Just ty <- [lookupTypeEnv pte name] ]
1635 return (Just (ModuleInfo {
1636 minf_type_env = mkTypeEnv tys,
1637 minf_exports = names,
1638 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names mdl,
1639 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1642 -- bogusly different for non-GHCI (ToDo)
1646 getHomeModuleInfo hsc_env mdl =
1647 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1648 Nothing -> return Nothing
1650 let details = hm_details hmi
1651 return (Just (ModuleInfo {
1652 minf_type_env = md_types details,
1653 minf_exports = md_exports details,
1654 minf_rdr_env = mi_globals $! hm_iface hmi,
1655 minf_instances = md_insts details
1658 -- | The list of top-level entities defined in a module
1659 modInfoTyThings :: ModuleInfo -> [TyThing]
1660 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1662 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1663 modInfoTopLevelScope minf
1664 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1666 modInfoExports :: ModuleInfo -> [Name]
1667 modInfoExports minf = nameSetToList $! minf_exports minf
1669 -- | Returns the instances defined by the specified module.
1670 -- Warning: currently unimplemented for package modules.
1671 modInfoInstances :: ModuleInfo -> [Instance]
1672 modInfoInstances = minf_instances
1674 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1675 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1677 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1678 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1680 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1681 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1682 case lookupTypeEnv (minf_type_env minf) name of
1683 Just tyThing -> return (Just tyThing)
1685 eps <- readIORef (hsc_EPS hsc_env)
1686 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1688 isDictonaryId :: Id -> Bool
1690 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1692 -- | Looks up a global name: that is, any top-level name in any
1693 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1694 -- the interactive context, and therefore does not require a preceding
1696 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1697 lookupGlobalName s name = withSession s $ \hsc_env -> do
1698 eps <- readIORef (hsc_EPS hsc_env)
1699 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1701 -- -----------------------------------------------------------------------------
1702 -- Misc exported utils
1704 dataConType :: DataCon -> Type
1705 dataConType dc = idType (dataConWrapId dc)
1707 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1708 pprParenSymName :: NamedThing a => a -> SDoc
1709 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1711 -- ----------------------------------------------------------------------------
1716 -- - Data and Typeable instances for HsSyn.
1718 -- ToDo: check for small transformations that happen to the syntax in
1719 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1721 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1722 -- to get from TyCons, Ids etc. to TH syntax (reify).
1724 -- :browse will use either lm_toplev or inspect lm_interface, depending
1725 -- on whether the module is interpreted or not.
1727 -- This is for reconstructing refactored source code
1728 -- Calls the lexer repeatedly.
1729 -- ToDo: add comment tokens to token stream
1730 getTokenStream :: Session -> Module -> IO [Located Token]
1733 -- -----------------------------------------------------------------------------
1734 -- Interactive evaluation
1738 -- | Set the interactive evaluation context.
1740 -- Setting the context doesn't throw away any bindings; the bindings
1741 -- we've built up in the InteractiveContext simply move to the new
1742 -- module. They always shadow anything in scope in the current context.
1743 setContext :: Session
1744 -> [Module] -- entire top level scope of these modules
1745 -> [Module] -- exports only of these modules
1747 setContext (Session ref) toplevs exports = do
1748 hsc_env <- readIORef ref
1749 let old_ic = hsc_IC hsc_env
1750 hpt = hsc_HPT hsc_env
1752 mapM_ (checkModuleExists hsc_env hpt) exports
1753 export_env <- mkExportEnv hsc_env exports
1754 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1755 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1756 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1757 ic_exports = exports,
1758 ic_rn_gbl_env = all_env } }
1760 -- Make a GlobalRdrEnv based on the exports of the modules only.
1761 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1762 mkExportEnv hsc_env mods = do
1763 stuff <- mapM (getModuleExports hsc_env) mods
1765 (_msgs, mb_name_sets) = unzip stuff
1766 gres = [ nameSetToGlobalRdrEnv name_set mod
1767 | (Just name_set, mod) <- zip mb_name_sets mods ]
1769 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1771 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1772 nameSetToGlobalRdrEnv names mod =
1773 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1774 | name <- nameSetToList names ]
1776 vanillaProv :: Module -> Provenance
1777 -- We're building a GlobalRdrEnv as if the user imported
1778 -- all the specified modules into the global interactive module
1779 vanillaProv mod = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1781 decl = ImpDeclSpec { is_mod = mod, is_as = mod,
1783 is_dloc = srcLocSpan interactiveSrcLoc }
1785 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1786 checkModuleExists hsc_env hpt mod =
1787 case lookupModuleEnv hpt mod of
1788 Just mod_info -> return ()
1789 _not_a_home_module -> do
1790 res <- findPackageModule hsc_env mod True
1792 Found _ _ -> return ()
1793 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1794 throwDyn (CmdLineError (showSDoc msg))
1796 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1797 mkTopLevEnv hpt modl
1798 = case lookupModuleEnv hpt modl of
1800 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1801 ++ showSDoc (pprModule modl)))
1803 case mi_globals (hm_iface details) of
1805 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1806 ++ showSDoc (pprModule modl)))
1807 Just env -> return env
1809 -- | Get the interactive evaluation context, consisting of a pair of the
1810 -- set of modules from which we take the full top-level scope, and the set
1811 -- of modules from which we take just the exports respectively.
1812 getContext :: Session -> IO ([Module],[Module])
1813 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1814 return (ic_toplev_scope ic, ic_exports ic))
1816 -- | Returns 'True' if the specified module is interpreted, and hence has
1817 -- its full top-level scope available.
1818 moduleIsInterpreted :: Session -> Module -> IO Bool
1819 moduleIsInterpreted s modl = withSession s $ \h ->
1820 case lookupModuleEnv (hsc_HPT h) modl of
1821 Just details -> return (isJust (mi_globals (hm_iface details)))
1822 _not_a_home_module -> return False
1824 -- | Looks up an identifier in the current interactive context (for :info)
1825 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
1826 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
1828 -- | Returns all names in scope in the current interactive context
1829 getNamesInScope :: Session -> IO [Name]
1830 getNamesInScope s = withSession s $ \hsc_env -> do
1831 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1833 -- | Parses a string as an identifier, and returns the list of 'Name's that
1834 -- the identifier can refer to in the current interactive context.
1835 parseName :: Session -> String -> IO [Name]
1836 parseName s str = withSession s $ \hsc_env -> do
1837 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1838 case maybe_rdr_name of
1839 Nothing -> return []
1840 Just (L _ rdr_name) -> do
1841 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1843 Nothing -> return []
1844 Just ns -> return ns
1845 -- ToDo: should return error messages
1847 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1848 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1849 lookupName :: Session -> Name -> IO (Maybe TyThing)
1850 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
1852 -- -----------------------------------------------------------------------------
1853 -- Getting the type of an expression
1855 -- | Get the type of an expression
1856 exprType :: Session -> String -> IO (Maybe Type)
1857 exprType s expr = withSession s $ \hsc_env -> do
1858 maybe_stuff <- hscTcExpr hsc_env expr
1860 Nothing -> return Nothing
1861 Just ty -> return (Just tidy_ty)
1863 tidy_ty = tidyType emptyTidyEnv ty
1865 -- -----------------------------------------------------------------------------
1866 -- Getting the kind of a type
1868 -- | Get the kind of a type
1869 typeKind :: Session -> String -> IO (Maybe Kind)
1870 typeKind s str = withSession s $ \hsc_env -> do
1871 maybe_stuff <- hscKcType hsc_env str
1873 Nothing -> return Nothing
1874 Just kind -> return (Just kind)
1876 -----------------------------------------------------------------------------
1877 -- cmCompileExpr: compile an expression and deliver an HValue
1879 compileExpr :: Session -> String -> IO (Maybe HValue)
1880 compileExpr s expr = withSession s $ \hsc_env -> do
1881 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1883 Nothing -> return Nothing
1884 Just (new_ic, names, hval) -> do
1886 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1888 case (names,hvals) of
1889 ([n],[hv]) -> return (Just hv)
1890 _ -> panic "compileExpr"
1892 -- -----------------------------------------------------------------------------
1893 -- running a statement interactively
1896 = RunOk [Name] -- ^ names bound by this evaluation
1897 | RunFailed -- ^ statement failed compilation
1898 | RunException Exception -- ^ statement raised an exception
1900 -- | Run a statement in the current interactive context. Statemenet
1901 -- may bind multple values.
1902 runStmt :: Session -> String -> IO RunResult
1903 runStmt (Session ref) expr
1905 hsc_env <- readIORef ref
1907 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1908 -- warnings about the implicit bindings we introduce.
1909 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1910 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1912 maybe_stuff <- hscStmt hsc_env' expr
1915 Nothing -> return RunFailed
1916 Just (new_hsc_env, names, hval) -> do
1918 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1919 either_hvals <- sandboxIO thing_to_run
1921 case either_hvals of
1923 -- on error, keep the *old* interactive context,
1924 -- so that 'it' is not bound to something
1925 -- that doesn't exist.
1926 return (RunException e)
1929 -- Get the newly bound things, and bind them.
1930 -- Don't need to delete any shadowed bindings;
1931 -- the new ones override the old ones.
1932 extendLinkEnv (zip names hvals)
1934 writeIORef ref new_hsc_env
1935 return (RunOk names)
1938 -- We run the statement in a "sandbox" to protect the rest of the
1939 -- system from anything the expression might do. For now, this
1940 -- consists of just wrapping it in an exception handler, but see below
1941 -- for another version.
1943 sandboxIO :: IO a -> IO (Either Exception a)
1944 sandboxIO thing = Exception.try thing
1947 -- This version of sandboxIO runs the expression in a completely new
1948 -- RTS main thread. It is disabled for now because ^C exceptions
1949 -- won't be delivered to the new thread, instead they'll be delivered
1950 -- to the (blocked) GHCi main thread.
1952 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1954 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1955 sandboxIO thing = do
1956 st_thing <- newStablePtr (Exception.try thing)
1957 alloca $ \ p_st_result -> do
1958 stat <- rts_evalStableIO st_thing p_st_result
1959 freeStablePtr st_thing
1961 then do st_result <- peek p_st_result
1962 result <- deRefStablePtr st_result
1963 freeStablePtr st_result
1964 return (Right result)
1966 return (Left (fromIntegral stat))
1968 foreign import "rts_evalStableIO" {- safe -}
1969 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1970 -- more informative than the C type!
1973 -----------------------------------------------------------------------------
1974 -- show a module and it's source/object filenames
1976 showModule :: Session -> ModSummary -> IO String
1977 showModule s mod_summary = withSession s $ \hsc_env -> do
1978 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1979 Nothing -> panic "missing linkable"
1980 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1982 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))