1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
25 Target(..), TargetId(..), Phase,
32 -- * Loading\/compiling the program
34 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
35 workingDirectoryChanged,
36 checkModule, CheckedModule(..),
37 TypecheckedSource, ParsedSource, RenamedSource,
39 -- * Inspecting the module structure of the program
40 ModuleGraph, ModSummary(..),
45 -- * Inspecting modules
50 modInfoPrintUnqualified,
53 modInfoIsExportedName,
58 PrintUnqualified, alwaysQualify,
60 -- * Interactive evaluation
61 getBindings, getPrintUnqual,
63 setContext, getContext,
77 -- * Abstract syntax elements
80 Module, mkModule, pprModule,
84 nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
89 isImplicitId, isDeadBinder,
90 isExportedId, isLocalId, isGlobalId,
92 isPrimOpId, isFCallId, isClassOpId_maybe,
93 isDataConWorkId, idDataCon,
94 isBottomingId, isDictonaryId,
95 recordSelectorFieldLabel,
97 -- ** Type constructors
99 tyConTyVars, tyConDataCons, tyConArity,
100 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon,
107 -- ** Data constructors
109 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
110 dataConIsInfix, isVanillaDataCon,
112 StrictnessMark(..), isMarkedStrict,
116 classMethods, classSCTheta, classTvsFds,
121 instanceDFunId, pprInstance, pprInstanceHdr,
123 -- ** Types and Kinds
124 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
127 ThetaType, pprThetaArrow,
133 module HsSyn, -- ToDo: remove extraneous bits
137 defaultFixity, maxPrecedence,
141 -- ** Source locations
145 GhcException(..), showGhcException,
155 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
156 * we need to expose DynFlags, so should parseDynamicFlags really be
157 part of this interface?
158 * what StaticFlags should we expose, if any?
161 #include "HsVersions.h"
164 import qualified Linker
165 import Linker ( HValue, extendLinkEnv )
166 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
167 tcRnLookupName, getModuleExports )
168 import RdrName ( plusGlobalRdrEnv, Provenance(..),
169 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
170 emptyGlobalRdrEnv, mkGlobalRdrEnv )
171 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
172 import Type ( tidyType )
173 import VarEnv ( emptyTidyEnv )
174 import GHC.Exts ( unsafeCoerce# )
177 import Packages ( initPackages )
178 import NameSet ( NameSet, nameSetToList, elemNameSet )
179 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName,
182 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
183 pprThetaArrow, pprParendType, splitForAllTys,
185 import Id ( Id, idType, isImplicitId, isDeadBinder,
186 isExportedId, isLocalId, isGlobalId,
187 isRecordSelector, recordSelectorFieldLabel,
188 isPrimOpId, isFCallId, isClassOpId_maybe,
189 isDataConWorkId, idDataCon,
192 import TysPrim ( alphaTyVars )
193 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
194 isPrimTyCon, tyConArity,
195 tyConTyVars, tyConDataCons, getSynTyConDefn )
196 import Class ( Class, classSCTheta, classTvsFds, classMethods )
197 import FunDeps ( pprFundeps )
198 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
199 dataConFieldLabels, dataConStrictMarks,
200 dataConIsInfix, isVanillaDataCon )
201 import Name ( Name, nameModule, NamedThing(..), nameParent_maybe,
203 import OccName ( parenSymOcc )
204 import NameEnv ( nameEnvElts )
205 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
207 import DriverPipeline
208 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
209 import GetImports ( getImports )
210 import Packages ( isHomePackage )
212 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
216 import SysTools ( initSysTools, cleanTempFiles )
221 import Bag ( unitBag )
222 import ErrUtils ( Severity(..), showPass, Messages, fatalErrorMsg, debugTraceMsg,
223 mkPlainErrMsg, printBagOfErrors, printErrorsAndWarnings )
224 import qualified ErrUtils
226 import StringBuffer ( StringBuffer, hGetStringBuffer )
228 import SysTools ( cleanTempFilesExcept )
230 import TcType ( tcSplitSigmaTy, isDictTy )
231 import FastString ( mkFastString )
233 import Directory ( getModificationTime, doesFileExist )
234 import Maybe ( isJust, isNothing, fromJust )
235 import Maybes ( orElse, expectJust, mapCatMaybes )
236 import List ( partition, nub )
237 import qualified List
238 import Monad ( unless, when )
239 import System ( exitWith, ExitCode(..) )
240 import Time ( ClockTime )
241 import EXCEPTION as Exception hiding (handle)
244 import Prelude hiding (init)
246 -- -----------------------------------------------------------------------------
247 -- Exception handlers
249 -- | Install some default exception handlers and run the inner computation.
250 -- Unless you want to handle exceptions yourself, you should wrap this around
251 -- the top level of your program. The default handlers output the error
252 -- message(s) to stderr and exit cleanly.
253 defaultErrorHandler :: DynFlags -> IO a -> IO a
254 defaultErrorHandler dflags inner =
255 -- top-level exception handler: any unrecognised exception is a compiler bug.
256 handle (\exception -> do
259 -- an IO exception probably isn't our fault, so don't panic
261 fatalErrorMsg dflags (text (show exception))
262 AsyncException StackOverflow ->
263 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
265 fatalErrorMsg dflags (text (show (Panic (show exception))))
266 exitWith (ExitFailure 1)
269 -- program errors: messages with locations attached. Sometimes it is
270 -- convenient to just throw these as exceptions.
271 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
272 exitWith (ExitFailure 1)) $
274 -- error messages propagated as exceptions
275 handleDyn (\dyn -> do
278 PhaseFailed _ code -> exitWith code
279 Interrupted -> exitWith (ExitFailure 1)
280 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
281 exitWith (ExitFailure 1)
285 -- | Install a default cleanup handler to remove temporary files
286 -- deposited by a GHC run. This is seperate from
287 -- 'defaultErrorHandler', because you might want to override the error
288 -- handling, but still get the ordinary cleanup behaviour.
289 defaultCleanupHandler :: DynFlags -> IO a -> IO a
290 defaultCleanupHandler dflags inner =
291 -- make sure we clean up after ourselves
292 later (unless (dopt Opt_KeepTmpFiles dflags) $
293 cleanTempFiles dflags)
294 -- exceptions will be blocked while we clean the temporary files,
295 -- so there shouldn't be any difficulty if we receive further
300 -- | Initialises GHC. This must be done /once/ only. Takes the
301 -- command-line arguments. All command-line arguments which aren't
302 -- understood by GHC will be returned.
304 init :: [String] -> IO [String]
307 installSignalHandlers
309 -- Grab the -B option if there is one
310 let (minusB_args, argv1) = partition (prefixMatch "-B") args
311 dflags0 <- initSysTools minusB_args defaultDynFlags
312 writeIORef v_initDynFlags dflags0
314 -- Parse the static flags
315 argv2 <- parseStaticFlags argv1
318 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
319 -- stores the DynFlags between the call to init and subsequent
320 -- calls to newSession.
322 -- | Starts a new session. A session consists of a set of loaded
323 -- modules, a set of options (DynFlags), and an interactive context.
324 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
326 newSession :: GhcMode -> IO Session
328 dflags0 <- readIORef v_initDynFlags
329 dflags <- initDynFlags dflags0
330 env <- newHscEnv dflags{ ghcMode=mode }
334 -- tmp: this breaks the abstraction, but required because DriverMkDepend
335 -- needs to call the Finder. ToDo: untangle this.
336 sessionHscEnv :: Session -> IO HscEnv
337 sessionHscEnv (Session ref) = readIORef ref
339 withSession :: Session -> (HscEnv -> IO a) -> IO a
340 withSession (Session ref) f = do h <- readIORef ref; f h
342 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
343 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
345 -- -----------------------------------------------------------------------------
348 -- | Grabs the DynFlags from the Session
349 getSessionDynFlags :: Session -> IO DynFlags
350 getSessionDynFlags s = withSession s (return . hsc_dflags)
352 -- | Updates the DynFlags in a Session
353 setSessionDynFlags :: Session -> DynFlags -> IO ()
354 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
356 -- -----------------------------------------------------------------------------
359 -- ToDo: think about relative vs. absolute file paths. And what
360 -- happens when the current directory changes.
362 -- | Sets the targets for this session. Each target may be a module name
363 -- or a filename. The targets correspond to the set of root modules for
364 -- the program\/library. Unloading the current program is achieved by
365 -- setting the current set of targets to be empty, followed by load.
366 setTargets :: Session -> [Target] -> IO ()
367 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
369 -- | returns the current set of targets
370 getTargets :: Session -> IO [Target]
371 getTargets s = withSession s (return . hsc_targets)
373 -- | Add another target
374 addTarget :: Session -> Target -> IO ()
376 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
379 removeTarget :: Session -> TargetId -> IO ()
380 removeTarget s target_id
381 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
383 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
385 -- Attempts to guess what Target a string refers to. This function implements
386 -- the --make/GHCi command-line syntax for filenames:
388 -- - if the string looks like a Haskell source filename, then interpret
390 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
392 -- - otherwise interpret the string as a module name
394 guessTarget :: String -> Maybe Phase -> IO Target
395 guessTarget file (Just phase)
396 = return (Target (TargetFile file (Just phase)) Nothing)
397 guessTarget file Nothing
398 | isHaskellSrcFilename file
399 = return (Target (TargetFile file Nothing) Nothing)
401 = do exists <- doesFileExist hs_file
403 then return (Target (TargetFile hs_file Nothing) Nothing)
405 exists <- doesFileExist lhs_file
407 then return (Target (TargetFile lhs_file Nothing) Nothing)
409 return (Target (TargetModule (mkModule file)) Nothing)
411 hs_file = file `joinFileExt` "hs"
412 lhs_file = file `joinFileExt` "lhs"
414 -- -----------------------------------------------------------------------------
415 -- Loading the program
417 -- Perform a dependency analysis starting from the current targets
418 -- and update the session with the new module graph.
419 depanal :: Session -> [Module] -> Bool -> IO (Maybe ModuleGraph)
420 depanal (Session ref) excluded_mods allow_dup_roots = do
421 hsc_env <- readIORef ref
423 dflags = hsc_dflags hsc_env
424 gmode = ghcMode (hsc_dflags hsc_env)
425 targets = hsc_targets hsc_env
426 old_graph = hsc_mod_graph hsc_env
428 showPass dflags "Chasing dependencies"
429 when (gmode == BatchCompile) $
430 debugTraceMsg dflags 1 (hcat [
431 text "Chasing modules from: ",
432 hcat (punctuate comma (map pprTarget targets))])
434 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
436 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
441 -- | The result of load.
443 = LoadOk Errors -- ^ all specified targets were loaded successfully.
444 | LoadFailed Errors -- ^ not all modules were loaded.
446 type Errors = [String]
448 data ErrMsg = ErrMsg {
449 errMsgSeverity :: Severity, -- warning, error, etc.
450 errMsgSpans :: [SrcSpan],
451 errMsgShortDoc :: Doc,
452 errMsgExtraInfo :: Doc
459 | LoadDependenciesOf Module
461 -- | Try to load the program. If a Module is supplied, then just
462 -- attempt to load up to this target. If no Module is supplied,
463 -- then try to load all targets.
464 load :: Session -> LoadHowMuch -> IO SuccessFlag
465 load s@(Session ref) how_much
467 -- Dependency analysis first. Note that this fixes the module graph:
468 -- even if we don't get a fully successful upsweep, the full module
469 -- graph is still retained in the Session. We can tell which modules
470 -- were successfully loaded by inspecting the Session's HPT.
471 mb_graph <- depanal s [] False
473 Just mod_graph -> load2 s how_much mod_graph
474 Nothing -> return Failed
476 load2 s@(Session ref) how_much mod_graph = do
477 hsc_env <- readIORef ref
479 let hpt1 = hsc_HPT hsc_env
480 let dflags = hsc_dflags hsc_env
481 let ghci_mode = ghcMode dflags -- this never changes
483 -- The "bad" boot modules are the ones for which we have
484 -- B.hs-boot in the module graph, but no B.hs
485 -- The downsweep should have ensured this does not happen
487 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
489 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
490 not (ms_mod s `elem` all_home_mods)]
492 ASSERT( null bad_boot_mods ) return ()
494 -- mg2_with_srcimps drops the hi-boot nodes, returning a
495 -- graph with cycles. Among other things, it is used for
496 -- backing out partially complete cycles following a failed
497 -- upsweep, and for removing from hpt all the modules
498 -- not in strict downwards closure, during calls to compile.
499 let mg2_with_srcimps :: [SCC ModSummary]
500 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
502 -- check the stability property for each module.
503 stable_mods@(stable_obj,stable_bco)
504 | BatchCompile <- ghci_mode = ([],[])
505 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
507 -- prune bits of the HPT which are definitely redundant now,
509 pruned_hpt = pruneHomePackageTable hpt1
510 (flattenSCCs mg2_with_srcimps)
515 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
516 text "Stable BCO:" <+> ppr stable_bco)
518 -- Unload any modules which are going to be re-linked this time around.
519 let stable_linkables = [ linkable
520 | m <- stable_obj++stable_bco,
521 Just hmi <- [lookupModuleEnv pruned_hpt m],
522 Just linkable <- [hm_linkable hmi] ]
523 unload hsc_env stable_linkables
525 -- We could at this point detect cycles which aren't broken by
526 -- a source-import, and complain immediately, but it seems better
527 -- to let upsweep_mods do this, so at least some useful work gets
528 -- done before the upsweep is abandoned.
529 --hPutStrLn stderr "after tsort:\n"
530 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
532 -- Now do the upsweep, calling compile for each module in
533 -- turn. Final result is version 3 of everything.
535 -- Topologically sort the module graph, this time including hi-boot
536 -- nodes, and possibly just including the portion of the graph
537 -- reachable from the module specified in the 2nd argument to load.
538 -- This graph should be cycle-free.
539 -- If we're restricting the upsweep to a portion of the graph, we
540 -- also want to retain everything that is still stable.
541 let full_mg :: [SCC ModSummary]
542 full_mg = topSortModuleGraph False mod_graph Nothing
544 maybe_top_mod = case how_much of
546 LoadDependenciesOf m -> Just m
549 partial_mg0 :: [SCC ModSummary]
550 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
552 -- LoadDependenciesOf m: we want the upsweep to stop just
553 -- short of the specified module (unless the specified module
556 | LoadDependenciesOf mod <- how_much
557 = ASSERT( case last partial_mg0 of
558 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
559 List.init partial_mg0
565 | AcyclicSCC ms <- full_mg,
566 ms_mod ms `elem` stable_obj++stable_bco,
567 ms_mod ms `notElem` [ ms_mod ms' |
568 AcyclicSCC ms' <- partial_mg ] ]
570 mg = stable_mg ++ partial_mg
572 -- clean up between compilations
573 let cleanup = cleanTempFilesExcept dflags
574 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
576 (upsweep_ok, hsc_env1, modsUpswept)
577 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
578 pruned_hpt stable_mods cleanup mg
580 -- Make modsDone be the summaries for each home module now
581 -- available; this should equal the domain of hpt3.
582 -- Get in in a roughly top .. bottom order (hence reverse).
584 let modsDone = reverse modsUpswept
586 -- Try and do linking in some form, depending on whether the
587 -- upsweep was completely or only partially successful.
589 if succeeded upsweep_ok
592 -- Easy; just relink it all.
593 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
595 -- Clean up after ourselves
596 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
598 -- Issue a warning for the confusing case where the user
599 -- said '-o foo' but we're not going to do any linking.
600 -- We attempt linking if either (a) one of the modules is
601 -- called Main, or (b) the user said -no-hs-main, indicating
602 -- that main() is going to come from somewhere else.
604 let ofile = outputFile dflags
605 let no_hs_main = dopt Opt_NoHsMain dflags
606 let mb_main_mod = mainModIs dflags
608 main_mod = mb_main_mod `orElse` "Main"
610 = any ((==main_mod).moduleUserString.ms_mod)
612 do_linking = a_root_is_Main || no_hs_main
614 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
615 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
616 "but no output will be generated\n" ++
617 "because there is no " ++ main_mod ++ " module."))
619 -- link everything together
620 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
622 loadFinish Succeeded linkresult ref hsc_env1
625 -- Tricky. We need to back out the effects of compiling any
626 -- half-done cycles, both so as to clean up the top level envs
627 -- and to avoid telling the interactive linker to link them.
628 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
631 = map ms_mod modsDone
632 let mods_to_zap_names
633 = findPartiallyCompletedCycles modsDone_names
636 = filter ((`notElem` mods_to_zap_names).ms_mod)
639 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
642 -- Clean up after ourselves
643 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
645 -- there should be no Nothings where linkables should be, now
646 ASSERT(all (isJust.hm_linkable)
647 (moduleEnvElts (hsc_HPT hsc_env))) do
649 -- Link everything together
650 linkresult <- link ghci_mode dflags False hpt4
652 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
653 loadFinish Failed linkresult ref hsc_env4
655 -- Finish up after a load.
657 -- If the link failed, unload everything and return.
658 loadFinish all_ok Failed ref hsc_env
659 = do unload hsc_env []
660 writeIORef ref $! discardProg hsc_env
663 -- Empty the interactive context and set the module context to the topmost
664 -- newly loaded module, or the Prelude if none were loaded.
665 loadFinish all_ok Succeeded ref hsc_env
666 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
670 -- Forget the current program, but retain the persistent info in HscEnv
671 discardProg :: HscEnv -> HscEnv
673 = hsc_env { hsc_mod_graph = emptyMG,
674 hsc_IC = emptyInteractiveContext,
675 hsc_HPT = emptyHomePackageTable }
677 -- used to fish out the preprocess output files for the purposes of
678 -- cleaning up. The preprocessed file *might* be the same as the
679 -- source file, but that doesn't do any harm.
680 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
682 -- -----------------------------------------------------------------------------
686 CheckedModule { parsedSource :: ParsedSource,
687 renamedSource :: Maybe RenamedSource,
688 typecheckedSource :: Maybe TypecheckedSource,
689 checkedModuleInfo :: Maybe ModuleInfo
691 -- ToDo: improvements that could be made here:
692 -- if the module succeeded renaming but not typechecking,
693 -- we can still get back the GlobalRdrEnv and exports, so
694 -- perhaps the ModuleInfo should be split up into separate
695 -- fields within CheckedModule.
697 type ParsedSource = Located (HsModule RdrName)
698 type RenamedSource = HsGroup Name
699 type TypecheckedSource = LHsBinds Id
702 -- - things that aren't in the output of the renamer:
705 -- - things that aren't in the output of the typechecker right now:
709 -- - type/data/newtype declarations
710 -- - class declarations
712 -- - extra things in the typechecker's output:
713 -- - default methods are turned into top-level decls.
714 -- - dictionary bindings
717 -- | This is the way to get access to parsed and typechecked source code
718 -- for a module. 'checkModule' loads all the dependencies of the specified
719 -- module in the Session, and then attempts to typecheck the module. If
720 -- successful, it returns the abstract syntax for the module.
721 checkModule :: Session -> Module -> IO (Maybe CheckedModule)
722 checkModule session@(Session ref) mod = do
723 -- load up the dependencies first
724 r <- load session (LoadDependenciesOf mod)
725 if (failed r) then return Nothing else do
727 -- now parse & typecheck the module
728 hsc_env <- readIORef ref
729 let mg = hsc_mod_graph hsc_env
730 case [ ms | ms <- mg, ms_mod ms == mod ] of
733 -- Add in the OPTIONS from the source file This is nasty:
734 -- we've done this once already, in the compilation manager
735 -- It might be better to cache the flags in the
736 -- ml_hspp_file field, say
737 let dflags0 = hsc_dflags hsc_env
738 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
739 filename = fromJust (ml_hs_file (ms_location ms))
740 opts = getOptionsFromStringBuffer hspp_buf filename
741 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
742 if (not (null leftovers))
743 then do printErrorsAndWarnings dflags1 (optionsErrorMsgs leftovers opts filename)
747 r <- hscFileCheck hsc_env{hsc_dflags=dflags1} ms
751 HscChecked parsed renamed Nothing ->
752 return (Just (CheckedModule {
753 parsedSource = parsed,
754 renamedSource = renamed,
755 typecheckedSource = Nothing,
756 checkedModuleInfo = Nothing }))
757 HscChecked parsed renamed
758 (Just (tc_binds, rdr_env, details)) -> do
759 let minf = ModuleInfo {
760 minf_type_env = md_types details,
761 minf_exports = md_exports details,
762 minf_rdr_env = Just rdr_env,
763 minf_instances = md_insts details
765 return (Just (CheckedModule {
766 parsedSource = parsed,
767 renamedSource = renamed,
768 typecheckedSource = Just tc_binds,
769 checkedModuleInfo = Just minf }))
773 -- ---------------------------------------------------------------------------
776 unload :: HscEnv -> [Linkable] -> IO ()
777 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
778 = case ghcMode (hsc_dflags hsc_env) of
779 BatchCompile -> return ()
780 JustTypecheck -> return ()
782 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
784 Interactive -> panic "unload: no interpreter"
786 other -> panic "unload: strange mode"
788 -- -----------------------------------------------------------------------------
792 Stability tells us which modules definitely do not need to be recompiled.
793 There are two main reasons for having stability:
795 - avoid doing a complete upsweep of the module graph in GHCi when
796 modules near the bottom of the tree have not changed.
798 - to tell GHCi when it can load object code: we can only load object code
799 for a module when we also load object code fo all of the imports of the
800 module. So we need to know that we will definitely not be recompiling
801 any of these modules, and we can use the object code.
803 NB. stability is of no importance to BatchCompile at all, only Interactive.
804 (ToDo: what about JustTypecheck?)
806 The stability check is as follows. Both stableObject and
807 stableBCO are used during the upsweep phase later.
810 stable m = stableObject m || stableBCO m
813 all stableObject (imports m)
814 && old linkable does not exist, or is == on-disk .o
815 && date(on-disk .o) > date(.hs)
818 all stable (imports m)
819 && date(BCO) > date(.hs)
822 These properties embody the following ideas:
824 - if a module is stable:
825 - if it has been compiled in a previous pass (present in HPT)
826 then it does not need to be compiled or re-linked.
827 - if it has not been compiled in a previous pass,
828 then we only need to read its .hi file from disk and
829 link it to produce a ModDetails.
831 - if a modules is not stable, we will definitely be at least
832 re-linking, and possibly re-compiling it during the upsweep.
833 All non-stable modules can (and should) therefore be unlinked
836 - Note that objects are only considered stable if they only depend
837 on other objects. We can't link object code against byte code.
841 :: HomePackageTable -- HPT from last compilation
842 -> [SCC ModSummary] -- current module graph (cyclic)
843 -> [Module] -- all home modules
844 -> ([Module], -- stableObject
845 [Module]) -- stableBCO
847 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
849 checkSCC (stable_obj, stable_bco) scc0
850 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
851 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
852 | otherwise = (stable_obj, stable_bco)
854 scc = flattenSCC scc0
855 scc_mods = map ms_mod scc
856 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
858 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
859 -- all imports outside the current SCC, but in the home pkg
861 stable_obj_imps = map (`elem` stable_obj) scc_allimps
862 stable_bco_imps = map (`elem` stable_bco) scc_allimps
869 and (zipWith (||) stable_obj_imps stable_bco_imps)
873 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
877 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
878 Just hmi | Just l <- hm_linkable hmi
879 -> isObjectLinkable l && t == linkableTime l
881 -- why '>=' rather than '>' above? If the filesystem stores
882 -- times to the nearset second, we may occasionally find that
883 -- the object & source have the same modification time,
884 -- especially if the source was automatically generated
885 -- and compiled. Using >= is slightly unsafe, but it matches
889 = case lookupModuleEnv hpt (ms_mod ms) of
890 Just hmi | Just l <- hm_linkable hmi ->
891 not (isObjectLinkable l) &&
892 linkableTime l >= ms_hs_date ms
895 ms_allimps :: ModSummary -> [Module]
896 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
898 -- -----------------------------------------------------------------------------
899 -- Prune the HomePackageTable
901 -- Before doing an upsweep, we can throw away:
903 -- - For non-stable modules:
904 -- - all ModDetails, all linked code
905 -- - all unlinked code that is out of date with respect to
908 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
909 -- space at the end of the upsweep, because the topmost ModDetails of the
910 -- old HPT holds on to the entire type environment from the previous
913 pruneHomePackageTable
916 -> ([Module],[Module])
919 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
920 = mapModuleEnv prune hpt
922 | is_stable modl = hmi'
923 | otherwise = hmi'{ hm_details = emptyModDetails }
925 modl = mi_module (hm_iface hmi)
926 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
927 = hmi{ hm_linkable = Nothing }
930 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
932 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
934 is_stable m = m `elem` stable_obj || m `elem` stable_bco
936 -- -----------------------------------------------------------------------------
938 -- Return (names of) all those in modsDone who are part of a cycle
939 -- as defined by theGraph.
940 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
941 findPartiallyCompletedCycles modsDone theGraph
945 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
946 chew ((CyclicSCC vs):rest)
947 = let names_in_this_cycle = nub (map ms_mod vs)
949 = nub ([done | done <- modsDone,
950 done `elem` names_in_this_cycle])
951 chewed_rest = chew rest
953 if notNull mods_in_this_cycle
954 && length mods_in_this_cycle < length names_in_this_cycle
955 then mods_in_this_cycle ++ chewed_rest
958 -- -----------------------------------------------------------------------------
961 -- This is where we compile each module in the module graph, in a pass
962 -- from the bottom to the top of the graph.
964 -- There better had not be any cyclic groups here -- we check for them.
967 :: HscEnv -- Includes initially-empty HPT
968 -> HomePackageTable -- HPT from last time round (pruned)
969 -> ([Module],[Module]) -- stable modules (see checkStability)
970 -> IO () -- How to clean up unwanted tmp files
971 -> [SCC ModSummary] -- Mods to do (the worklist)
973 HscEnv, -- With an updated HPT
974 [ModSummary]) -- Mods which succeeded
976 upsweep hsc_env old_hpt stable_mods cleanup mods
977 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
979 upsweep' hsc_env old_hpt stable_mods cleanup
981 = return (Succeeded, hsc_env, [])
983 upsweep' hsc_env old_hpt stable_mods cleanup
985 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
986 return (Failed, hsc_env, [])
988 upsweep' hsc_env old_hpt stable_mods cleanup
989 (AcyclicSCC mod:mods) mod_index nmods
990 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
991 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
992 -- (moduleEnvElts (hsc_HPT hsc_env)))
994 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
997 cleanup -- Remove unwanted tmp files between compilations
1000 Nothing -> return (Failed, hsc_env, [])
1002 { let this_mod = ms_mod mod
1004 -- Add new info to hsc_env
1005 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
1007 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1009 -- Space-saving: delete the old HPT entry
1010 -- for mod BUT if mod is a hs-boot
1011 -- node, don't delete it. For the
1012 -- interface, the HPT entry is probaby for the
1013 -- main Haskell source file. Deleting it
1014 -- would force .. (what?? --SDM)
1015 old_hpt1 | isBootSummary mod = old_hpt
1016 | otherwise = delModuleEnv old_hpt this_mod
1018 ; (restOK, hsc_env2, modOKs)
1019 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1020 mods (mod_index+1) nmods
1021 ; return (restOK, hsc_env2, mod:modOKs)
1025 -- Compile a single module. Always produce a Linkable for it if
1026 -- successful. If no compilation happened, return the old Linkable.
1027 upsweep_mod :: HscEnv
1029 -> ([Module],[Module])
1031 -> Int -- index of module
1032 -> Int -- total number of modules
1033 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1035 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1038 this_mod = ms_mod summary
1039 mb_obj_date = ms_obj_date summary
1040 obj_fn = ml_obj_file (ms_location summary)
1041 hs_date = ms_hs_date summary
1043 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1044 compile_it = upsweep_compile hsc_env old_hpt this_mod
1045 summary mod_index nmods
1047 case ghcMode (hsc_dflags hsc_env) of
1050 -- Batch-compilating is easy: just check whether we have
1051 -- an up-to-date object file. If we do, then the compiler
1052 -- needs to do a recompilation check.
1053 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1055 findObjectLinkable this_mod obj_fn obj_date
1056 compile_it (Just linkable)
1063 _ | is_stable_obj, isJust old_hmi ->
1065 -- object is stable, and we have an entry in the
1066 -- old HPT: nothing to do
1068 | is_stable_obj, isNothing old_hmi -> do
1070 findObjectLinkable this_mod obj_fn
1071 (expectJust "upseep1" mb_obj_date)
1072 compile_it (Just linkable)
1073 -- object is stable, but we need to load the interface
1074 -- off disk to make a HMI.
1077 ASSERT(isJust old_hmi) -- must be in the old_hpt
1079 -- BCO is stable: nothing to do
1081 | Just hmi <- old_hmi,
1082 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1083 linkableTime l >= ms_hs_date summary ->
1085 -- we have an old BCO that is up to date with respect
1086 -- to the source: do a recompilation check as normal.
1090 -- no existing code at all: we must recompile.
1092 is_stable_obj = this_mod `elem` stable_obj
1093 is_stable_bco = this_mod `elem` stable_bco
1095 old_hmi = lookupModuleEnv old_hpt this_mod
1097 -- Run hsc to compile a module
1098 upsweep_compile hsc_env old_hpt this_mod summary
1100 mb_old_linkable = do
1102 -- The old interface is ok if it's in the old HPT
1103 -- a) we're compiling a source file, and the old HPT
1104 -- entry is for a source file
1105 -- b) we're compiling a hs-boot file
1106 -- Case (b) allows an hs-boot file to get the interface of its
1107 -- real source file on the second iteration of the compilation
1108 -- manager, but that does no harm. Otherwise the hs-boot file
1109 -- will always be recompiled
1112 = case lookupModuleEnv old_hpt this_mod of
1114 Just hm_info | isBootSummary summary -> Just iface
1115 | not (mi_boot iface) -> Just iface
1116 | otherwise -> Nothing
1118 iface = hm_iface hm_info
1120 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1124 -- Compilation failed. Compile may still have updated the PCS, tho.
1125 CompErrs -> return Nothing
1127 -- Compilation "succeeded", and may or may not have returned a new
1128 -- linkable (depending on whether compilation was actually performed
1130 CompOK new_details new_iface new_linkable
1131 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1132 hm_details = new_details,
1133 hm_linkable = new_linkable }
1134 return (Just new_info)
1137 -- Filter modules in the HPT
1138 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1139 retainInTopLevelEnvs keep_these hpt
1140 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1142 , let mb_mod_info = lookupModuleEnv hpt mod
1143 , isJust mb_mod_info ]
1145 -- ---------------------------------------------------------------------------
1146 -- Topological sort of the module graph
1149 :: Bool -- Drop hi-boot nodes? (see below)
1153 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1154 -- The resulting list of strongly-connected-components is in topologically
1155 -- sorted order, starting with the module(s) at the bottom of the
1156 -- dependency graph (ie compile them first) and ending with the ones at
1159 -- Drop hi-boot nodes (first boolean arg)?
1161 -- False: treat the hi-boot summaries as nodes of the graph,
1162 -- so the graph must be acyclic
1164 -- True: eliminate the hi-boot nodes, and instead pretend
1165 -- the a source-import of Foo is an import of Foo
1166 -- The resulting graph has no hi-boot nodes, but can by cyclic
1168 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1169 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1170 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1171 = stronglyConnComp (map vertex_fn (reachable graph root))
1173 -- restrict the graph to just those modules reachable from
1174 -- the specified module. We do this by building a graph with
1175 -- the full set of nodes, and determining the reachable set from
1176 -- the specified node.
1177 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1178 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1180 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1181 | otherwise = throwDyn (ProgramError "module does not exist")
1183 moduleGraphNodes :: Bool -> [ModSummary]
1184 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1185 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1187 -- Drop hs-boot nodes by using HsSrcFile as the key
1188 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1189 | otherwise = HsBootFile
1191 -- We use integers as the keys for the SCC algorithm
1192 nodes :: [(ModSummary, Int, [Int])]
1193 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1194 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1195 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) )
1197 , not (isBootSummary s && drop_hs_boot_nodes) ]
1198 -- Drop the hi-boot ones if told to do so
1200 key_map :: NodeMap Int
1201 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1204 lookup_key :: HscSource -> Module -> Maybe Int
1205 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1207 out_edge_keys :: HscSource -> [Module] -> [Int]
1208 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1209 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1210 -- the IsBootInterface parameter True; else False
1213 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1214 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1216 msKey :: ModSummary -> NodeKey
1217 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1219 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1220 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1222 nodeMapElts :: NodeMap a -> [a]
1223 nodeMapElts = eltsFM
1225 -----------------------------------------------------------------------------
1226 -- Downsweep (dependency analysis)
1228 -- Chase downwards from the specified root set, returning summaries
1229 -- for all home modules encountered. Only follow source-import
1232 -- We pass in the previous collection of summaries, which is used as a
1233 -- cache to avoid recalculating a module summary if the source is
1236 -- The returned list of [ModSummary] nodes has one node for each home-package
1237 -- module, plus one for any hs-boot files. The imports of these nodes
1238 -- are all there, including the imports of non-home-package modules.
1241 -> [ModSummary] -- Old summaries
1242 -> [Module] -- Ignore dependencies on these; treat
1243 -- them as if they were package modules
1244 -> Bool -- True <=> allow multiple targets to have
1245 -- the same module name; this is
1246 -- very useful for ghc -M
1247 -> IO (Maybe [ModSummary])
1248 -- The elts of [ModSummary] all have distinct
1249 -- (Modules, IsBoot) identifiers, unless the Bool is true
1250 -- in which case there can be repeats
1251 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1252 = -- catch error messages and return them
1253 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1254 rootSummaries <- mapM getRootSummary roots
1255 let root_map = mkRootMap rootSummaries
1256 checkDuplicates root_map
1257 summs <- loop (concatMap msDeps rootSummaries) root_map
1260 roots = hsc_targets hsc_env
1262 old_summary_map :: NodeMap ModSummary
1263 old_summary_map = mkNodeMap old_summaries
1265 getRootSummary :: Target -> IO ModSummary
1266 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1267 = do exists <- doesFileExist file
1269 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1270 else throwDyn $ mkPlainErrMsg noSrcSpan $
1271 text "can't find file:" <+> text file
1272 getRootSummary (Target (TargetModule modl) maybe_buf)
1273 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1274 (L rootLoc modl) maybe_buf excl_mods
1275 case maybe_summary of
1276 Nothing -> packageModErr modl
1279 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1281 -- In a root module, the filename is allowed to diverge from the module
1282 -- name, so we have to check that there aren't multiple root files
1283 -- defining the same module (otherwise the duplicates will be silently
1284 -- ignored, leading to confusing behaviour).
1285 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1286 checkDuplicates root_map
1287 | allow_dup_roots = return ()
1288 | null dup_roots = return ()
1289 | otherwise = multiRootsErr (head dup_roots)
1291 dup_roots :: [[ModSummary]] -- Each at least of length 2
1292 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1294 loop :: [(Located Module,IsBootInterface)]
1295 -- Work list: process these modules
1296 -> NodeMap [ModSummary]
1297 -- Visited set; the range is a list because
1298 -- the roots can have the same module names
1299 -- if allow_dup_roots is True
1301 -- The result includes the worklist, except
1302 -- for those mentioned in the visited set
1303 loop [] done = return (concat (nodeMapElts done))
1304 loop ((wanted_mod, is_boot) : ss) done
1305 | Just summs <- lookupFM done key
1306 = if isSingleton summs then
1309 do { multiRootsErr summs; return [] }
1310 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1311 is_boot wanted_mod Nothing excl_mods
1313 Nothing -> loop ss done
1314 Just s -> loop (msDeps s ++ ss)
1315 (addToFM done key [s]) }
1317 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1319 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1320 mkRootMap summaries = addListToFM_C (++) emptyFM
1321 [ (msKey s, [s]) | s <- summaries ]
1323 msDeps :: ModSummary -> [(Located Module, IsBootInterface)]
1324 -- (msDeps s) returns the dependencies of the ModSummary s.
1325 -- A wrinkle is that for a {-# SOURCE #-} import we return
1326 -- *both* the hs-boot file
1327 -- *and* the source file
1328 -- as "dependencies". That ensures that the list of all relevant
1329 -- modules always contains B.hs if it contains B.hs-boot.
1330 -- Remember, this pass isn't doing the topological sort. It's
1331 -- just gathering the list of all relevant ModSummaries
1333 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1334 ++ [ (m,False) | m <- ms_imps s ]
1336 -----------------------------------------------------------------------------
1337 -- Summarising modules
1339 -- We have two types of summarisation:
1341 -- * Summarise a file. This is used for the root module(s) passed to
1342 -- cmLoadModules. The file is read, and used to determine the root
1343 -- module name. The module name may differ from the filename.
1345 -- * Summarise a module. We are given a module name, and must provide
1346 -- a summary. The finder is used to locate the file in which the module
1351 -> [ModSummary] -- old summaries
1352 -> FilePath -- source file name
1353 -> Maybe Phase -- start phase
1354 -> Maybe (StringBuffer,ClockTime)
1357 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1358 -- we can use a cached summary if one is available and the
1359 -- source file hasn't changed, But we have to look up the summary
1360 -- by source file, rather than module name as we do in summarise.
1361 | Just old_summary <- findSummaryBySourceFile old_summaries file
1363 let location = ms_location old_summary
1365 -- return the cached summary if the source didn't change
1366 src_timestamp <- case maybe_buf of
1367 Just (_,t) -> return t
1368 Nothing -> getModificationTime file
1369 -- The file exists; we checked in getRootSummary above.
1370 -- If it gets removed subsequently, then this
1371 -- getModificationTime may fail, but that's the right
1374 if ms_hs_date old_summary == src_timestamp
1375 then do -- update the object-file timestamp
1376 obj_timestamp <- getObjTimestamp location False
1377 return old_summary{ ms_obj_date = obj_timestamp }
1385 let dflags = hsc_dflags hsc_env
1387 (dflags', hspp_fn, buf)
1388 <- preprocessFile dflags file mb_phase maybe_buf
1390 (srcimps,the_imps, L _ mod) <- getImports dflags' buf hspp_fn
1392 -- Make a ModLocation for this file
1393 location <- mkHomeModLocation dflags mod file
1395 -- Tell the Finder cache where it is, so that subsequent calls
1396 -- to findModule will find it, even if it's not on any search path
1397 addHomeModuleToFinder hsc_env mod location
1399 src_timestamp <- case maybe_buf of
1400 Just (_,t) -> return t
1401 Nothing -> getModificationTime file
1402 -- getMofificationTime may fail
1404 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1406 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1407 ms_location = location,
1408 ms_hspp_file = Just hspp_fn,
1409 ms_hspp_buf = Just buf,
1410 ms_srcimps = srcimps, ms_imps = the_imps,
1411 ms_hs_date = src_timestamp,
1412 ms_obj_date = obj_timestamp })
1414 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1415 findSummaryBySourceFile summaries file
1416 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1417 fromJust (ml_hs_file (ms_location ms)) == file ] of
1421 -- Summarise a module, and pick up source and timestamp.
1424 -> NodeMap ModSummary -- Map of old summaries
1425 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1426 -> Located Module -- Imported module to be summarised
1427 -> Maybe (StringBuffer, ClockTime)
1428 -> [Module] -- Modules to exclude
1429 -> IO (Maybe ModSummary) -- Its new summary
1431 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1432 | wanted_mod `elem` excl_mods
1435 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1436 = do -- Find its new timestamp; all the
1437 -- ModSummaries in the old map have valid ml_hs_files
1438 let location = ms_location old_summary
1439 src_fn = expectJust "summariseModule" (ml_hs_file location)
1441 -- check the modification time on the source file, and
1442 -- return the cached summary if it hasn't changed. If the
1443 -- file has disappeared, we need to call the Finder again.
1445 Just (_,t) -> check_timestamp old_summary location src_fn t
1447 m <- IO.try (getModificationTime src_fn)
1449 Right t -> check_timestamp old_summary location src_fn t
1450 Left e | isDoesNotExistError e -> find_it
1451 | otherwise -> ioError e
1453 | otherwise = find_it
1455 dflags = hsc_dflags hsc_env
1457 hsc_src = if is_boot then HsBootFile else HsSrcFile
1459 check_timestamp old_summary location src_fn src_timestamp
1460 | ms_hs_date old_summary == src_timestamp = do
1461 -- update the object-file timestamp
1462 obj_timestamp <- getObjTimestamp location is_boot
1463 return (Just old_summary{ ms_obj_date = obj_timestamp })
1465 -- source changed: find and re-summarise. We call the finder
1466 -- again, because the user may have moved the source file.
1467 new_summary location src_fn src_timestamp
1470 -- Don't use the Finder's cache this time. If the module was
1471 -- previously a package module, it may have now appeared on the
1472 -- search path, so we want to consider it to be a home module. If
1473 -- the module was previously a home module, it may have moved.
1474 uncacheModule hsc_env wanted_mod
1475 found <- findModule hsc_env wanted_mod True {-explicit-}
1478 | not (isHomePackage pkg) -> return Nothing
1479 -- Drop external-pkg
1480 | isJust (ml_hs_file location) -> just_found location
1482 err -> noModError dflags loc wanted_mod err
1485 just_found location = do
1486 -- Adjust location to point to the hs-boot source file,
1487 -- hi file, object file, when is_boot says so
1488 let location' | is_boot = addBootSuffixLocn location
1489 | otherwise = location
1490 src_fn = expectJust "summarise2" (ml_hs_file location')
1492 -- Check that it exists
1493 -- It might have been deleted since the Finder last found it
1494 maybe_t <- modificationTimeIfExists src_fn
1496 Nothing -> noHsFileErr loc src_fn
1497 Just t -> new_summary location' src_fn t
1500 new_summary location src_fn src_timestamp
1502 -- Preprocess the source file and get its imports
1503 -- The dflags' contains the OPTIONS pragmas
1504 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1505 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1507 when (mod_name /= wanted_mod) $
1508 throwDyn $ mkPlainErrMsg mod_loc $
1509 text "file name does not match module name"
1510 <+> quotes (ppr mod_name)
1512 -- Find the object timestamp, and return the summary
1513 obj_timestamp <- getObjTimestamp location is_boot
1515 return (Just ( ModSummary { ms_mod = wanted_mod,
1516 ms_hsc_src = hsc_src,
1517 ms_location = location,
1518 ms_hspp_file = Just hspp_fn,
1519 ms_hspp_buf = Just buf,
1520 ms_srcimps = srcimps,
1522 ms_hs_date = src_timestamp,
1523 ms_obj_date = obj_timestamp }))
1526 getObjTimestamp location is_boot
1527 = if is_boot then return Nothing
1528 else modificationTimeIfExists (ml_obj_file location)
1531 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1532 -> IO (DynFlags, FilePath, StringBuffer)
1533 preprocessFile dflags src_fn mb_phase Nothing
1535 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1536 buf <- hGetStringBuffer hspp_fn
1537 return (dflags', hspp_fn, buf)
1539 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1541 -- case we bypass the preprocessing stage?
1543 local_opts = getOptionsFromStringBuffer buf src_fn
1545 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1549 | Just (Unlit _) <- mb_phase = True
1550 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1551 -- note: local_opts is only required if there's no Unlit phase
1552 | dopt Opt_Cpp dflags' = True
1553 | dopt Opt_Pp dflags' = True
1556 when needs_preprocessing $
1557 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1559 return (dflags', src_fn, buf)
1562 -----------------------------------------------------------------------------
1564 -----------------------------------------------------------------------------
1566 noModError :: DynFlags -> SrcSpan -> Module -> FindResult -> IO ab
1567 -- ToDo: we don't have a proper line number for this error
1568 noModError dflags loc wanted_mod err
1569 = throwDyn $ mkPlainErrMsg loc $ cantFindError dflags wanted_mod err
1571 noHsFileErr loc path
1572 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1575 = throwDyn $ mkPlainErrMsg noSrcSpan $
1576 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1578 multiRootsErr :: [ModSummary] -> IO ()
1579 multiRootsErr summs@(summ1:_)
1580 = throwDyn $ mkPlainErrMsg noSrcSpan $
1581 text "module" <+> quotes (ppr mod) <+>
1582 text "is defined in multiple files:" <+>
1583 sep (map text files)
1586 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1588 cyclicModuleErr :: [ModSummary] -> SDoc
1590 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1591 2 (vcat (map show_one ms))
1593 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1594 nest 2 $ ptext SLIT("imports:") <+>
1595 (pp_imps HsBootFile (ms_srcimps ms)
1596 $$ pp_imps HsSrcFile (ms_imps ms))]
1597 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1598 pp_imps src mods = fsep (map (show_mod src) mods)
1601 -- | Inform GHC that the working directory has changed. GHC will flush
1602 -- its cache of module locations, since it may no longer be valid.
1603 -- Note: if you change the working directory, you should also unload
1604 -- the current program (set targets to empty, followed by load).
1605 workingDirectoryChanged :: Session -> IO ()
1606 workingDirectoryChanged s = withSession s $ \hsc_env ->
1607 flushFinderCache (hsc_FC hsc_env)
1609 -- -----------------------------------------------------------------------------
1610 -- inspecting the session
1612 -- | Get the module dependency graph.
1613 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1614 getModuleGraph s = withSession s (return . hsc_mod_graph)
1616 isLoaded :: Session -> Module -> IO Bool
1617 isLoaded s m = withSession s $ \hsc_env ->
1618 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1620 getBindings :: Session -> IO [TyThing]
1621 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1623 getPrintUnqual :: Session -> IO PrintUnqualified
1624 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1626 -- | Container for information about a 'Module'.
1627 data ModuleInfo = ModuleInfo {
1628 minf_type_env :: TypeEnv,
1629 minf_exports :: NameSet,
1630 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1631 minf_instances :: [Instance]
1632 -- ToDo: this should really contain the ModIface too
1634 -- We don't want HomeModInfo here, because a ModuleInfo applies
1635 -- to package modules too.
1637 -- | Request information about a loaded 'Module'
1638 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1639 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1640 let mg = hsc_mod_graph hsc_env
1641 if mdl `elem` map ms_mod mg
1642 then getHomeModuleInfo hsc_env mdl
1644 {- if isHomeModule (hsc_dflags hsc_env) mdl
1646 else -} getPackageModuleInfo hsc_env mdl
1647 -- getPackageModuleInfo will attempt to find the interface, so
1648 -- we don't want to call it for a home module, just in case there
1649 -- was a problem loading the module and the interface doesn't
1650 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1652 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1653 getPackageModuleInfo hsc_env mdl = do
1655 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1657 Nothing -> return Nothing
1659 eps <- readIORef (hsc_EPS hsc_env)
1662 n_list = nameSetToList names
1663 tys = [ ty | name <- n_list,
1664 Just ty <- [lookupTypeEnv pte name] ]
1666 return (Just (ModuleInfo {
1667 minf_type_env = mkTypeEnv tys,
1668 minf_exports = names,
1669 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names mdl,
1670 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1673 -- bogusly different for non-GHCI (ToDo)
1677 getHomeModuleInfo hsc_env mdl =
1678 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1679 Nothing -> return Nothing
1681 let details = hm_details hmi
1682 return (Just (ModuleInfo {
1683 minf_type_env = md_types details,
1684 minf_exports = md_exports details,
1685 minf_rdr_env = mi_globals $! hm_iface hmi,
1686 minf_instances = md_insts details
1689 -- | The list of top-level entities defined in a module
1690 modInfoTyThings :: ModuleInfo -> [TyThing]
1691 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1693 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1694 modInfoTopLevelScope minf
1695 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1697 modInfoExports :: ModuleInfo -> [Name]
1698 modInfoExports minf = nameSetToList $! minf_exports minf
1700 -- | Returns the instances defined by the specified module.
1701 -- Warning: currently unimplemented for package modules.
1702 modInfoInstances :: ModuleInfo -> [Instance]
1703 modInfoInstances = minf_instances
1705 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1706 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1708 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1709 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1711 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1712 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1713 case lookupTypeEnv (minf_type_env minf) name of
1714 Just tyThing -> return (Just tyThing)
1716 eps <- readIORef (hsc_EPS hsc_env)
1717 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1719 isDictonaryId :: Id -> Bool
1721 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1723 -- | Looks up a global name: that is, any top-level name in any
1724 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1725 -- the interactive context, and therefore does not require a preceding
1727 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1728 lookupGlobalName s name = withSession s $ \hsc_env -> do
1729 eps <- readIORef (hsc_EPS hsc_env)
1730 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1732 -- -----------------------------------------------------------------------------
1733 -- Misc exported utils
1735 dataConType :: DataCon -> Type
1736 dataConType dc = idType (dataConWrapId dc)
1738 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1739 pprParenSymName :: NamedThing a => a -> SDoc
1740 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1742 -- ----------------------------------------------------------------------------
1747 -- - Data and Typeable instances for HsSyn.
1749 -- ToDo: check for small transformations that happen to the syntax in
1750 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1752 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1753 -- to get from TyCons, Ids etc. to TH syntax (reify).
1755 -- :browse will use either lm_toplev or inspect lm_interface, depending
1756 -- on whether the module is interpreted or not.
1758 -- This is for reconstructing refactored source code
1759 -- Calls the lexer repeatedly.
1760 -- ToDo: add comment tokens to token stream
1761 getTokenStream :: Session -> Module -> IO [Located Token]
1764 -- -----------------------------------------------------------------------------
1765 -- Interactive evaluation
1769 -- | Set the interactive evaluation context.
1771 -- Setting the context doesn't throw away any bindings; the bindings
1772 -- we've built up in the InteractiveContext simply move to the new
1773 -- module. They always shadow anything in scope in the current context.
1774 setContext :: Session
1775 -> [Module] -- entire top level scope of these modules
1776 -> [Module] -- exports only of these modules
1778 setContext (Session ref) toplevs exports = do
1779 hsc_env <- readIORef ref
1780 let old_ic = hsc_IC hsc_env
1781 hpt = hsc_HPT hsc_env
1783 mapM_ (checkModuleExists hsc_env hpt) exports
1784 export_env <- mkExportEnv hsc_env exports
1785 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1786 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1787 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1788 ic_exports = exports,
1789 ic_rn_gbl_env = all_env }}
1792 -- Make a GlobalRdrEnv based on the exports of the modules only.
1793 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1794 mkExportEnv hsc_env mods = do
1795 stuff <- mapM (getModuleExports hsc_env) mods
1797 (_msgs, mb_name_sets) = unzip stuff
1798 gres = [ nameSetToGlobalRdrEnv name_set mod
1799 | (Just name_set, mod) <- zip mb_name_sets mods ]
1801 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1803 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1804 nameSetToGlobalRdrEnv names mod =
1805 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1806 | name <- nameSetToList names ]
1808 vanillaProv :: Module -> Provenance
1809 -- We're building a GlobalRdrEnv as if the user imported
1810 -- all the specified modules into the global interactive module
1811 vanillaProv mod = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1813 decl = ImpDeclSpec { is_mod = mod, is_as = mod,
1815 is_dloc = srcLocSpan interactiveSrcLoc }
1817 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1818 checkModuleExists hsc_env hpt mod =
1819 case lookupModuleEnv hpt mod of
1820 Just mod_info -> return ()
1821 _not_a_home_module -> do
1822 res <- findPackageModule hsc_env mod True
1824 Found _ _ -> return ()
1825 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1826 throwDyn (CmdLineError (showSDoc msg))
1828 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1829 mkTopLevEnv hpt modl
1830 = case lookupModuleEnv hpt modl of
1832 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1833 ++ showSDoc (pprModule modl)))
1835 case mi_globals (hm_iface details) of
1837 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1838 ++ showSDoc (pprModule modl)))
1839 Just env -> return env
1841 -- | Get the interactive evaluation context, consisting of a pair of the
1842 -- set of modules from which we take the full top-level scope, and the set
1843 -- of modules from which we take just the exports respectively.
1844 getContext :: Session -> IO ([Module],[Module])
1845 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1846 return (ic_toplev_scope ic, ic_exports ic))
1848 -- | Returns 'True' if the specified module is interpreted, and hence has
1849 -- its full top-level scope available.
1850 moduleIsInterpreted :: Session -> Module -> IO Bool
1851 moduleIsInterpreted s modl = withSession s $ \h ->
1852 case lookupModuleEnv (hsc_HPT h) modl of
1853 Just details -> return (isJust (mi_globals (hm_iface details)))
1854 _not_a_home_module -> return False
1856 -- | Looks up an identifier in the current interactive context (for :info)
1857 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
1858 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
1860 -- | Returns all names in scope in the current interactive context
1861 getNamesInScope :: Session -> IO [Name]
1862 getNamesInScope s = withSession s $ \hsc_env -> do
1863 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1865 -- | Parses a string as an identifier, and returns the list of 'Name's that
1866 -- the identifier can refer to in the current interactive context.
1867 parseName :: Session -> String -> IO [Name]
1868 parseName s str = withSession s $ \hsc_env -> do
1869 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1870 case maybe_rdr_name of
1871 Nothing -> return []
1872 Just (L _ rdr_name) -> do
1873 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1875 Nothing -> return []
1876 Just ns -> return ns
1877 -- ToDo: should return error messages
1879 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1880 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1881 lookupName :: Session -> Name -> IO (Maybe TyThing)
1882 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
1884 -- -----------------------------------------------------------------------------
1885 -- Getting the type of an expression
1887 -- | Get the type of an expression
1888 exprType :: Session -> String -> IO (Maybe Type)
1889 exprType s expr = withSession s $ \hsc_env -> do
1890 maybe_stuff <- hscTcExpr hsc_env expr
1892 Nothing -> return Nothing
1893 Just ty -> return (Just tidy_ty)
1895 tidy_ty = tidyType emptyTidyEnv ty
1897 -- -----------------------------------------------------------------------------
1898 -- Getting the kind of a type
1900 -- | Get the kind of a type
1901 typeKind :: Session -> String -> IO (Maybe Kind)
1902 typeKind s str = withSession s $ \hsc_env -> do
1903 maybe_stuff <- hscKcType hsc_env str
1905 Nothing -> return Nothing
1906 Just kind -> return (Just kind)
1908 -----------------------------------------------------------------------------
1909 -- cmCompileExpr: compile an expression and deliver an HValue
1911 compileExpr :: Session -> String -> IO (Maybe HValue)
1912 compileExpr s expr = withSession s $ \hsc_env -> do
1913 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1915 Nothing -> return Nothing
1916 Just (new_ic, names, hval) -> do
1918 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1920 case (names,hvals) of
1921 ([n],[hv]) -> return (Just hv)
1922 _ -> panic "compileExpr"
1924 -- -----------------------------------------------------------------------------
1925 -- running a statement interactively
1928 = RunOk [Name] -- ^ names bound by this evaluation
1929 | RunFailed -- ^ statement failed compilation
1930 | RunException Exception -- ^ statement raised an exception
1932 -- | Run a statement in the current interactive context. Statemenet
1933 -- may bind multple values.
1934 runStmt :: Session -> String -> IO RunResult
1935 runStmt (Session ref) expr
1937 hsc_env <- readIORef ref
1939 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1940 -- warnings about the implicit bindings we introduce.
1941 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1942 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1944 maybe_stuff <- hscStmt hsc_env' expr
1947 Nothing -> return RunFailed
1948 Just (new_hsc_env, names, hval) -> do
1950 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1951 either_hvals <- sandboxIO thing_to_run
1953 case either_hvals of
1955 -- on error, keep the *old* interactive context,
1956 -- so that 'it' is not bound to something
1957 -- that doesn't exist.
1958 return (RunException e)
1961 -- Get the newly bound things, and bind them.
1962 -- Don't need to delete any shadowed bindings;
1963 -- the new ones override the old ones.
1964 extendLinkEnv (zip names hvals)
1966 writeIORef ref new_hsc_env
1967 return (RunOk names)
1970 -- We run the statement in a "sandbox" to protect the rest of the
1971 -- system from anything the expression might do. For now, this
1972 -- consists of just wrapping it in an exception handler, but see below
1973 -- for another version.
1975 sandboxIO :: IO a -> IO (Either Exception a)
1976 sandboxIO thing = Exception.try thing
1979 -- This version of sandboxIO runs the expression in a completely new
1980 -- RTS main thread. It is disabled for now because ^C exceptions
1981 -- won't be delivered to the new thread, instead they'll be delivered
1982 -- to the (blocked) GHCi main thread.
1984 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1986 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1987 sandboxIO thing = do
1988 st_thing <- newStablePtr (Exception.try thing)
1989 alloca $ \ p_st_result -> do
1990 stat <- rts_evalStableIO st_thing p_st_result
1991 freeStablePtr st_thing
1993 then do st_result <- peek p_st_result
1994 result <- deRefStablePtr st_result
1995 freeStablePtr st_result
1996 return (Right result)
1998 return (Left (fromIntegral stat))
2000 foreign import "rts_evalStableIO" {- safe -}
2001 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2002 -- more informative than the C type!
2005 -----------------------------------------------------------------------------
2006 -- show a module and it's source/object filenames
2008 showModule :: Session -> ModSummary -> IO String
2009 showModule s mod_summary = withSession s $ \hsc_env -> do
2010 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
2011 Nothing -> panic "missing linkable"
2012 Just mod_info -> return (showModMsg obj_linkable mod_summary)
2014 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))