1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18 GhcMode(..), GhcLink(..), defaultObjectTarget,
25 Target(..), TargetId(..), Phase,
32 -- * Extending the program scope
33 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
34 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
35 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
36 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
38 -- * Loading\/compiling the program
40 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
41 workingDirectoryChanged,
42 checkModule, CheckedModule(..),
43 TypecheckedSource, ParsedSource, RenamedSource,
46 -- * Parsing Haddock comments
49 -- * Inspecting the module structure of the program
50 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
55 -- * Inspecting modules
60 modInfoPrintUnqualified,
63 modInfoIsExportedName,
68 PrintUnqualified, alwaysQualify,
70 -- * Interactive evaluation
71 getBindings, getPrintUnqual,
74 setContext, getContext,
83 runStmt, SingleStep(..),
85 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
86 resumeHistory, resumeHistoryIx),
87 History(historyBreakInfo), getHistorySpan,
91 InteractiveEval.forward,
94 compileExpr, HValue, dynCompileExpr,
96 obtainTerm, obtainTerm1,
98 ModBreaks(..), BreakIndex,
99 BreakInfo(breakInfo_number, breakInfo_module),
100 BreakArray, setBreakOn, setBreakOff, getBreak,
103 -- * Abstract syntax elements
109 Module, mkModule, pprModule, moduleName, modulePackageId,
110 ModuleName, mkModuleName, moduleNameString,
114 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
116 RdrName(Qual,Unqual),
120 isImplicitId, isDeadBinder,
121 isExportedId, isLocalId, isGlobalId,
123 isPrimOpId, isFCallId, isClassOpId_maybe,
124 isDataConWorkId, idDataCon,
125 isBottomingId, isDictonaryId,
126 recordSelectorFieldLabel,
128 -- ** Type constructors
130 tyConTyVars, tyConDataCons, tyConArity,
131 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
133 synTyConDefn, synTyConType, synTyConResKind,
139 -- ** Data constructors
141 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
142 dataConIsInfix, isVanillaDataCon,
144 StrictnessMark(..), isMarkedStrict,
148 classMethods, classSCTheta, classTvsFds,
153 instanceDFunId, pprInstance, pprInstanceHdr,
155 -- ** Types and Kinds
156 Type, dropForAlls, splitForAllTys, funResultTy,
157 pprParendType, pprTypeApp,
160 ThetaType, pprThetaArrow,
166 module HsSyn, -- ToDo: remove extraneous bits
170 defaultFixity, maxPrecedence,
174 -- ** Source locations
176 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
177 srcLocFile, srcLocLine, srcLocCol,
179 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
180 srcSpanStart, srcSpanEnd,
182 srcSpanStartLine, srcSpanEndLine,
183 srcSpanStartCol, srcSpanEndCol,
186 GhcException(..), showGhcException,
196 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
197 * what StaticFlags should we expose, if any?
200 #include "HsVersions.h"
203 import qualified Linker
204 import Linker ( HValue )
209 import InteractiveEval
216 import Type hiding (typeKind)
217 import TcType hiding (typeKind)
219 import Var hiding (setIdType)
220 import TysPrim ( alphaTyVars )
225 import Name hiding ( varName )
226 import OccName ( parenSymOcc )
227 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
231 import TcRnDriver ( tcRnModule )
232 import DriverPipeline
233 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
234 import HeaderInfo ( getImports, getOptions )
236 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
240 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
250 import Bag ( unitBag, listToBag )
251 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
252 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
254 import qualified ErrUtils
256 import StringBuffer ( StringBuffer, hGetStringBuffer )
259 import Maybes ( expectJust, mapCatMaybes )
261 import HaddockLex ( tokenise )
263 import Control.Concurrent
264 import System.Directory ( getModificationTime, doesFileExist )
267 import qualified Data.List as List
269 import System.Exit ( exitWith, ExitCode(..) )
270 import System.Time ( ClockTime )
271 import Control.Exception as Exception hiding (handle)
274 import System.IO.Error ( try, isDoesNotExistError )
275 import Prelude hiding (init)
278 -- -----------------------------------------------------------------------------
279 -- Exception handlers
281 -- | Install some default exception handlers and run the inner computation.
282 -- Unless you want to handle exceptions yourself, you should wrap this around
283 -- the top level of your program. The default handlers output the error
284 -- message(s) to stderr and exit cleanly.
285 defaultErrorHandler :: DynFlags -> IO a -> IO a
286 defaultErrorHandler dflags inner =
287 -- top-level exception handler: any unrecognised exception is a compiler bug.
288 handle (\exception -> do
291 -- an IO exception probably isn't our fault, so don't panic
293 fatalErrorMsg dflags (text (show exception))
294 AsyncException StackOverflow ->
295 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
297 fatalErrorMsg dflags (text (show (Panic (show exception))))
298 exitWith (ExitFailure 1)
301 -- program errors: messages with locations attached. Sometimes it is
302 -- convenient to just throw these as exceptions.
303 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
304 exitWith (ExitFailure 1)) $
306 -- error messages propagated as exceptions
307 handleDyn (\dyn -> do
310 PhaseFailed _ code -> exitWith code
311 Interrupted -> exitWith (ExitFailure 1)
312 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
313 exitWith (ExitFailure 1)
317 -- | Install a default cleanup handler to remove temporary files
318 -- deposited by a GHC run. This is seperate from
319 -- 'defaultErrorHandler', because you might want to override the error
320 -- handling, but still get the ordinary cleanup behaviour.
321 defaultCleanupHandler :: DynFlags -> IO a -> IO a
322 defaultCleanupHandler dflags inner =
323 -- make sure we clean up after ourselves
324 later (do cleanTempFiles dflags
327 -- exceptions will be blocked while we clean the temporary files,
328 -- so there shouldn't be any difficulty if we receive further
333 -- | Starts a new session. A session consists of a set of loaded
334 -- modules, a set of options (DynFlags), and an interactive context.
335 newSession :: Maybe FilePath -> IO Session
336 newSession mb_top_dir = do
338 main_thread <- myThreadId
339 modifyMVar_ interruptTargetThread (return . (main_thread :))
340 installSignalHandlers
343 dflags0 <- initSysTools mb_top_dir defaultDynFlags
344 dflags <- initDynFlags dflags0
345 env <- newHscEnv dflags
349 -- tmp: this breaks the abstraction, but required because DriverMkDepend
350 -- needs to call the Finder. ToDo: untangle this.
351 sessionHscEnv :: Session -> IO HscEnv
352 sessionHscEnv (Session ref) = readIORef ref
354 -- -----------------------------------------------------------------------------
357 -- | Grabs the DynFlags from the Session
358 getSessionDynFlags :: Session -> IO DynFlags
359 getSessionDynFlags s = withSession s (return . hsc_dflags)
361 -- | Updates the DynFlags in a Session. This also reads
362 -- the package database (unless it has already been read),
363 -- and prepares the compilers knowledge about packages. It
364 -- can be called again to load new packages: just add new
365 -- package flags to (packageFlags dflags).
367 -- Returns a list of new packages that may need to be linked in using
368 -- the dynamic linker (see 'linkPackages') as a result of new package
369 -- flags. If you are not doing linking or doing static linking, you
370 -- can ignore the list of packages returned.
372 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
373 setSessionDynFlags (Session ref) dflags = do
374 hsc_env <- readIORef ref
375 (dflags', preload) <- initPackages dflags
376 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
379 -- | If there is no -o option, guess the name of target executable
380 -- by using top-level source file name as a base.
381 guessOutputFile :: Session -> IO ()
382 guessOutputFile s = modifySession s $ \env ->
383 let dflags = hsc_dflags env
384 mod_graph = hsc_mod_graph env
385 mainModuleSrcPath, guessedName :: Maybe String
386 mainModuleSrcPath = do
387 let isMain = (== mainModIs dflags) . ms_mod
388 [ms] <- return (filter isMain mod_graph)
389 ml_hs_file (ms_location ms)
390 guessedName = fmap basenameOf mainModuleSrcPath
392 case outputFile dflags of
394 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
396 -- -----------------------------------------------------------------------------
399 -- ToDo: think about relative vs. absolute file paths. And what
400 -- happens when the current directory changes.
402 -- | Sets the targets for this session. Each target may be a module name
403 -- or a filename. The targets correspond to the set of root modules for
404 -- the program\/library. Unloading the current program is achieved by
405 -- setting the current set of targets to be empty, followed by load.
406 setTargets :: Session -> [Target] -> IO ()
407 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
409 -- | returns the current set of targets
410 getTargets :: Session -> IO [Target]
411 getTargets s = withSession s (return . hsc_targets)
413 -- | Add another target
414 addTarget :: Session -> Target -> IO ()
416 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
419 removeTarget :: Session -> TargetId -> IO ()
420 removeTarget s target_id
421 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
423 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
425 -- Attempts to guess what Target a string refers to. This function implements
426 -- the --make/GHCi command-line syntax for filenames:
428 -- - if the string looks like a Haskell source filename, then interpret
430 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
432 -- - otherwise interpret the string as a module name
434 guessTarget :: String -> Maybe Phase -> IO Target
435 guessTarget file (Just phase)
436 = return (Target (TargetFile file (Just phase)) Nothing)
437 guessTarget file Nothing
438 | isHaskellSrcFilename file
439 = return (Target (TargetFile file Nothing) Nothing)
441 = do exists <- doesFileExist hs_file
443 then return (Target (TargetFile hs_file Nothing) Nothing)
445 exists <- doesFileExist lhs_file
447 then return (Target (TargetFile lhs_file Nothing) Nothing)
449 return (Target (TargetModule (mkModuleName file)) Nothing)
451 hs_file = file `joinFileExt` "hs"
452 lhs_file = file `joinFileExt` "lhs"
454 -- -----------------------------------------------------------------------------
455 -- Extending the program scope
457 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
458 extendGlobalRdrScope session rdrElts
459 = modifySession session $ \hscEnv ->
460 let global_rdr = hsc_global_rdr_env hscEnv
461 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
463 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
464 setGlobalRdrScope session rdrElts
465 = modifySession session $ \hscEnv ->
466 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
468 extendGlobalTypeScope :: Session -> [Id] -> IO ()
469 extendGlobalTypeScope session ids
470 = modifySession session $ \hscEnv ->
471 let global_type = hsc_global_type_env hscEnv
472 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
474 setGlobalTypeScope :: Session -> [Id] -> IO ()
475 setGlobalTypeScope session ids
476 = modifySession session $ \hscEnv ->
477 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
479 -- -----------------------------------------------------------------------------
480 -- Parsing Haddock comments
482 parseHaddockComment :: String -> Either String (HsDoc RdrName)
483 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
485 -- -----------------------------------------------------------------------------
486 -- Loading the program
488 -- Perform a dependency analysis starting from the current targets
489 -- and update the session with the new module graph.
490 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
491 depanal (Session ref) excluded_mods allow_dup_roots = do
492 hsc_env <- readIORef ref
494 dflags = hsc_dflags hsc_env
495 targets = hsc_targets hsc_env
496 old_graph = hsc_mod_graph hsc_env
498 showPass dflags "Chasing dependencies"
499 debugTraceMsg dflags 2 (hcat [
500 text "Chasing modules from: ",
501 hcat (punctuate comma (map pprTarget targets))])
503 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
505 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
510 -- | The result of load.
512 = LoadOk Errors -- ^ all specified targets were loaded successfully.
513 | LoadFailed Errors -- ^ not all modules were loaded.
515 type Errors = [String]
517 data ErrMsg = ErrMsg {
518 errMsgSeverity :: Severity, -- warning, error, etc.
519 errMsgSpans :: [SrcSpan],
520 errMsgShortDoc :: Doc,
521 errMsgExtraInfo :: Doc
527 | LoadUpTo ModuleName
528 | LoadDependenciesOf ModuleName
530 -- | Try to load the program. If a Module is supplied, then just
531 -- attempt to load up to this target. If no Module is supplied,
532 -- then try to load all targets.
533 load :: Session -> LoadHowMuch -> IO SuccessFlag
534 load s@(Session ref) how_much
536 -- Dependency analysis first. Note that this fixes the module graph:
537 -- even if we don't get a fully successful upsweep, the full module
538 -- graph is still retained in the Session. We can tell which modules
539 -- were successfully loaded by inspecting the Session's HPT.
540 mb_graph <- depanal s [] False
542 Just mod_graph -> load2 s how_much mod_graph
543 Nothing -> return Failed
545 load2 s@(Session ref) how_much mod_graph = do
547 hsc_env <- readIORef ref
549 let hpt1 = hsc_HPT hsc_env
550 let dflags = hsc_dflags hsc_env
552 -- The "bad" boot modules are the ones for which we have
553 -- B.hs-boot in the module graph, but no B.hs
554 -- The downsweep should have ensured this does not happen
556 let all_home_mods = [ms_mod_name s
557 | s <- mod_graph, not (isBootSummary s)]
559 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
560 not (ms_mod_name s `elem` all_home_mods)]
562 ASSERT( null bad_boot_mods ) return ()
564 -- mg2_with_srcimps drops the hi-boot nodes, returning a
565 -- graph with cycles. Among other things, it is used for
566 -- backing out partially complete cycles following a failed
567 -- upsweep, and for removing from hpt all the modules
568 -- not in strict downwards closure, during calls to compile.
569 let mg2_with_srcimps :: [SCC ModSummary]
570 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
572 -- If we can determine that any of the {-# SOURCE #-} imports
573 -- are definitely unnecessary, then emit a warning.
574 warnUnnecessarySourceImports dflags mg2_with_srcimps
577 -- check the stability property for each module.
578 stable_mods@(stable_obj,stable_bco)
579 = checkStability hpt1 mg2_with_srcimps all_home_mods
581 -- prune bits of the HPT which are definitely redundant now,
583 pruned_hpt = pruneHomePackageTable hpt1
584 (flattenSCCs mg2_with_srcimps)
589 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
590 text "Stable BCO:" <+> ppr stable_bco)
592 -- Unload any modules which are going to be re-linked this time around.
593 let stable_linkables = [ linkable
594 | m <- stable_obj++stable_bco,
595 Just hmi <- [lookupUFM pruned_hpt m],
596 Just linkable <- [hm_linkable hmi] ]
597 unload hsc_env stable_linkables
599 -- We could at this point detect cycles which aren't broken by
600 -- a source-import, and complain immediately, but it seems better
601 -- to let upsweep_mods do this, so at least some useful work gets
602 -- done before the upsweep is abandoned.
603 --hPutStrLn stderr "after tsort:\n"
604 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
606 -- Now do the upsweep, calling compile for each module in
607 -- turn. Final result is version 3 of everything.
609 -- Topologically sort the module graph, this time including hi-boot
610 -- nodes, and possibly just including the portion of the graph
611 -- reachable from the module specified in the 2nd argument to load.
612 -- This graph should be cycle-free.
613 -- If we're restricting the upsweep to a portion of the graph, we
614 -- also want to retain everything that is still stable.
615 let full_mg :: [SCC ModSummary]
616 full_mg = topSortModuleGraph False mod_graph Nothing
618 maybe_top_mod = case how_much of
620 LoadDependenciesOf m -> Just m
623 partial_mg0 :: [SCC ModSummary]
624 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
626 -- LoadDependenciesOf m: we want the upsweep to stop just
627 -- short of the specified module (unless the specified module
630 | LoadDependenciesOf mod <- how_much
631 = ASSERT( case last partial_mg0 of
632 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
633 List.init partial_mg0
639 | AcyclicSCC ms <- full_mg,
640 ms_mod_name ms `elem` stable_obj++stable_bco,
641 ms_mod_name ms `notElem` [ ms_mod_name ms' |
642 AcyclicSCC ms' <- partial_mg ] ]
644 mg = stable_mg ++ partial_mg
646 -- clean up between compilations
647 let cleanup = cleanTempFilesExcept dflags
648 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
650 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
652 (upsweep_ok, hsc_env1, modsUpswept)
653 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
654 pruned_hpt stable_mods cleanup mg
656 -- Make modsDone be the summaries for each home module now
657 -- available; this should equal the domain of hpt3.
658 -- Get in in a roughly top .. bottom order (hence reverse).
660 let modsDone = reverse modsUpswept
662 -- Try and do linking in some form, depending on whether the
663 -- upsweep was completely or only partially successful.
665 if succeeded upsweep_ok
668 -- Easy; just relink it all.
669 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
671 -- Clean up after ourselves
672 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
674 -- Issue a warning for the confusing case where the user
675 -- said '-o foo' but we're not going to do any linking.
676 -- We attempt linking if either (a) one of the modules is
677 -- called Main, or (b) the user said -no-hs-main, indicating
678 -- that main() is going to come from somewhere else.
680 let ofile = outputFile dflags
681 let no_hs_main = dopt Opt_NoHsMain dflags
683 main_mod = mainModIs dflags
684 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
685 do_linking = a_root_is_Main || no_hs_main
687 when (ghcLink dflags == LinkBinary
688 && isJust ofile && not do_linking) $
689 debugTraceMsg dflags 1 $
690 text ("Warning: output was redirected with -o, " ++
691 "but no output will be generated\n" ++
692 "because there is no " ++
693 moduleNameString (moduleName main_mod) ++ " module.")
695 -- link everything together
696 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
698 loadFinish Succeeded linkresult ref hsc_env1
701 -- Tricky. We need to back out the effects of compiling any
702 -- half-done cycles, both so as to clean up the top level envs
703 -- and to avoid telling the interactive linker to link them.
704 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
707 = map ms_mod modsDone
708 let mods_to_zap_names
709 = findPartiallyCompletedCycles modsDone_names
712 = filter ((`notElem` mods_to_zap_names).ms_mod)
715 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
718 -- Clean up after ourselves
719 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
721 -- there should be no Nothings where linkables should be, now
722 ASSERT(all (isJust.hm_linkable)
723 (eltsUFM (hsc_HPT hsc_env))) do
725 -- Link everything together
726 linkresult <- link (ghcLink dflags) dflags False hpt4
728 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
729 loadFinish Failed linkresult ref hsc_env4
731 -- Finish up after a load.
733 -- If the link failed, unload everything and return.
734 loadFinish all_ok Failed ref hsc_env
735 = do unload hsc_env []
736 writeIORef ref $! discardProg hsc_env
739 -- Empty the interactive context and set the module context to the topmost
740 -- newly loaded module, or the Prelude if none were loaded.
741 loadFinish all_ok Succeeded ref hsc_env
742 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
746 -- Forget the current program, but retain the persistent info in HscEnv
747 discardProg :: HscEnv -> HscEnv
749 = hsc_env { hsc_mod_graph = emptyMG,
750 hsc_IC = emptyInteractiveContext,
751 hsc_HPT = emptyHomePackageTable }
753 -- used to fish out the preprocess output files for the purposes of
754 -- cleaning up. The preprocessed file *might* be the same as the
755 -- source file, but that doesn't do any harm.
756 ppFilesFromSummaries summaries = map ms_hspp_file summaries
758 -- -----------------------------------------------------------------------------
762 CheckedModule { parsedSource :: ParsedSource,
763 renamedSource :: Maybe RenamedSource,
764 typecheckedSource :: Maybe TypecheckedSource,
765 checkedModuleInfo :: Maybe ModuleInfo
767 -- ToDo: improvements that could be made here:
768 -- if the module succeeded renaming but not typechecking,
769 -- we can still get back the GlobalRdrEnv and exports, so
770 -- perhaps the ModuleInfo should be split up into separate
771 -- fields within CheckedModule.
773 type ParsedSource = Located (HsModule RdrName)
774 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
775 Maybe (HsDoc Name), HaddockModInfo Name)
776 type TypecheckedSource = LHsBinds Id
779 -- - things that aren't in the output of the typechecker right now:
783 -- - type/data/newtype declarations
784 -- - class declarations
786 -- - extra things in the typechecker's output:
787 -- - default methods are turned into top-level decls.
788 -- - dictionary bindings
791 -- | This is the way to get access to parsed and typechecked source code
792 -- for a module. 'checkModule' loads all the dependencies of the specified
793 -- module in the Session, and then attempts to typecheck the module. If
794 -- successful, it returns the abstract syntax for the module.
795 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
796 checkModule session@(Session ref) mod = do
797 -- load up the dependencies first
798 r <- load session (LoadDependenciesOf mod)
799 if (failed r) then return Nothing else do
801 -- now parse & typecheck the module
802 hsc_env <- readIORef ref
803 let mg = hsc_mod_graph hsc_env
804 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
807 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
809 Nothing -> return Nothing
810 Just (HscChecked parsed renamed Nothing) ->
811 return (Just (CheckedModule {
812 parsedSource = parsed,
813 renamedSource = renamed,
814 typecheckedSource = Nothing,
815 checkedModuleInfo = Nothing }))
816 Just (HscChecked parsed renamed
817 (Just (tc_binds, rdr_env, details))) -> do
818 let minf = ModuleInfo {
819 minf_type_env = md_types details,
820 minf_exports = availsToNameSet $
822 minf_rdr_env = Just rdr_env,
823 minf_instances = md_insts details
825 ,minf_modBreaks = emptyModBreaks
828 return (Just (CheckedModule {
829 parsedSource = parsed,
830 renamedSource = renamed,
831 typecheckedSource = Just tc_binds,
832 checkedModuleInfo = Just minf }))
834 -- | This is the way to get access to the Core bindings corresponding
835 -- to a module. 'compileToCore' first invokes 'checkModule' to parse and
836 -- typecheck the module, then desugars it and returns the resulting list
837 -- of Core bindings if successful.
838 compileToCore :: Session -> ModuleName -> FilePath -> IO (Maybe [CoreBind])
839 compileToCore session@(Session ref) mod fn = do
840 hsc_env <- readIORef ref
841 maybeCheckedModule <- checkModule session mod
842 case maybeCheckedModule of
843 Nothing -> return Nothing
844 Just checkedMod -> do
845 let parsedMod = parsedSource checkedMod
846 -- Note: this typechecks the module twice (because checkModule
847 -- also calls tcRnModule), but arranging for checkModule to
848 -- return the type env would require changing a lot of data
849 -- structures, so I'm leaving it like that for now.
850 (_, maybe_tc_result) <- tcRnModule hsc_env HsSrcFile False parsedMod
851 case maybe_tc_result of
852 -- TODO: this ignores the type error messages and just returns Nothing
853 Nothing -> return Nothing
855 let dflags = hsc_dflags hsc_env
856 location <- mkHomeModLocation dflags mod fn
857 maybeModGuts <- deSugar hsc_env location tcgEnv
859 Nothing -> return Nothing
860 Just mg -> return $ Just $ mg_binds mg
861 -- ---------------------------------------------------------------------------
864 unload :: HscEnv -> [Linkable] -> IO ()
865 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
866 = case ghcLink (hsc_dflags hsc_env) of
868 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
870 LinkInMemory -> panic "unload: no interpreter"
874 -- -----------------------------------------------------------------------------
878 Stability tells us which modules definitely do not need to be recompiled.
879 There are two main reasons for having stability:
881 - avoid doing a complete upsweep of the module graph in GHCi when
882 modules near the bottom of the tree have not changed.
884 - to tell GHCi when it can load object code: we can only load object code
885 for a module when we also load object code fo all of the imports of the
886 module. So we need to know that we will definitely not be recompiling
887 any of these modules, and we can use the object code.
889 The stability check is as follows. Both stableObject and
890 stableBCO are used during the upsweep phase later.
893 stable m = stableObject m || stableBCO m
896 all stableObject (imports m)
897 && old linkable does not exist, or is == on-disk .o
898 && date(on-disk .o) > date(.hs)
901 all stable (imports m)
902 && date(BCO) > date(.hs)
905 These properties embody the following ideas:
907 - if a module is stable, then:
908 - if it has been compiled in a previous pass (present in HPT)
909 then it does not need to be compiled or re-linked.
910 - if it has not been compiled in a previous pass,
911 then we only need to read its .hi file from disk and
912 link it to produce a ModDetails.
914 - if a modules is not stable, we will definitely be at least
915 re-linking, and possibly re-compiling it during the upsweep.
916 All non-stable modules can (and should) therefore be unlinked
919 - Note that objects are only considered stable if they only depend
920 on other objects. We can't link object code against byte code.
924 :: HomePackageTable -- HPT from last compilation
925 -> [SCC ModSummary] -- current module graph (cyclic)
926 -> [ModuleName] -- all home modules
927 -> ([ModuleName], -- stableObject
928 [ModuleName]) -- stableBCO
930 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
932 checkSCC (stable_obj, stable_bco) scc0
933 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
934 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
935 | otherwise = (stable_obj, stable_bco)
937 scc = flattenSCC scc0
938 scc_mods = map ms_mod_name scc
939 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
941 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
942 -- all imports outside the current SCC, but in the home pkg
944 stable_obj_imps = map (`elem` stable_obj) scc_allimps
945 stable_bco_imps = map (`elem` stable_bco) scc_allimps
952 and (zipWith (||) stable_obj_imps stable_bco_imps)
956 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
960 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
961 Just hmi | Just l <- hm_linkable hmi
962 -> isObjectLinkable l && t == linkableTime l
964 -- why '>=' rather than '>' above? If the filesystem stores
965 -- times to the nearset second, we may occasionally find that
966 -- the object & source have the same modification time,
967 -- especially if the source was automatically generated
968 -- and compiled. Using >= is slightly unsafe, but it matches
972 = case lookupUFM hpt (ms_mod_name ms) of
973 Just hmi | Just l <- hm_linkable hmi ->
974 not (isObjectLinkable l) &&
975 linkableTime l >= ms_hs_date ms
978 ms_allimps :: ModSummary -> [ModuleName]
979 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
981 -- -----------------------------------------------------------------------------
982 -- Prune the HomePackageTable
984 -- Before doing an upsweep, we can throw away:
986 -- - For non-stable modules:
987 -- - all ModDetails, all linked code
988 -- - all unlinked code that is out of date with respect to
991 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
992 -- space at the end of the upsweep, because the topmost ModDetails of the
993 -- old HPT holds on to the entire type environment from the previous
996 pruneHomePackageTable
999 -> ([ModuleName],[ModuleName])
1002 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1005 | is_stable modl = hmi'
1006 | otherwise = hmi'{ hm_details = emptyModDetails }
1008 modl = moduleName (mi_module (hm_iface hmi))
1009 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1010 = hmi{ hm_linkable = Nothing }
1013 where ms = expectJust "prune" (lookupUFM ms_map modl)
1015 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1017 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1019 -- -----------------------------------------------------------------------------
1021 -- Return (names of) all those in modsDone who are part of a cycle
1022 -- as defined by theGraph.
1023 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1024 findPartiallyCompletedCycles modsDone theGraph
1028 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1029 chew ((CyclicSCC vs):rest)
1030 = let names_in_this_cycle = nub (map ms_mod vs)
1032 = nub ([done | done <- modsDone,
1033 done `elem` names_in_this_cycle])
1034 chewed_rest = chew rest
1036 if notNull mods_in_this_cycle
1037 && length mods_in_this_cycle < length names_in_this_cycle
1038 then mods_in_this_cycle ++ chewed_rest
1041 -- -----------------------------------------------------------------------------
1044 -- This is where we compile each module in the module graph, in a pass
1045 -- from the bottom to the top of the graph.
1047 -- There better had not be any cyclic groups here -- we check for them.
1050 :: HscEnv -- Includes initially-empty HPT
1051 -> HomePackageTable -- HPT from last time round (pruned)
1052 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1053 -> IO () -- How to clean up unwanted tmp files
1054 -> [SCC ModSummary] -- Mods to do (the worklist)
1056 HscEnv, -- With an updated HPT
1057 [ModSummary]) -- Mods which succeeded
1059 upsweep hsc_env old_hpt stable_mods cleanup mods
1060 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1062 upsweep' hsc_env old_hpt stable_mods cleanup
1064 = return (Succeeded, hsc_env, [])
1066 upsweep' hsc_env old_hpt stable_mods cleanup
1067 (CyclicSCC ms:_) _ _
1068 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1069 return (Failed, hsc_env, [])
1071 upsweep' hsc_env old_hpt stable_mods cleanup
1072 (AcyclicSCC mod:mods) mod_index nmods
1073 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1074 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1075 -- (moduleEnvElts (hsc_HPT hsc_env)))
1077 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1080 cleanup -- Remove unwanted tmp files between compilations
1083 Nothing -> return (Failed, hsc_env, [])
1085 { let this_mod = ms_mod_name mod
1087 -- Add new info to hsc_env
1088 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1089 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1091 -- Space-saving: delete the old HPT entry
1092 -- for mod BUT if mod is a hs-boot
1093 -- node, don't delete it. For the
1094 -- interface, the HPT entry is probaby for the
1095 -- main Haskell source file. Deleting it
1096 -- would force .. (what?? --SDM)
1097 old_hpt1 | isBootSummary mod = old_hpt
1098 | otherwise = delFromUFM old_hpt this_mod
1100 ; (restOK, hsc_env2, modOKs)
1101 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1102 mods (mod_index+1) nmods
1103 ; return (restOK, hsc_env2, mod:modOKs)
1107 -- Compile a single module. Always produce a Linkable for it if
1108 -- successful. If no compilation happened, return the old Linkable.
1109 upsweep_mod :: HscEnv
1111 -> ([ModuleName],[ModuleName])
1113 -> Int -- index of module
1114 -> Int -- total number of modules
1115 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1117 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1119 this_mod_name = ms_mod_name summary
1120 this_mod = ms_mod summary
1121 mb_obj_date = ms_obj_date summary
1122 obj_fn = ml_obj_file (ms_location summary)
1123 hs_date = ms_hs_date summary
1125 is_stable_obj = this_mod_name `elem` stable_obj
1126 is_stable_bco = this_mod_name `elem` stable_bco
1128 old_hmi = lookupUFM old_hpt this_mod_name
1130 -- We're using the dflags for this module now, obtained by
1131 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1132 dflags = ms_hspp_opts summary
1133 prevailing_target = hscTarget (hsc_dflags hsc_env)
1134 local_target = hscTarget dflags
1136 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1137 -- we don't do anything dodgy: these should only work to change
1138 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1139 -- end up trying to link object code to byte code.
1140 target = if prevailing_target /= local_target
1141 && (not (isObjectTarget prevailing_target)
1142 || not (isObjectTarget local_target))
1143 then prevailing_target
1146 -- store the corrected hscTarget into the summary
1147 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1149 -- The old interface is ok if
1150 -- a) we're compiling a source file, and the old HPT
1151 -- entry is for a source file
1152 -- b) we're compiling a hs-boot file
1153 -- Case (b) allows an hs-boot file to get the interface of its
1154 -- real source file on the second iteration of the compilation
1155 -- manager, but that does no harm. Otherwise the hs-boot file
1156 -- will always be recompiled
1161 Just hm_info | isBootSummary summary -> Just iface
1162 | not (mi_boot iface) -> Just iface
1163 | otherwise -> Nothing
1165 iface = hm_iface hm_info
1167 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1168 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1169 summary' mod_index nmods mb_old_iface
1171 compile_it_discard_iface
1172 = upsweep_compile hsc_env old_hpt this_mod_name
1173 summary' mod_index nmods Nothing
1179 -- Regardless of whether we're generating object code or
1180 -- byte code, we can always use an existing object file
1181 -- if it is *stable* (see checkStability).
1182 | is_stable_obj, isJust old_hmi ->
1184 -- object is stable, and we have an entry in the
1185 -- old HPT: nothing to do
1187 | is_stable_obj, isNothing old_hmi -> do
1188 linkable <- findObjectLinkable this_mod obj_fn
1189 (expectJust "upseep1" mb_obj_date)
1190 compile_it (Just linkable)
1191 -- object is stable, but we need to load the interface
1192 -- off disk to make a HMI.
1196 ASSERT(isJust old_hmi) -- must be in the old_hpt
1198 -- BCO is stable: nothing to do
1200 | Just hmi <- old_hmi,
1201 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1202 linkableTime l >= ms_hs_date summary ->
1204 -- we have an old BCO that is up to date with respect
1205 -- to the source: do a recompilation check as normal.
1209 -- no existing code at all: we must recompile.
1211 -- When generating object code, if there's an up-to-date
1212 -- object file on the disk, then we can use it.
1213 -- However, if the object file is new (compared to any
1214 -- linkable we had from a previous compilation), then we
1215 -- must discard any in-memory interface, because this
1216 -- means the user has compiled the source file
1217 -- separately and generated a new interface, that we must
1218 -- read from the disk.
1220 obj | isObjectTarget obj,
1221 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1224 | Just l <- hm_linkable hmi,
1225 isObjectLinkable l && linkableTime l == obj_date
1226 -> compile_it (Just l)
1228 linkable <- findObjectLinkable this_mod obj_fn obj_date
1229 compile_it_discard_iface (Just linkable)
1235 -- Run hsc to compile a module
1236 upsweep_compile hsc_env old_hpt this_mod summary
1241 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1245 -- Compilation failed. Compile may still have updated the PCS, tho.
1246 CompErrs -> return Nothing
1248 -- Compilation "succeeded", and may or may not have returned a new
1249 -- linkable (depending on whether compilation was actually performed
1251 CompOK new_details new_iface new_linkable
1252 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1253 hm_details = new_details,
1254 hm_linkable = new_linkable }
1255 return (Just new_info)
1258 -- Filter modules in the HPT
1259 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1260 retainInTopLevelEnvs keep_these hpt
1261 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1263 , let mb_mod_info = lookupUFM hpt mod
1264 , isJust mb_mod_info ]
1266 -- ---------------------------------------------------------------------------
1267 -- Topological sort of the module graph
1270 :: Bool -- Drop hi-boot nodes? (see below)
1274 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1275 -- The resulting list of strongly-connected-components is in topologically
1276 -- sorted order, starting with the module(s) at the bottom of the
1277 -- dependency graph (ie compile them first) and ending with the ones at
1280 -- Drop hi-boot nodes (first boolean arg)?
1282 -- False: treat the hi-boot summaries as nodes of the graph,
1283 -- so the graph must be acyclic
1285 -- True: eliminate the hi-boot nodes, and instead pretend
1286 -- the a source-import of Foo is an import of Foo
1287 -- The resulting graph has no hi-boot nodes, but can by cyclic
1289 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1290 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1291 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1292 = stronglyConnComp (map vertex_fn (reachable graph root))
1294 -- restrict the graph to just those modules reachable from
1295 -- the specified module. We do this by building a graph with
1296 -- the full set of nodes, and determining the reachable set from
1297 -- the specified node.
1298 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1299 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1301 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1302 | otherwise = throwDyn (ProgramError "module does not exist")
1304 moduleGraphNodes :: Bool -> [ModSummary]
1305 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1306 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1308 -- Drop hs-boot nodes by using HsSrcFile as the key
1309 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1310 | otherwise = HsBootFile
1312 -- We use integers as the keys for the SCC algorithm
1313 nodes :: [(ModSummary, Int, [Int])]
1314 nodes = [(s, expectJust "topSort" $
1315 lookup_key (ms_hsc_src s) (ms_mod_name s),
1316 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1317 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1318 (-- see [boot-edges] below
1319 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1321 else case lookup_key HsBootFile (ms_mod_name s) of
1326 , not (isBootSummary s && drop_hs_boot_nodes) ]
1327 -- Drop the hi-boot ones if told to do so
1329 -- [boot-edges] if this is a .hs and there is an equivalent
1330 -- .hs-boot, add a link from the former to the latter. This
1331 -- has the effect of detecting bogus cases where the .hs-boot
1332 -- depends on the .hs, by introducing a cycle. Additionally,
1333 -- it ensures that we will always process the .hs-boot before
1334 -- the .hs, and so the HomePackageTable will always have the
1335 -- most up to date information.
1337 key_map :: NodeMap Int
1338 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1342 lookup_key :: HscSource -> ModuleName -> Maybe Int
1343 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1345 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1346 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1347 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1348 -- the IsBootInterface parameter True; else False
1351 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1352 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1354 msKey :: ModSummary -> NodeKey
1355 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1357 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1358 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1360 nodeMapElts :: NodeMap a -> [a]
1361 nodeMapElts = eltsFM
1363 -- If there are {-# SOURCE #-} imports between strongly connected
1364 -- components in the topological sort, then those imports can
1365 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1366 -- were necessary, then the edge would be part of a cycle.
1367 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1368 warnUnnecessarySourceImports dflags sccs =
1369 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1371 let mods_in_this_cycle = map ms_mod_name ms in
1372 [ warn m i | m <- ms, i <- ms_srcimps m,
1373 unLoc i `notElem` mods_in_this_cycle ]
1375 warn :: ModSummary -> Located ModuleName -> WarnMsg
1376 warn ms (L loc mod) =
1378 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1379 <+> quotes (ppr mod))
1381 -----------------------------------------------------------------------------
1382 -- Downsweep (dependency analysis)
1384 -- Chase downwards from the specified root set, returning summaries
1385 -- for all home modules encountered. Only follow source-import
1388 -- We pass in the previous collection of summaries, which is used as a
1389 -- cache to avoid recalculating a module summary if the source is
1392 -- The returned list of [ModSummary] nodes has one node for each home-package
1393 -- module, plus one for any hs-boot files. The imports of these nodes
1394 -- are all there, including the imports of non-home-package modules.
1397 -> [ModSummary] -- Old summaries
1398 -> [ModuleName] -- Ignore dependencies on these; treat
1399 -- them as if they were package modules
1400 -> Bool -- True <=> allow multiple targets to have
1401 -- the same module name; this is
1402 -- very useful for ghc -M
1403 -> IO (Maybe [ModSummary])
1404 -- The elts of [ModSummary] all have distinct
1405 -- (Modules, IsBoot) identifiers, unless the Bool is true
1406 -- in which case there can be repeats
1407 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1408 = -- catch error messages and return them
1409 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1410 rootSummaries <- mapM getRootSummary roots
1411 let root_map = mkRootMap rootSummaries
1412 checkDuplicates root_map
1413 summs <- loop (concatMap msDeps rootSummaries) root_map
1416 roots = hsc_targets hsc_env
1418 old_summary_map :: NodeMap ModSummary
1419 old_summary_map = mkNodeMap old_summaries
1421 getRootSummary :: Target -> IO ModSummary
1422 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1423 = do exists <- doesFileExist file
1425 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1426 else throwDyn $ mkPlainErrMsg noSrcSpan $
1427 text "can't find file:" <+> text file
1428 getRootSummary (Target (TargetModule modl) maybe_buf)
1429 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1430 (L rootLoc modl) maybe_buf excl_mods
1431 case maybe_summary of
1432 Nothing -> packageModErr modl
1435 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1437 -- In a root module, the filename is allowed to diverge from the module
1438 -- name, so we have to check that there aren't multiple root files
1439 -- defining the same module (otherwise the duplicates will be silently
1440 -- ignored, leading to confusing behaviour).
1441 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1442 checkDuplicates root_map
1443 | allow_dup_roots = return ()
1444 | null dup_roots = return ()
1445 | otherwise = multiRootsErr (head dup_roots)
1447 dup_roots :: [[ModSummary]] -- Each at least of length 2
1448 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1450 loop :: [(Located ModuleName,IsBootInterface)]
1451 -- Work list: process these modules
1452 -> NodeMap [ModSummary]
1453 -- Visited set; the range is a list because
1454 -- the roots can have the same module names
1455 -- if allow_dup_roots is True
1457 -- The result includes the worklist, except
1458 -- for those mentioned in the visited set
1459 loop [] done = return (concat (nodeMapElts done))
1460 loop ((wanted_mod, is_boot) : ss) done
1461 | Just summs <- lookupFM done key
1462 = if isSingleton summs then
1465 do { multiRootsErr summs; return [] }
1466 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1467 is_boot wanted_mod Nothing excl_mods
1469 Nothing -> loop ss done
1470 Just s -> loop (msDeps s ++ ss)
1471 (addToFM done key [s]) }
1473 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1475 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1476 mkRootMap summaries = addListToFM_C (++) emptyFM
1477 [ (msKey s, [s]) | s <- summaries ]
1479 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1480 -- (msDeps s) returns the dependencies of the ModSummary s.
1481 -- A wrinkle is that for a {-# SOURCE #-} import we return
1482 -- *both* the hs-boot file
1483 -- *and* the source file
1484 -- as "dependencies". That ensures that the list of all relevant
1485 -- modules always contains B.hs if it contains B.hs-boot.
1486 -- Remember, this pass isn't doing the topological sort. It's
1487 -- just gathering the list of all relevant ModSummaries
1489 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1490 ++ [ (m,False) | m <- ms_imps s ]
1492 -----------------------------------------------------------------------------
1493 -- Summarising modules
1495 -- We have two types of summarisation:
1497 -- * Summarise a file. This is used for the root module(s) passed to
1498 -- cmLoadModules. The file is read, and used to determine the root
1499 -- module name. The module name may differ from the filename.
1501 -- * Summarise a module. We are given a module name, and must provide
1502 -- a summary. The finder is used to locate the file in which the module
1507 -> [ModSummary] -- old summaries
1508 -> FilePath -- source file name
1509 -> Maybe Phase -- start phase
1510 -> Maybe (StringBuffer,ClockTime)
1513 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1514 -- we can use a cached summary if one is available and the
1515 -- source file hasn't changed, But we have to look up the summary
1516 -- by source file, rather than module name as we do in summarise.
1517 | Just old_summary <- findSummaryBySourceFile old_summaries file
1519 let location = ms_location old_summary
1521 -- return the cached summary if the source didn't change
1522 src_timestamp <- case maybe_buf of
1523 Just (_,t) -> return t
1524 Nothing -> getModificationTime file
1525 -- The file exists; we checked in getRootSummary above.
1526 -- If it gets removed subsequently, then this
1527 -- getModificationTime may fail, but that's the right
1530 if ms_hs_date old_summary == src_timestamp
1531 then do -- update the object-file timestamp
1532 obj_timestamp <- getObjTimestamp location False
1533 return old_summary{ ms_obj_date = obj_timestamp }
1541 let dflags = hsc_dflags hsc_env
1543 (dflags', hspp_fn, buf)
1544 <- preprocessFile dflags file mb_phase maybe_buf
1546 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1548 -- Make a ModLocation for this file
1549 location <- mkHomeModLocation dflags mod_name file
1551 -- Tell the Finder cache where it is, so that subsequent calls
1552 -- to findModule will find it, even if it's not on any search path
1553 mod <- addHomeModuleToFinder hsc_env mod_name location
1555 src_timestamp <- case maybe_buf of
1556 Just (_,t) -> return t
1557 Nothing -> getModificationTime file
1558 -- getMofificationTime may fail
1560 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1562 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1563 ms_location = location,
1564 ms_hspp_file = hspp_fn,
1565 ms_hspp_opts = dflags',
1566 ms_hspp_buf = Just buf,
1567 ms_srcimps = srcimps, ms_imps = the_imps,
1568 ms_hs_date = src_timestamp,
1569 ms_obj_date = obj_timestamp })
1571 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1572 findSummaryBySourceFile summaries file
1573 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1574 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1578 -- Summarise a module, and pick up source and timestamp.
1581 -> NodeMap ModSummary -- Map of old summaries
1582 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1583 -> Located ModuleName -- Imported module to be summarised
1584 -> Maybe (StringBuffer, ClockTime)
1585 -> [ModuleName] -- Modules to exclude
1586 -> IO (Maybe ModSummary) -- Its new summary
1588 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1589 | wanted_mod `elem` excl_mods
1592 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1593 = do -- Find its new timestamp; all the
1594 -- ModSummaries in the old map have valid ml_hs_files
1595 let location = ms_location old_summary
1596 src_fn = expectJust "summariseModule" (ml_hs_file location)
1598 -- check the modification time on the source file, and
1599 -- return the cached summary if it hasn't changed. If the
1600 -- file has disappeared, we need to call the Finder again.
1602 Just (_,t) -> check_timestamp old_summary location src_fn t
1604 m <- System.IO.Error.try (getModificationTime src_fn)
1606 Right t -> check_timestamp old_summary location src_fn t
1607 Left e | isDoesNotExistError e -> find_it
1608 | otherwise -> ioError e
1610 | otherwise = find_it
1612 dflags = hsc_dflags hsc_env
1614 hsc_src = if is_boot then HsBootFile else HsSrcFile
1616 check_timestamp old_summary location src_fn src_timestamp
1617 | ms_hs_date old_summary == src_timestamp = do
1618 -- update the object-file timestamp
1619 obj_timestamp <- getObjTimestamp location is_boot
1620 return (Just old_summary{ ms_obj_date = obj_timestamp })
1622 -- source changed: re-summarise.
1623 new_summary location (ms_mod old_summary) src_fn src_timestamp
1626 -- Don't use the Finder's cache this time. If the module was
1627 -- previously a package module, it may have now appeared on the
1628 -- search path, so we want to consider it to be a home module. If
1629 -- the module was previously a home module, it may have moved.
1630 uncacheModule hsc_env wanted_mod
1631 found <- findImportedModule hsc_env wanted_mod Nothing
1634 | isJust (ml_hs_file location) ->
1636 just_found location mod
1638 -- Drop external-pkg
1639 ASSERT(modulePackageId mod /= thisPackage dflags)
1643 err -> noModError dflags loc wanted_mod err
1646 just_found location mod = do
1647 -- Adjust location to point to the hs-boot source file,
1648 -- hi file, object file, when is_boot says so
1649 let location' | is_boot = addBootSuffixLocn location
1650 | otherwise = location
1651 src_fn = expectJust "summarise2" (ml_hs_file location')
1653 -- Check that it exists
1654 -- It might have been deleted since the Finder last found it
1655 maybe_t <- modificationTimeIfExists src_fn
1657 Nothing -> noHsFileErr loc src_fn
1658 Just t -> new_summary location' mod src_fn t
1661 new_summary location mod src_fn src_timestamp
1663 -- Preprocess the source file and get its imports
1664 -- The dflags' contains the OPTIONS pragmas
1665 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1666 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1668 when (mod_name /= wanted_mod) $
1669 throwDyn $ mkPlainErrMsg mod_loc $
1670 text "file name does not match module name"
1671 <+> quotes (ppr mod_name)
1673 -- Find the object timestamp, and return the summary
1674 obj_timestamp <- getObjTimestamp location is_boot
1676 return (Just ( ModSummary { ms_mod = mod,
1677 ms_hsc_src = hsc_src,
1678 ms_location = location,
1679 ms_hspp_file = hspp_fn,
1680 ms_hspp_opts = dflags',
1681 ms_hspp_buf = Just buf,
1682 ms_srcimps = srcimps,
1684 ms_hs_date = src_timestamp,
1685 ms_obj_date = obj_timestamp }))
1688 getObjTimestamp location is_boot
1689 = if is_boot then return Nothing
1690 else modificationTimeIfExists (ml_obj_file location)
1693 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1694 -> IO (DynFlags, FilePath, StringBuffer)
1695 preprocessFile dflags src_fn mb_phase Nothing
1697 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1698 buf <- hGetStringBuffer hspp_fn
1699 return (dflags', hspp_fn, buf)
1701 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1703 -- case we bypass the preprocessing stage?
1705 local_opts = getOptions buf src_fn
1707 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1711 | Just (Unlit _) <- mb_phase = True
1712 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1713 -- note: local_opts is only required if there's no Unlit phase
1714 | dopt Opt_Cpp dflags' = True
1715 | dopt Opt_Pp dflags' = True
1718 when needs_preprocessing $
1719 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1721 return (dflags', src_fn, buf)
1724 -----------------------------------------------------------------------------
1726 -----------------------------------------------------------------------------
1728 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1729 -- ToDo: we don't have a proper line number for this error
1730 noModError dflags loc wanted_mod err
1731 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1733 noHsFileErr loc path
1734 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1737 = throwDyn $ mkPlainErrMsg noSrcSpan $
1738 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1740 multiRootsErr :: [ModSummary] -> IO ()
1741 multiRootsErr summs@(summ1:_)
1742 = throwDyn $ mkPlainErrMsg noSrcSpan $
1743 text "module" <+> quotes (ppr mod) <+>
1744 text "is defined in multiple files:" <+>
1745 sep (map text files)
1748 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1750 cyclicModuleErr :: [ModSummary] -> SDoc
1752 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1753 2 (vcat (map show_one ms))
1755 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1756 nest 2 $ ptext SLIT("imports:") <+>
1757 (pp_imps HsBootFile (ms_srcimps ms)
1758 $$ pp_imps HsSrcFile (ms_imps ms))]
1759 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1760 pp_imps src mods = fsep (map (show_mod src) mods)
1763 -- | Inform GHC that the working directory has changed. GHC will flush
1764 -- its cache of module locations, since it may no longer be valid.
1765 -- Note: if you change the working directory, you should also unload
1766 -- the current program (set targets to empty, followed by load).
1767 workingDirectoryChanged :: Session -> IO ()
1768 workingDirectoryChanged s = withSession s $ flushFinderCaches
1770 -- -----------------------------------------------------------------------------
1771 -- inspecting the session
1773 -- | Get the module dependency graph.
1774 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1775 getModuleGraph s = withSession s (return . hsc_mod_graph)
1777 isLoaded :: Session -> ModuleName -> IO Bool
1778 isLoaded s m = withSession s $ \hsc_env ->
1779 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1781 getBindings :: Session -> IO [TyThing]
1782 getBindings s = withSession s $ \hsc_env ->
1783 -- we have to implement the shadowing behaviour of ic_tmp_ids here
1784 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
1786 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
1787 filtered = foldr f (const []) tmp_ids emptyUniqSet
1789 | uniq `elementOfUniqSet` set = rest set
1790 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
1791 where uniq = getUnique (nameOccName (idName id))
1795 getPrintUnqual :: Session -> IO PrintUnqualified
1796 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1798 -- | Container for information about a 'Module'.
1799 data ModuleInfo = ModuleInfo {
1800 minf_type_env :: TypeEnv,
1801 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1802 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1803 minf_instances :: [Instance]
1805 ,minf_modBreaks :: ModBreaks
1807 -- ToDo: this should really contain the ModIface too
1809 -- We don't want HomeModInfo here, because a ModuleInfo applies
1810 -- to package modules too.
1812 -- | Request information about a loaded 'Module'
1813 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1814 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1815 let mg = hsc_mod_graph hsc_env
1816 if mdl `elem` map ms_mod mg
1817 then getHomeModuleInfo hsc_env (moduleName mdl)
1819 {- if isHomeModule (hsc_dflags hsc_env) mdl
1821 else -} getPackageModuleInfo hsc_env mdl
1822 -- getPackageModuleInfo will attempt to find the interface, so
1823 -- we don't want to call it for a home module, just in case there
1824 -- was a problem loading the module and the interface doesn't
1825 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1827 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1828 getPackageModuleInfo hsc_env mdl = do
1830 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1832 Nothing -> return Nothing
1834 eps <- readIORef (hsc_EPS hsc_env)
1836 names = availsToNameSet avails
1838 tys = [ ty | name <- concatMap availNames avails,
1839 Just ty <- [lookupTypeEnv pte name] ]
1841 return (Just (ModuleInfo {
1842 minf_type_env = mkTypeEnv tys,
1843 minf_exports = names,
1844 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1845 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1846 minf_modBreaks = emptyModBreaks
1849 -- bogusly different for non-GHCI (ToDo)
1853 getHomeModuleInfo hsc_env mdl =
1854 case lookupUFM (hsc_HPT hsc_env) mdl of
1855 Nothing -> return Nothing
1857 let details = hm_details hmi
1858 return (Just (ModuleInfo {
1859 minf_type_env = md_types details,
1860 minf_exports = availsToNameSet (md_exports details),
1861 minf_rdr_env = mi_globals $! hm_iface hmi,
1862 minf_instances = md_insts details
1864 ,minf_modBreaks = md_modBreaks details
1868 -- | The list of top-level entities defined in a module
1869 modInfoTyThings :: ModuleInfo -> [TyThing]
1870 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1872 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1873 modInfoTopLevelScope minf
1874 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1876 modInfoExports :: ModuleInfo -> [Name]
1877 modInfoExports minf = nameSetToList $! minf_exports minf
1879 -- | Returns the instances defined by the specified module.
1880 -- Warning: currently unimplemented for package modules.
1881 modInfoInstances :: ModuleInfo -> [Instance]
1882 modInfoInstances = minf_instances
1884 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1885 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1887 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1888 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1890 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1891 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1892 case lookupTypeEnv (minf_type_env minf) name of
1893 Just tyThing -> return (Just tyThing)
1895 eps <- readIORef (hsc_EPS hsc_env)
1896 return $! lookupType (hsc_dflags hsc_env)
1897 (hsc_HPT hsc_env) (eps_PTE eps) name
1900 modInfoModBreaks = minf_modBreaks
1903 isDictonaryId :: Id -> Bool
1905 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1907 -- | Looks up a global name: that is, any top-level name in any
1908 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1909 -- the interactive context, and therefore does not require a preceding
1911 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1912 lookupGlobalName s name = withSession s $ \hsc_env -> do
1913 eps <- readIORef (hsc_EPS hsc_env)
1914 return $! lookupType (hsc_dflags hsc_env)
1915 (hsc_HPT hsc_env) (eps_PTE eps) name
1917 -- -----------------------------------------------------------------------------
1918 -- Misc exported utils
1920 dataConType :: DataCon -> Type
1921 dataConType dc = idType (dataConWrapId dc)
1923 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1924 pprParenSymName :: NamedThing a => a -> SDoc
1925 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1927 -- ----------------------------------------------------------------------------
1932 -- - Data and Typeable instances for HsSyn.
1934 -- ToDo: check for small transformations that happen to the syntax in
1935 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1937 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1938 -- to get from TyCons, Ids etc. to TH syntax (reify).
1940 -- :browse will use either lm_toplev or inspect lm_interface, depending
1941 -- on whether the module is interpreted or not.
1943 -- This is for reconstructing refactored source code
1944 -- Calls the lexer repeatedly.
1945 -- ToDo: add comment tokens to token stream
1946 getTokenStream :: Session -> Module -> IO [Located Token]
1949 -- -----------------------------------------------------------------------------
1950 -- Interactive evaluation
1952 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1953 -- filesystem and package database to find the corresponding 'Module',
1954 -- using the algorithm that is used for an @import@ declaration.
1955 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1956 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1957 findModule' hsc_env mod_name maybe_pkg
1959 findModule' hsc_env mod_name maybe_pkg =
1961 dflags = hsc_dflags hsc_env
1962 hpt = hsc_HPT hsc_env
1963 this_pkg = thisPackage dflags
1965 case lookupUFM hpt mod_name of
1966 Just mod_info -> return (mi_module (hm_iface mod_info))
1967 _not_a_home_module -> do
1968 res <- findImportedModule hsc_env mod_name maybe_pkg
1970 Found _ m | modulePackageId m /= this_pkg -> return m
1971 | otherwise -> throwDyn (CmdLineError (showSDoc $
1972 text "module" <+> pprModule m <+>
1973 text "is not loaded"))
1974 err -> let msg = cannotFindModule dflags mod_name err in
1975 throwDyn (CmdLineError (showSDoc msg))