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
62 modInfoIsExportedName,
65 mkPrintUnqualifiedForModule,
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, historyEnclosingDecl),
88 GHC.getHistorySpan, getHistoryModule,
92 InteractiveEval.forward,
95 compileExpr, HValue, dynCompileExpr,
97 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
99 ModBreaks(..), BreakIndex,
100 BreakInfo(breakInfo_number, breakInfo_module),
101 BreakArray, setBreakOn, setBreakOff, getBreak,
104 -- * Abstract syntax elements
110 Module, mkModule, pprModule, moduleName, modulePackageId,
111 ModuleName, mkModuleName, moduleNameString,
115 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
117 RdrName(Qual,Unqual),
121 isImplicitId, isDeadBinder,
122 isExportedId, isLocalId, isGlobalId,
124 isPrimOpId, isFCallId, isClassOpId_maybe,
125 isDataConWorkId, idDataCon,
126 isBottomingId, isDictonaryId,
127 recordSelectorFieldLabel,
129 -- ** Type constructors
131 tyConTyVars, tyConDataCons, tyConArity,
132 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
134 synTyConDefn, synTyConType, synTyConResKind,
140 -- ** Data constructors
142 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
143 dataConIsInfix, isVanillaDataCon,
145 StrictnessMark(..), isMarkedStrict,
149 classMethods, classSCTheta, classTvsFds,
154 instanceDFunId, pprInstance, pprInstanceHdr,
156 -- ** Types and Kinds
157 Type, dropForAlls, splitForAllTys, funResultTy,
158 pprParendType, pprTypeApp,
161 ThetaType, pprThetaArrow,
167 module HsSyn, -- ToDo: remove extraneous bits
171 defaultFixity, maxPrecedence,
175 -- ** Source locations
177 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
178 srcLocFile, srcLocLine, srcLocCol,
180 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
181 srcSpanStart, srcSpanEnd,
183 srcSpanStartLine, srcSpanEndLine,
184 srcSpanStartCol, srcSpanEndCol,
187 GhcException(..), showGhcException,
197 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
198 * what StaticFlags should we expose, if any?
201 #include "HsVersions.h"
204 import qualified Linker
205 import Linker ( HValue )
210 import InteractiveEval
217 import Type hiding (typeKind)
218 import TcType hiding (typeKind)
220 import Var hiding (setIdType)
221 import TysPrim ( alphaTyVars )
226 import Name hiding ( varName )
227 import OccName ( parenSymOcc )
228 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
231 import DriverPipeline
232 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
233 import HeaderInfo ( getImports, getOptions )
235 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
239 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
249 import Bag ( unitBag, listToBag )
250 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
251 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
253 import qualified ErrUtils
255 import StringBuffer ( StringBuffer, hGetStringBuffer )
258 import Maybes ( expectJust, mapCatMaybes )
260 import HaddockLex ( tokenise )
262 import Control.Concurrent
263 import System.Directory ( getModificationTime, doesFileExist )
266 import qualified Data.List as List
268 import System.Exit ( exitWith, ExitCode(..) )
269 import System.Time ( ClockTime )
270 import Control.Exception as Exception hiding (handle)
273 import System.IO.Error ( try, isDoesNotExistError )
274 import Prelude hiding (init)
277 -- -----------------------------------------------------------------------------
278 -- Exception handlers
280 -- | Install some default exception handlers and run the inner computation.
281 -- Unless you want to handle exceptions yourself, you should wrap this around
282 -- the top level of your program. The default handlers output the error
283 -- message(s) to stderr and exit cleanly.
284 defaultErrorHandler :: DynFlags -> IO a -> IO a
285 defaultErrorHandler dflags inner =
286 -- top-level exception handler: any unrecognised exception is a compiler bug.
287 handle (\exception -> do
290 -- an IO exception probably isn't our fault, so don't panic
292 fatalErrorMsg dflags (text (show exception))
293 AsyncException StackOverflow ->
294 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
296 fatalErrorMsg dflags (text (show (Panic (show exception))))
297 exitWith (ExitFailure 1)
300 -- program errors: messages with locations attached. Sometimes it is
301 -- convenient to just throw these as exceptions.
302 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
303 exitWith (ExitFailure 1)) $
305 -- error messages propagated as exceptions
306 handleDyn (\dyn -> do
309 PhaseFailed _ code -> exitWith code
310 Interrupted -> exitWith (ExitFailure 1)
311 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
312 exitWith (ExitFailure 1)
316 -- | Install a default cleanup handler to remove temporary files
317 -- deposited by a GHC run. This is seperate from
318 -- 'defaultErrorHandler', because you might want to override the error
319 -- handling, but still get the ordinary cleanup behaviour.
320 defaultCleanupHandler :: DynFlags -> IO a -> IO a
321 defaultCleanupHandler dflags inner =
322 -- make sure we clean up after ourselves
323 later (do cleanTempFiles dflags
326 -- exceptions will be blocked while we clean the temporary files,
327 -- so there shouldn't be any difficulty if we receive further
332 -- | Starts a new session. A session consists of a set of loaded
333 -- modules, a set of options (DynFlags), and an interactive context.
334 newSession :: Maybe FilePath -> IO Session
335 newSession mb_top_dir = do
337 main_thread <- myThreadId
338 modifyMVar_ interruptTargetThread (return . (main_thread :))
339 installSignalHandlers
342 dflags0 <- initSysTools mb_top_dir defaultDynFlags
343 dflags <- initDynFlags dflags0
344 env <- newHscEnv dflags
348 -- tmp: this breaks the abstraction, but required because DriverMkDepend
349 -- needs to call the Finder. ToDo: untangle this.
350 sessionHscEnv :: Session -> IO HscEnv
351 sessionHscEnv (Session ref) = readIORef ref
353 -- -----------------------------------------------------------------------------
356 -- | Grabs the DynFlags from the Session
357 getSessionDynFlags :: Session -> IO DynFlags
358 getSessionDynFlags s = withSession s (return . hsc_dflags)
360 -- | Updates the DynFlags in a Session. This also reads
361 -- the package database (unless it has already been read),
362 -- and prepares the compilers knowledge about packages. It
363 -- can be called again to load new packages: just add new
364 -- package flags to (packageFlags dflags).
366 -- Returns a list of new packages that may need to be linked in using
367 -- the dynamic linker (see 'linkPackages') as a result of new package
368 -- flags. If you are not doing linking or doing static linking, you
369 -- can ignore the list of packages returned.
371 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
372 setSessionDynFlags (Session ref) dflags = do
373 hsc_env <- readIORef ref
374 (dflags', preload) <- initPackages dflags
375 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
378 -- | If there is no -o option, guess the name of target executable
379 -- by using top-level source file name as a base.
380 guessOutputFile :: Session -> IO ()
381 guessOutputFile s = modifySession s $ \env ->
382 let dflags = hsc_dflags env
383 mod_graph = hsc_mod_graph env
384 mainModuleSrcPath, guessedName :: Maybe String
385 mainModuleSrcPath = do
386 let isMain = (== mainModIs dflags) . ms_mod
387 [ms] <- return (filter isMain mod_graph)
388 ml_hs_file (ms_location ms)
389 guessedName = fmap basenameOf mainModuleSrcPath
391 case outputFile dflags of
393 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
395 -- -----------------------------------------------------------------------------
398 -- ToDo: think about relative vs. absolute file paths. And what
399 -- happens when the current directory changes.
401 -- | Sets the targets for this session. Each target may be a module name
402 -- or a filename. The targets correspond to the set of root modules for
403 -- the program\/library. Unloading the current program is achieved by
404 -- setting the current set of targets to be empty, followed by load.
405 setTargets :: Session -> [Target] -> IO ()
406 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
408 -- | returns the current set of targets
409 getTargets :: Session -> IO [Target]
410 getTargets s = withSession s (return . hsc_targets)
412 -- | Add another target
413 addTarget :: Session -> Target -> IO ()
415 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
418 removeTarget :: Session -> TargetId -> IO ()
419 removeTarget s target_id
420 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
422 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
424 -- Attempts to guess what Target a string refers to. This function implements
425 -- the --make/GHCi command-line syntax for filenames:
427 -- - if the string looks like a Haskell source filename, then interpret
429 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
431 -- - otherwise interpret the string as a module name
433 guessTarget :: String -> Maybe Phase -> IO Target
434 guessTarget file (Just phase)
435 = return (Target (TargetFile file (Just phase)) Nothing)
436 guessTarget file Nothing
437 | isHaskellSrcFilename file
438 = return (Target (TargetFile file Nothing) Nothing)
440 = do exists <- doesFileExist hs_file
442 then return (Target (TargetFile hs_file Nothing) Nothing)
444 exists <- doesFileExist lhs_file
446 then return (Target (TargetFile lhs_file Nothing) Nothing)
448 return (Target (TargetModule (mkModuleName file)) Nothing)
450 hs_file = file `joinFileExt` "hs"
451 lhs_file = file `joinFileExt` "lhs"
453 -- -----------------------------------------------------------------------------
454 -- Extending the program scope
456 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
457 extendGlobalRdrScope session rdrElts
458 = modifySession session $ \hscEnv ->
459 let global_rdr = hsc_global_rdr_env hscEnv
460 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
462 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
463 setGlobalRdrScope session rdrElts
464 = modifySession session $ \hscEnv ->
465 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
467 extendGlobalTypeScope :: Session -> [Id] -> IO ()
468 extendGlobalTypeScope session ids
469 = modifySession session $ \hscEnv ->
470 let global_type = hsc_global_type_env hscEnv
471 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
473 setGlobalTypeScope :: Session -> [Id] -> IO ()
474 setGlobalTypeScope session ids
475 = modifySession session $ \hscEnv ->
476 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
478 -- -----------------------------------------------------------------------------
479 -- Parsing Haddock comments
481 parseHaddockComment :: String -> Either String (HsDoc RdrName)
482 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
484 -- -----------------------------------------------------------------------------
485 -- Loading the program
487 -- Perform a dependency analysis starting from the current targets
488 -- and update the session with the new module graph.
489 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
490 depanal (Session ref) excluded_mods allow_dup_roots = do
491 hsc_env <- readIORef ref
493 dflags = hsc_dflags hsc_env
494 targets = hsc_targets hsc_env
495 old_graph = hsc_mod_graph hsc_env
497 showPass dflags "Chasing dependencies"
498 debugTraceMsg dflags 2 (hcat [
499 text "Chasing modules from: ",
500 hcat (punctuate comma (map pprTarget targets))])
502 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
504 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
509 -- | The result of load.
511 = LoadOk Errors -- ^ all specified targets were loaded successfully.
512 | LoadFailed Errors -- ^ not all modules were loaded.
514 type Errors = [String]
516 data ErrMsg = ErrMsg {
517 errMsgSeverity :: Severity, -- warning, error, etc.
518 errMsgSpans :: [SrcSpan],
519 errMsgShortDoc :: Doc,
520 errMsgExtraInfo :: Doc
526 | LoadUpTo ModuleName
527 | LoadDependenciesOf ModuleName
529 -- | Try to load the program. If a Module is supplied, then just
530 -- attempt to load up to this target. If no Module is supplied,
531 -- then try to load all targets.
532 load :: Session -> LoadHowMuch -> IO SuccessFlag
533 load s@(Session ref) how_much
535 -- Dependency analysis first. Note that this fixes the module graph:
536 -- even if we don't get a fully successful upsweep, the full module
537 -- graph is still retained in the Session. We can tell which modules
538 -- were successfully loaded by inspecting the Session's HPT.
539 mb_graph <- depanal s [] False
541 Just mod_graph -> catchingFailure $ load2 s how_much mod_graph
542 Nothing -> return Failed
543 where catchingFailure f = f `Exception.catch` \e -> do
544 hsc_env <- readIORef ref
545 -- trac #1565 / test ghci021:
546 -- let bindings may explode if we try to use them after
548 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
551 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
552 load2 s@(Session ref) how_much mod_graph = do
554 hsc_env <- readIORef ref
556 let hpt1 = hsc_HPT hsc_env
557 let dflags = hsc_dflags hsc_env
559 -- The "bad" boot modules are the ones for which we have
560 -- B.hs-boot in the module graph, but no B.hs
561 -- The downsweep should have ensured this does not happen
563 let all_home_mods = [ms_mod_name s
564 | s <- mod_graph, not (isBootSummary s)]
566 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
567 not (ms_mod_name s `elem` all_home_mods)]
569 ASSERT( null bad_boot_mods ) return ()
571 -- mg2_with_srcimps drops the hi-boot nodes, returning a
572 -- graph with cycles. Among other things, it is used for
573 -- backing out partially complete cycles following a failed
574 -- upsweep, and for removing from hpt all the modules
575 -- not in strict downwards closure, during calls to compile.
576 let mg2_with_srcimps :: [SCC ModSummary]
577 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
579 -- If we can determine that any of the {-# SOURCE #-} imports
580 -- are definitely unnecessary, then emit a warning.
581 warnUnnecessarySourceImports dflags mg2_with_srcimps
584 -- check the stability property for each module.
585 stable_mods@(stable_obj,stable_bco)
586 = checkStability hpt1 mg2_with_srcimps all_home_mods
588 -- prune bits of the HPT which are definitely redundant now,
590 pruned_hpt = pruneHomePackageTable hpt1
591 (flattenSCCs mg2_with_srcimps)
596 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
597 text "Stable BCO:" <+> ppr stable_bco)
599 -- Unload any modules which are going to be re-linked this time around.
600 let stable_linkables = [ linkable
601 | m <- stable_obj++stable_bco,
602 Just hmi <- [lookupUFM pruned_hpt m],
603 Just linkable <- [hm_linkable hmi] ]
604 unload hsc_env stable_linkables
606 -- We could at this point detect cycles which aren't broken by
607 -- a source-import, and complain immediately, but it seems better
608 -- to let upsweep_mods do this, so at least some useful work gets
609 -- done before the upsweep is abandoned.
610 --hPutStrLn stderr "after tsort:\n"
611 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
613 -- Now do the upsweep, calling compile for each module in
614 -- turn. Final result is version 3 of everything.
616 -- Topologically sort the module graph, this time including hi-boot
617 -- nodes, and possibly just including the portion of the graph
618 -- reachable from the module specified in the 2nd argument to load.
619 -- This graph should be cycle-free.
620 -- If we're restricting the upsweep to a portion of the graph, we
621 -- also want to retain everything that is still stable.
622 let full_mg :: [SCC ModSummary]
623 full_mg = topSortModuleGraph False mod_graph Nothing
625 maybe_top_mod = case how_much of
627 LoadDependenciesOf m -> Just m
630 partial_mg0 :: [SCC ModSummary]
631 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
633 -- LoadDependenciesOf m: we want the upsweep to stop just
634 -- short of the specified module (unless the specified module
637 | LoadDependenciesOf _mod <- how_much
638 = ASSERT( case last partial_mg0 of
639 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
640 List.init partial_mg0
646 | AcyclicSCC ms <- full_mg,
647 ms_mod_name ms `elem` stable_obj++stable_bco,
648 ms_mod_name ms `notElem` [ ms_mod_name ms' |
649 AcyclicSCC ms' <- partial_mg ] ]
651 mg = stable_mg ++ partial_mg
653 -- clean up between compilations
654 let cleanup = cleanTempFilesExcept dflags
655 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
657 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
659 (upsweep_ok, hsc_env1, modsUpswept)
660 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
661 pruned_hpt stable_mods cleanup mg
663 -- Make modsDone be the summaries for each home module now
664 -- available; this should equal the domain of hpt3.
665 -- Get in in a roughly top .. bottom order (hence reverse).
667 let modsDone = reverse modsUpswept
669 -- Try and do linking in some form, depending on whether the
670 -- upsweep was completely or only partially successful.
672 if succeeded upsweep_ok
675 -- Easy; just relink it all.
676 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
678 -- Clean up after ourselves
679 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
681 -- Issue a warning for the confusing case where the user
682 -- said '-o foo' but we're not going to do any linking.
683 -- We attempt linking if either (a) one of the modules is
684 -- called Main, or (b) the user said -no-hs-main, indicating
685 -- that main() is going to come from somewhere else.
687 let ofile = outputFile dflags
688 let no_hs_main = dopt Opt_NoHsMain dflags
690 main_mod = mainModIs dflags
691 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
692 do_linking = a_root_is_Main || no_hs_main
694 when (ghcLink dflags == LinkBinary
695 && isJust ofile && not do_linking) $
696 debugTraceMsg dflags 1 $
697 text ("Warning: output was redirected with -o, " ++
698 "but no output will be generated\n" ++
699 "because there is no " ++
700 moduleNameString (moduleName main_mod) ++ " module.")
702 -- link everything together
703 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
705 loadFinish Succeeded linkresult ref hsc_env1
708 -- Tricky. We need to back out the effects of compiling any
709 -- half-done cycles, both so as to clean up the top level envs
710 -- and to avoid telling the interactive linker to link them.
711 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
714 = map ms_mod modsDone
715 let mods_to_zap_names
716 = findPartiallyCompletedCycles modsDone_names
719 = filter ((`notElem` mods_to_zap_names).ms_mod)
722 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
725 -- Clean up after ourselves
726 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
728 -- there should be no Nothings where linkables should be, now
729 ASSERT(all (isJust.hm_linkable)
730 (eltsUFM (hsc_HPT hsc_env))) do
732 -- Link everything together
733 linkresult <- link (ghcLink dflags) dflags False hpt4
735 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
736 loadFinish Failed linkresult ref hsc_env4
738 -- Finish up after a load.
740 -- If the link failed, unload everything and return.
741 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
742 loadFinish _all_ok Failed ref hsc_env
743 = do unload hsc_env []
744 writeIORef ref $! discardProg hsc_env
747 -- Empty the interactive context and set the module context to the topmost
748 -- newly loaded module, or the Prelude if none were loaded.
749 loadFinish all_ok Succeeded ref hsc_env
750 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
754 -- Forget the current program, but retain the persistent info in HscEnv
755 discardProg :: HscEnv -> HscEnv
757 = hsc_env { hsc_mod_graph = emptyMG,
758 hsc_IC = emptyInteractiveContext,
759 hsc_HPT = emptyHomePackageTable }
761 -- used to fish out the preprocess output files for the purposes of
762 -- cleaning up. The preprocessed file *might* be the same as the
763 -- source file, but that doesn't do any harm.
764 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
765 ppFilesFromSummaries summaries = map ms_hspp_file summaries
767 -- -----------------------------------------------------------------------------
771 CheckedModule { parsedSource :: ParsedSource,
772 renamedSource :: Maybe RenamedSource,
773 typecheckedSource :: Maybe TypecheckedSource,
774 checkedModuleInfo :: Maybe ModuleInfo,
775 coreBinds :: Maybe [CoreBind]
777 -- ToDo: improvements that could be made here:
778 -- if the module succeeded renaming but not typechecking,
779 -- we can still get back the GlobalRdrEnv and exports, so
780 -- perhaps the ModuleInfo should be split up into separate
781 -- fields within CheckedModule.
783 type ParsedSource = Located (HsModule RdrName)
784 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
785 Maybe (HsDoc Name), HaddockModInfo Name)
786 type TypecheckedSource = LHsBinds Id
789 -- - things that aren't in the output of the typechecker right now:
793 -- - type/data/newtype declarations
794 -- - class declarations
796 -- - extra things in the typechecker's output:
797 -- - default methods are turned into top-level decls.
798 -- - dictionary bindings
801 -- | This is the way to get access to parsed and typechecked source code
802 -- for a module. 'checkModule' attempts to typecheck the module. If
803 -- successful, it returns the abstract syntax for the module.
804 -- If compileToCore is true, it also desugars the module and returns the
805 -- resulting Core bindings as a component of the CheckedModule.
806 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
807 checkModule (Session ref) mod compileToCore = do
808 -- parse & typecheck the module
809 hsc_env <- readIORef ref
810 let mg = hsc_mod_graph hsc_env
811 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
814 mbChecked <- hscFileCheck
815 hsc_env{hsc_dflags=ms_hspp_opts ms}
818 Nothing -> return Nothing
819 Just (HscChecked parsed renamed Nothing _) ->
820 return (Just (CheckedModule {
821 parsedSource = parsed,
822 renamedSource = renamed,
823 typecheckedSource = Nothing,
824 checkedModuleInfo = Nothing,
825 coreBinds = Nothing }))
826 Just (HscChecked parsed renamed
827 (Just (tc_binds, rdr_env, details))
828 maybeCoreBinds) -> do
829 let minf = ModuleInfo {
830 minf_type_env = md_types details,
831 minf_exports = availsToNameSet $
833 minf_rdr_env = Just rdr_env,
834 minf_instances = md_insts details
836 ,minf_modBreaks = emptyModBreaks
839 return (Just (CheckedModule {
840 parsedSource = parsed,
841 renamedSource = renamed,
842 typecheckedSource = Just tc_binds,
843 checkedModuleInfo = Just minf,
844 coreBinds = maybeCoreBinds}))
846 -- | This is the way to get access to the Core bindings corresponding
847 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
848 -- desugar the module, then returns the resulting list of Core bindings if
850 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
851 compileToCore session fn = do
852 -- First, set the target to the desired filename
853 target <- guessTarget fn Nothing
854 addTarget session target
855 load session LoadAllTargets
856 -- Then find dependencies
857 maybeModGraph <- depanal session [] True
858 case maybeModGraph of
859 Nothing -> return Nothing
861 let modSummary = expectJust "compileToCore" $
862 find ((== fn) . msHsFilePath) modGraph
863 -- Now we have the module name;
864 -- parse, typecheck and desugar the module
865 let mod = ms_mod_name modSummary
866 maybeCheckedModule <- checkModule session mod True
867 case maybeCheckedModule of
868 Nothing -> return Nothing
869 Just checkedMod -> return $ coreBinds checkedMod
870 -- ---------------------------------------------------------------------------
873 unload :: HscEnv -> [Linkable] -> IO ()
874 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
875 = case ghcLink (hsc_dflags hsc_env) of
877 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
879 LinkInMemory -> panic "unload: no interpreter"
880 -- urgh. avoid warnings:
881 hsc_env stable_linkables
885 -- -----------------------------------------------------------------------------
889 Stability tells us which modules definitely do not need to be recompiled.
890 There are two main reasons for having stability:
892 - avoid doing a complete upsweep of the module graph in GHCi when
893 modules near the bottom of the tree have not changed.
895 - to tell GHCi when it can load object code: we can only load object code
896 for a module when we also load object code fo all of the imports of the
897 module. So we need to know that we will definitely not be recompiling
898 any of these modules, and we can use the object code.
900 The stability check is as follows. Both stableObject and
901 stableBCO are used during the upsweep phase later.
904 stable m = stableObject m || stableBCO m
907 all stableObject (imports m)
908 && old linkable does not exist, or is == on-disk .o
909 && date(on-disk .o) > date(.hs)
912 all stable (imports m)
913 && date(BCO) > date(.hs)
916 These properties embody the following ideas:
918 - if a module is stable, then:
919 - if it has been compiled in a previous pass (present in HPT)
920 then it does not need to be compiled or re-linked.
921 - if it has not been compiled in a previous pass,
922 then we only need to read its .hi file from disk and
923 link it to produce a ModDetails.
925 - if a modules is not stable, we will definitely be at least
926 re-linking, and possibly re-compiling it during the upsweep.
927 All non-stable modules can (and should) therefore be unlinked
930 - Note that objects are only considered stable if they only depend
931 on other objects. We can't link object code against byte code.
935 :: HomePackageTable -- HPT from last compilation
936 -> [SCC ModSummary] -- current module graph (cyclic)
937 -> [ModuleName] -- all home modules
938 -> ([ModuleName], -- stableObject
939 [ModuleName]) -- stableBCO
941 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
943 checkSCC (stable_obj, stable_bco) scc0
944 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
945 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
946 | otherwise = (stable_obj, stable_bco)
948 scc = flattenSCC scc0
949 scc_mods = map ms_mod_name scc
950 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
952 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
953 -- all imports outside the current SCC, but in the home pkg
955 stable_obj_imps = map (`elem` stable_obj) scc_allimps
956 stable_bco_imps = map (`elem` stable_bco) scc_allimps
963 and (zipWith (||) stable_obj_imps stable_bco_imps)
967 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
971 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
972 Just hmi | Just l <- hm_linkable hmi
973 -> isObjectLinkable l && t == linkableTime l
975 -- why '>=' rather than '>' above? If the filesystem stores
976 -- times to the nearset second, we may occasionally find that
977 -- the object & source have the same modification time,
978 -- especially if the source was automatically generated
979 -- and compiled. Using >= is slightly unsafe, but it matches
983 = case lookupUFM hpt (ms_mod_name ms) of
984 Just hmi | Just l <- hm_linkable hmi ->
985 not (isObjectLinkable l) &&
986 linkableTime l >= ms_hs_date ms
989 ms_allimps :: ModSummary -> [ModuleName]
990 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
992 -- -----------------------------------------------------------------------------
993 -- Prune the HomePackageTable
995 -- Before doing an upsweep, we can throw away:
997 -- - For non-stable modules:
998 -- - all ModDetails, all linked code
999 -- - all unlinked code that is out of date with respect to
1002 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1003 -- space at the end of the upsweep, because the topmost ModDetails of the
1004 -- old HPT holds on to the entire type environment from the previous
1007 pruneHomePackageTable
1010 -> ([ModuleName],[ModuleName])
1013 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1016 | is_stable modl = hmi'
1017 | otherwise = hmi'{ hm_details = emptyModDetails }
1019 modl = moduleName (mi_module (hm_iface hmi))
1020 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1021 = hmi{ hm_linkable = Nothing }
1024 where ms = expectJust "prune" (lookupUFM ms_map modl)
1026 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1028 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1030 -- -----------------------------------------------------------------------------
1032 -- Return (names of) all those in modsDone who are part of a cycle
1033 -- as defined by theGraph.
1034 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1035 findPartiallyCompletedCycles modsDone theGraph
1039 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1040 chew ((CyclicSCC vs):rest)
1041 = let names_in_this_cycle = nub (map ms_mod vs)
1043 = nub ([done | done <- modsDone,
1044 done `elem` names_in_this_cycle])
1045 chewed_rest = chew rest
1047 if notNull mods_in_this_cycle
1048 && length mods_in_this_cycle < length names_in_this_cycle
1049 then mods_in_this_cycle ++ chewed_rest
1052 -- -----------------------------------------------------------------------------
1055 -- This is where we compile each module in the module graph, in a pass
1056 -- from the bottom to the top of the graph.
1058 -- There better had not be any cyclic groups here -- we check for them.
1061 :: HscEnv -- Includes initially-empty HPT
1062 -> HomePackageTable -- HPT from last time round (pruned)
1063 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1064 -> IO () -- How to clean up unwanted tmp files
1065 -> [SCC ModSummary] -- Mods to do (the worklist)
1067 HscEnv, -- With an updated HPT
1068 [ModSummary]) -- Mods which succeeded
1070 upsweep hsc_env old_hpt stable_mods cleanup mods
1071 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1074 upsweep' hsc_env _old_hpt _stable_mods _cleanup
1076 = return (Succeeded, hsc_env, [])
1078 upsweep' hsc_env _old_hpt _stable_mods _cleanup
1079 (CyclicSCC ms:_) _ _
1080 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1081 return (Failed, hsc_env, [])
1083 upsweep' hsc_env old_hpt stable_mods cleanup
1084 (AcyclicSCC mod:mods) mod_index nmods
1085 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1086 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1087 -- (moduleEnvElts (hsc_HPT hsc_env)))
1089 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1092 cleanup -- Remove unwanted tmp files between compilations
1095 Nothing -> return (Failed, hsc_env, [])
1097 { let this_mod = ms_mod_name mod
1099 -- Add new info to hsc_env
1100 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1101 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1103 -- Space-saving: delete the old HPT entry
1104 -- for mod BUT if mod is a hs-boot
1105 -- node, don't delete it. For the
1106 -- interface, the HPT entry is probaby for the
1107 -- main Haskell source file. Deleting it
1108 -- would force .. (what?? --SDM)
1109 old_hpt1 | isBootSummary mod = old_hpt
1110 | otherwise = delFromUFM old_hpt this_mod
1112 ; (restOK, hsc_env2, modOKs)
1113 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1114 mods (mod_index+1) nmods
1115 ; return (restOK, hsc_env2, mod:modOKs)
1119 -- Compile a single module. Always produce a Linkable for it if
1120 -- successful. If no compilation happened, return the old Linkable.
1121 upsweep_mod :: HscEnv
1123 -> ([ModuleName],[ModuleName])
1125 -> Int -- index of module
1126 -> Int -- total number of modules
1127 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1129 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1131 this_mod_name = ms_mod_name summary
1132 this_mod = ms_mod summary
1133 mb_obj_date = ms_obj_date summary
1134 obj_fn = ml_obj_file (ms_location summary)
1135 hs_date = ms_hs_date summary
1137 is_stable_obj = this_mod_name `elem` stable_obj
1138 is_stable_bco = this_mod_name `elem` stable_bco
1140 old_hmi = lookupUFM old_hpt this_mod_name
1142 -- We're using the dflags for this module now, obtained by
1143 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1144 dflags = ms_hspp_opts summary
1145 prevailing_target = hscTarget (hsc_dflags hsc_env)
1146 local_target = hscTarget dflags
1148 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1149 -- we don't do anything dodgy: these should only work to change
1150 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1151 -- end up trying to link object code to byte code.
1152 target = if prevailing_target /= local_target
1153 && (not (isObjectTarget prevailing_target)
1154 || not (isObjectTarget local_target))
1155 then prevailing_target
1158 -- store the corrected hscTarget into the summary
1159 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1161 -- The old interface is ok if
1162 -- a) we're compiling a source file, and the old HPT
1163 -- entry is for a source file
1164 -- b) we're compiling a hs-boot file
1165 -- Case (b) allows an hs-boot file to get the interface of its
1166 -- real source file on the second iteration of the compilation
1167 -- manager, but that does no harm. Otherwise the hs-boot file
1168 -- will always be recompiled
1173 Just hm_info | isBootSummary summary -> Just iface
1174 | not (mi_boot iface) -> Just iface
1175 | otherwise -> Nothing
1177 iface = hm_iface hm_info
1179 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1180 compile_it = upsweep_compile hsc_env
1181 summary' mod_index nmods mb_old_iface
1183 compile_it_discard_iface
1184 = upsweep_compile hsc_env
1185 summary' mod_index nmods Nothing
1191 -- Regardless of whether we're generating object code or
1192 -- byte code, we can always use an existing object file
1193 -- if it is *stable* (see checkStability).
1194 | is_stable_obj, isJust old_hmi ->
1196 -- object is stable, and we have an entry in the
1197 -- old HPT: nothing to do
1199 | is_stable_obj, isNothing old_hmi -> do
1200 linkable <- findObjectLinkable this_mod obj_fn
1201 (expectJust "upseep1" mb_obj_date)
1202 compile_it (Just linkable)
1203 -- object is stable, but we need to load the interface
1204 -- off disk to make a HMI.
1208 ASSERT(isJust old_hmi) -- must be in the old_hpt
1210 -- BCO is stable: nothing to do
1212 | Just hmi <- old_hmi,
1213 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1214 linkableTime l >= ms_hs_date summary ->
1216 -- we have an old BCO that is up to date with respect
1217 -- to the source: do a recompilation check as normal.
1221 -- no existing code at all: we must recompile.
1223 -- When generating object code, if there's an up-to-date
1224 -- object file on the disk, then we can use it.
1225 -- However, if the object file is new (compared to any
1226 -- linkable we had from a previous compilation), then we
1227 -- must discard any in-memory interface, because this
1228 -- means the user has compiled the source file
1229 -- separately and generated a new interface, that we must
1230 -- read from the disk.
1232 obj | isObjectTarget obj,
1233 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1236 | Just l <- hm_linkable hmi,
1237 isObjectLinkable l && linkableTime l == obj_date
1238 -> compile_it (Just l)
1240 linkable <- findObjectLinkable this_mod obj_fn obj_date
1241 compile_it_discard_iface (Just linkable)
1247 -- Run hsc to compile a module
1248 upsweep_compile :: HscEnv -> ModSummary -> Int -> Int
1249 -> Maybe ModIface -> Maybe Linkable -> IO (Maybe HomeModInfo)
1250 upsweep_compile hsc_env summary mod_index nmods mb_old_iface mb_old_linkable
1252 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1256 -- Compilation failed. Compile may still have updated the PCS, tho.
1257 CompErrs -> return Nothing
1259 -- Compilation "succeeded", and may or may not have returned a new
1260 -- linkable (depending on whether compilation was actually performed
1262 CompOK new_details new_iface new_linkable
1263 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1264 hm_details = new_details,
1265 hm_linkable = new_linkable }
1266 return (Just new_info)
1269 -- Filter modules in the HPT
1270 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1271 retainInTopLevelEnvs keep_these hpt
1272 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1274 , let mb_mod_info = lookupUFM hpt mod
1275 , isJust mb_mod_info ]
1277 -- ---------------------------------------------------------------------------
1278 -- Topological sort of the module graph
1281 :: Bool -- Drop hi-boot nodes? (see below)
1285 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1286 -- The resulting list of strongly-connected-components is in topologically
1287 -- sorted order, starting with the module(s) at the bottom of the
1288 -- dependency graph (ie compile them first) and ending with the ones at
1291 -- Drop hi-boot nodes (first boolean arg)?
1293 -- False: treat the hi-boot summaries as nodes of the graph,
1294 -- so the graph must be acyclic
1296 -- True: eliminate the hi-boot nodes, and instead pretend
1297 -- the a source-import of Foo is an import of Foo
1298 -- The resulting graph has no hi-boot nodes, but can by cyclic
1300 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1301 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1302 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1303 = stronglyConnComp (map vertex_fn (reachable graph root))
1305 -- restrict the graph to just those modules reachable from
1306 -- the specified module. We do this by building a graph with
1307 -- the full set of nodes, and determining the reachable set from
1308 -- the specified node.
1309 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1310 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1312 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1313 | otherwise = throwDyn (ProgramError "module does not exist")
1315 moduleGraphNodes :: Bool -> [ModSummary]
1316 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1317 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1319 -- Drop hs-boot nodes by using HsSrcFile as the key
1320 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1321 | otherwise = HsBootFile
1323 -- We use integers as the keys for the SCC algorithm
1324 nodes :: [(ModSummary, Int, [Int])]
1325 nodes = [(s, expectJust "topSort" $
1326 lookup_key (ms_hsc_src s) (ms_mod_name s),
1327 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1328 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1329 (-- see [boot-edges] below
1330 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1332 else case lookup_key HsBootFile (ms_mod_name s) of
1337 , not (isBootSummary s && drop_hs_boot_nodes) ]
1338 -- Drop the hi-boot ones if told to do so
1340 -- [boot-edges] if this is a .hs and there is an equivalent
1341 -- .hs-boot, add a link from the former to the latter. This
1342 -- has the effect of detecting bogus cases where the .hs-boot
1343 -- depends on the .hs, by introducing a cycle. Additionally,
1344 -- it ensures that we will always process the .hs-boot before
1345 -- the .hs, and so the HomePackageTable will always have the
1346 -- most up to date information.
1348 key_map :: NodeMap Int
1349 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1353 lookup_key :: HscSource -> ModuleName -> Maybe Int
1354 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1356 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1357 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1358 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1359 -- the IsBootInterface parameter True; else False
1362 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1363 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1365 msKey :: ModSummary -> NodeKey
1366 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1368 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1369 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1371 nodeMapElts :: NodeMap a -> [a]
1372 nodeMapElts = eltsFM
1374 -- If there are {-# SOURCE #-} imports between strongly connected
1375 -- components in the topological sort, then those imports can
1376 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1377 -- were necessary, then the edge would be part of a cycle.
1378 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1379 warnUnnecessarySourceImports dflags sccs =
1380 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1382 let mods_in_this_cycle = map ms_mod_name ms in
1383 [ warn i | m <- ms, i <- ms_srcimps m,
1384 unLoc i `notElem` mods_in_this_cycle ]
1386 warn :: Located ModuleName -> WarnMsg
1389 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1390 <+> quotes (ppr mod))
1392 -----------------------------------------------------------------------------
1393 -- Downsweep (dependency analysis)
1395 -- Chase downwards from the specified root set, returning summaries
1396 -- for all home modules encountered. Only follow source-import
1399 -- We pass in the previous collection of summaries, which is used as a
1400 -- cache to avoid recalculating a module summary if the source is
1403 -- The returned list of [ModSummary] nodes has one node for each home-package
1404 -- module, plus one for any hs-boot files. The imports of these nodes
1405 -- are all there, including the imports of non-home-package modules.
1408 -> [ModSummary] -- Old summaries
1409 -> [ModuleName] -- Ignore dependencies on these; treat
1410 -- them as if they were package modules
1411 -> Bool -- True <=> allow multiple targets to have
1412 -- the same module name; this is
1413 -- very useful for ghc -M
1414 -> IO (Maybe [ModSummary])
1415 -- The elts of [ModSummary] all have distinct
1416 -- (Modules, IsBoot) identifiers, unless the Bool is true
1417 -- in which case there can be repeats
1418 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1419 = -- catch error messages and return them
1420 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1421 rootSummaries <- mapM getRootSummary roots
1422 let root_map = mkRootMap rootSummaries
1423 checkDuplicates root_map
1424 summs <- loop (concatMap msDeps rootSummaries) root_map
1427 roots = hsc_targets hsc_env
1429 old_summary_map :: NodeMap ModSummary
1430 old_summary_map = mkNodeMap old_summaries
1432 getRootSummary :: Target -> IO ModSummary
1433 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1434 = do exists <- doesFileExist file
1436 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1437 else throwDyn $ mkPlainErrMsg noSrcSpan $
1438 text "can't find file:" <+> text file
1439 getRootSummary (Target (TargetModule modl) maybe_buf)
1440 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1441 (L rootLoc modl) maybe_buf excl_mods
1442 case maybe_summary of
1443 Nothing -> packageModErr modl
1446 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1448 -- In a root module, the filename is allowed to diverge from the module
1449 -- name, so we have to check that there aren't multiple root files
1450 -- defining the same module (otherwise the duplicates will be silently
1451 -- ignored, leading to confusing behaviour).
1452 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1453 checkDuplicates root_map
1454 | allow_dup_roots = return ()
1455 | null dup_roots = return ()
1456 | otherwise = multiRootsErr (head dup_roots)
1458 dup_roots :: [[ModSummary]] -- Each at least of length 2
1459 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1461 loop :: [(Located ModuleName,IsBootInterface)]
1462 -- Work list: process these modules
1463 -> NodeMap [ModSummary]
1464 -- Visited set; the range is a list because
1465 -- the roots can have the same module names
1466 -- if allow_dup_roots is True
1468 -- The result includes the worklist, except
1469 -- for those mentioned in the visited set
1470 loop [] done = return (concat (nodeMapElts done))
1471 loop ((wanted_mod, is_boot) : ss) done
1472 | Just summs <- lookupFM done key
1473 = if isSingleton summs then
1476 do { multiRootsErr summs; return [] }
1477 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1478 is_boot wanted_mod Nothing excl_mods
1480 Nothing -> loop ss done
1481 Just s -> loop (msDeps s ++ ss)
1482 (addToFM done key [s]) }
1484 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1486 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1487 mkRootMap summaries = addListToFM_C (++) emptyFM
1488 [ (msKey s, [s]) | s <- summaries ]
1490 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1491 -- (msDeps s) returns the dependencies of the ModSummary s.
1492 -- A wrinkle is that for a {-# SOURCE #-} import we return
1493 -- *both* the hs-boot file
1494 -- *and* the source file
1495 -- as "dependencies". That ensures that the list of all relevant
1496 -- modules always contains B.hs if it contains B.hs-boot.
1497 -- Remember, this pass isn't doing the topological sort. It's
1498 -- just gathering the list of all relevant ModSummaries
1500 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1501 ++ [ (m,False) | m <- ms_imps s ]
1503 -----------------------------------------------------------------------------
1504 -- Summarising modules
1506 -- We have two types of summarisation:
1508 -- * Summarise a file. This is used for the root module(s) passed to
1509 -- cmLoadModules. The file is read, and used to determine the root
1510 -- module name. The module name may differ from the filename.
1512 -- * Summarise a module. We are given a module name, and must provide
1513 -- a summary. The finder is used to locate the file in which the module
1518 -> [ModSummary] -- old summaries
1519 -> FilePath -- source file name
1520 -> Maybe Phase -- start phase
1521 -> Maybe (StringBuffer,ClockTime)
1524 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1525 -- we can use a cached summary if one is available and the
1526 -- source file hasn't changed, But we have to look up the summary
1527 -- by source file, rather than module name as we do in summarise.
1528 | Just old_summary <- findSummaryBySourceFile old_summaries file
1530 let location = ms_location old_summary
1532 -- return the cached summary if the source didn't change
1533 src_timestamp <- case maybe_buf of
1534 Just (_,t) -> return t
1535 Nothing -> getModificationTime file
1536 -- The file exists; we checked in getRootSummary above.
1537 -- If it gets removed subsequently, then this
1538 -- getModificationTime may fail, but that's the right
1541 if ms_hs_date old_summary == src_timestamp
1542 then do -- update the object-file timestamp
1543 obj_timestamp <- getObjTimestamp location False
1544 return old_summary{ ms_obj_date = obj_timestamp }
1552 let dflags = hsc_dflags hsc_env
1554 (dflags', hspp_fn, buf)
1555 <- preprocessFile dflags file mb_phase maybe_buf
1557 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1559 -- Make a ModLocation for this file
1560 location <- mkHomeModLocation dflags mod_name file
1562 -- Tell the Finder cache where it is, so that subsequent calls
1563 -- to findModule will find it, even if it's not on any search path
1564 mod <- addHomeModuleToFinder hsc_env mod_name location
1566 src_timestamp <- case maybe_buf of
1567 Just (_,t) -> return t
1568 Nothing -> getModificationTime file
1569 -- getMofificationTime may fail
1571 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1573 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1574 ms_location = location,
1575 ms_hspp_file = hspp_fn,
1576 ms_hspp_opts = dflags',
1577 ms_hspp_buf = Just buf,
1578 ms_srcimps = srcimps, ms_imps = the_imps,
1579 ms_hs_date = src_timestamp,
1580 ms_obj_date = obj_timestamp })
1582 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1583 findSummaryBySourceFile summaries file
1584 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1585 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1589 -- Summarise a module, and pick up source and timestamp.
1592 -> NodeMap ModSummary -- Map of old summaries
1593 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1594 -> Located ModuleName -- Imported module to be summarised
1595 -> Maybe (StringBuffer, ClockTime)
1596 -> [ModuleName] -- Modules to exclude
1597 -> IO (Maybe ModSummary) -- Its new summary
1599 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1600 | wanted_mod `elem` excl_mods
1603 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1604 = do -- Find its new timestamp; all the
1605 -- ModSummaries in the old map have valid ml_hs_files
1606 let location = ms_location old_summary
1607 src_fn = expectJust "summariseModule" (ml_hs_file location)
1609 -- check the modification time on the source file, and
1610 -- return the cached summary if it hasn't changed. If the
1611 -- file has disappeared, we need to call the Finder again.
1613 Just (_,t) -> check_timestamp old_summary location src_fn t
1615 m <- System.IO.Error.try (getModificationTime src_fn)
1617 Right t -> check_timestamp old_summary location src_fn t
1618 Left e | isDoesNotExistError e -> find_it
1619 | otherwise -> ioError e
1621 | otherwise = find_it
1623 dflags = hsc_dflags hsc_env
1625 hsc_src = if is_boot then HsBootFile else HsSrcFile
1627 check_timestamp old_summary location src_fn src_timestamp
1628 | ms_hs_date old_summary == src_timestamp = do
1629 -- update the object-file timestamp
1630 obj_timestamp <- getObjTimestamp location is_boot
1631 return (Just old_summary{ ms_obj_date = obj_timestamp })
1633 -- source changed: re-summarise.
1634 new_summary location (ms_mod old_summary) src_fn src_timestamp
1637 -- Don't use the Finder's cache this time. If the module was
1638 -- previously a package module, it may have now appeared on the
1639 -- search path, so we want to consider it to be a home module. If
1640 -- the module was previously a home module, it may have moved.
1641 uncacheModule hsc_env wanted_mod
1642 found <- findImportedModule hsc_env wanted_mod Nothing
1645 | isJust (ml_hs_file location) ->
1647 just_found location mod
1649 -- Drop external-pkg
1650 ASSERT(modulePackageId mod /= thisPackage dflags)
1654 err -> noModError dflags loc wanted_mod err
1657 just_found location mod = do
1658 -- Adjust location to point to the hs-boot source file,
1659 -- hi file, object file, when is_boot says so
1660 let location' | is_boot = addBootSuffixLocn location
1661 | otherwise = location
1662 src_fn = expectJust "summarise2" (ml_hs_file location')
1664 -- Check that it exists
1665 -- It might have been deleted since the Finder last found it
1666 maybe_t <- modificationTimeIfExists src_fn
1668 Nothing -> noHsFileErr loc src_fn
1669 Just t -> new_summary location' mod src_fn t
1672 new_summary location mod src_fn src_timestamp
1674 -- Preprocess the source file and get its imports
1675 -- The dflags' contains the OPTIONS pragmas
1676 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1677 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1679 when (mod_name /= wanted_mod) $
1680 throwDyn $ mkPlainErrMsg mod_loc $
1681 text "file name does not match module name"
1682 <+> quotes (ppr mod_name)
1684 -- Find the object timestamp, and return the summary
1685 obj_timestamp <- getObjTimestamp location is_boot
1687 return (Just ( ModSummary { ms_mod = mod,
1688 ms_hsc_src = hsc_src,
1689 ms_location = location,
1690 ms_hspp_file = hspp_fn,
1691 ms_hspp_opts = dflags',
1692 ms_hspp_buf = Just buf,
1693 ms_srcimps = srcimps,
1695 ms_hs_date = src_timestamp,
1696 ms_obj_date = obj_timestamp }))
1699 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1700 getObjTimestamp location is_boot
1701 = if is_boot then return Nothing
1702 else modificationTimeIfExists (ml_obj_file location)
1705 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1706 -> IO (DynFlags, FilePath, StringBuffer)
1707 preprocessFile dflags src_fn mb_phase Nothing
1709 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1710 buf <- hGetStringBuffer hspp_fn
1711 return (dflags', hspp_fn, buf)
1713 preprocessFile dflags src_fn mb_phase (Just (buf, _time))
1715 -- case we bypass the preprocessing stage?
1717 local_opts = getOptions buf src_fn
1719 (dflags', _errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1720 -- XXX: shouldn't we be reporting the errors?
1724 | Just (Unlit _) <- mb_phase = True
1725 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1726 -- note: local_opts is only required if there's no Unlit phase
1727 | dopt Opt_Cpp dflags' = True
1728 | dopt Opt_Pp dflags' = True
1731 when needs_preprocessing $
1732 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1734 return (dflags', src_fn, buf)
1737 -----------------------------------------------------------------------------
1739 -----------------------------------------------------------------------------
1741 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1742 -- ToDo: we don't have a proper line number for this error
1743 noModError dflags loc wanted_mod err
1744 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1746 noHsFileErr :: SrcSpan -> String -> a
1747 noHsFileErr loc path
1748 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1750 packageModErr :: ModuleName -> a
1752 = throwDyn $ mkPlainErrMsg noSrcSpan $
1753 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1755 multiRootsErr :: [ModSummary] -> IO ()
1756 multiRootsErr [] = panic "multiRootsErr"
1757 multiRootsErr summs@(summ1:_)
1758 = throwDyn $ mkPlainErrMsg noSrcSpan $
1759 text "module" <+> quotes (ppr mod) <+>
1760 text "is defined in multiple files:" <+>
1761 sep (map text files)
1764 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1766 cyclicModuleErr :: [ModSummary] -> SDoc
1768 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1769 2 (vcat (map show_one ms))
1771 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1772 nest 2 $ ptext SLIT("imports:") <+>
1773 (pp_imps HsBootFile (ms_srcimps ms)
1774 $$ pp_imps HsSrcFile (ms_imps ms))]
1775 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1776 pp_imps src mods = fsep (map (show_mod src) mods)
1779 -- | Inform GHC that the working directory has changed. GHC will flush
1780 -- its cache of module locations, since it may no longer be valid.
1781 -- Note: if you change the working directory, you should also unload
1782 -- the current program (set targets to empty, followed by load).
1783 workingDirectoryChanged :: Session -> IO ()
1784 workingDirectoryChanged s = withSession s $ flushFinderCaches
1786 -- -----------------------------------------------------------------------------
1787 -- inspecting the session
1789 -- | Get the module dependency graph.
1790 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1791 getModuleGraph s = withSession s (return . hsc_mod_graph)
1793 isLoaded :: Session -> ModuleName -> IO Bool
1794 isLoaded s m = withSession s $ \hsc_env ->
1795 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1797 getBindings :: Session -> IO [TyThing]
1798 getBindings s = withSession s $ \hsc_env ->
1799 -- we have to implement the shadowing behaviour of ic_tmp_ids here
1800 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
1802 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
1803 filtered = foldr f (const []) tmp_ids emptyUniqSet
1805 | uniq `elementOfUniqSet` set = rest set
1806 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
1807 where uniq = getUnique (nameOccName (idName id))
1811 getPrintUnqual :: Session -> IO PrintUnqualified
1812 getPrintUnqual s = withSession s $ \hsc_env ->
1813 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
1815 -- | Container for information about a 'Module'.
1816 data ModuleInfo = ModuleInfo {
1817 minf_type_env :: TypeEnv,
1818 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1819 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1820 minf_instances :: [Instance]
1822 ,minf_modBreaks :: ModBreaks
1824 -- ToDo: this should really contain the ModIface too
1826 -- We don't want HomeModInfo here, because a ModuleInfo applies
1827 -- to package modules too.
1829 -- | Request information about a loaded 'Module'
1830 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1831 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1832 let mg = hsc_mod_graph hsc_env
1833 if mdl `elem` map ms_mod mg
1834 then getHomeModuleInfo hsc_env (moduleName mdl)
1836 {- if isHomeModule (hsc_dflags hsc_env) mdl
1838 else -} getPackageModuleInfo hsc_env mdl
1839 -- getPackageModuleInfo will attempt to find the interface, so
1840 -- we don't want to call it for a home module, just in case there
1841 -- was a problem loading the module and the interface doesn't
1842 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1844 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1846 getPackageModuleInfo hsc_env mdl = do
1847 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1849 Nothing -> return Nothing
1851 eps <- readIORef (hsc_EPS hsc_env)
1853 names = availsToNameSet avails
1855 tys = [ ty | name <- concatMap availNames avails,
1856 Just ty <- [lookupTypeEnv pte name] ]
1858 return (Just (ModuleInfo {
1859 minf_type_env = mkTypeEnv tys,
1860 minf_exports = names,
1861 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1862 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1863 minf_modBreaks = emptyModBreaks
1866 getPackageModuleInfo _hsc_env _mdl = do
1867 -- bogusly different for non-GHCI (ToDo)
1871 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
1872 getHomeModuleInfo hsc_env mdl =
1873 case lookupUFM (hsc_HPT hsc_env) mdl of
1874 Nothing -> return Nothing
1876 let details = hm_details hmi
1877 return (Just (ModuleInfo {
1878 minf_type_env = md_types details,
1879 minf_exports = availsToNameSet (md_exports details),
1880 minf_rdr_env = mi_globals $! hm_iface hmi,
1881 minf_instances = md_insts details
1883 ,minf_modBreaks = getModBreaks hmi
1887 -- | The list of top-level entities defined in a module
1888 modInfoTyThings :: ModuleInfo -> [TyThing]
1889 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1891 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1892 modInfoTopLevelScope minf
1893 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1895 modInfoExports :: ModuleInfo -> [Name]
1896 modInfoExports minf = nameSetToList $! minf_exports minf
1898 -- | Returns the instances defined by the specified module.
1899 -- Warning: currently unimplemented for package modules.
1900 modInfoInstances :: ModuleInfo -> [Instance]
1901 modInfoInstances = minf_instances
1903 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1904 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1906 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
1907 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
1908 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1910 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1911 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1912 case lookupTypeEnv (minf_type_env minf) name of
1913 Just tyThing -> return (Just tyThing)
1915 eps <- readIORef (hsc_EPS hsc_env)
1916 return $! lookupType (hsc_dflags hsc_env)
1917 (hsc_HPT hsc_env) (eps_PTE eps) name
1920 modInfoModBreaks :: ModuleInfo -> ModBreaks
1921 modInfoModBreaks = minf_modBreaks
1924 isDictonaryId :: Id -> Bool
1926 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1928 -- | Looks up a global name: that is, any top-level name in any
1929 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1930 -- the interactive context, and therefore does not require a preceding
1932 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1933 lookupGlobalName s name = withSession s $ \hsc_env -> do
1934 eps <- readIORef (hsc_EPS hsc_env)
1935 return $! lookupType (hsc_dflags hsc_env)
1936 (hsc_HPT hsc_env) (eps_PTE eps) name
1938 -- -----------------------------------------------------------------------------
1939 -- Misc exported utils
1941 dataConType :: DataCon -> Type
1942 dataConType dc = idType (dataConWrapId dc)
1944 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1945 pprParenSymName :: NamedThing a => a -> SDoc
1946 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1948 -- ----------------------------------------------------------------------------
1953 -- - Data and Typeable instances for HsSyn.
1955 -- ToDo: check for small transformations that happen to the syntax in
1956 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1958 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1959 -- to get from TyCons, Ids etc. to TH syntax (reify).
1961 -- :browse will use either lm_toplev or inspect lm_interface, depending
1962 -- on whether the module is interpreted or not.
1964 -- This is for reconstructing refactored source code
1965 -- Calls the lexer repeatedly.
1966 -- ToDo: add comment tokens to token stream
1967 getTokenStream :: Session -> Module -> IO [Located Token]
1970 -- -----------------------------------------------------------------------------
1971 -- Interactive evaluation
1973 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1974 -- filesystem and package database to find the corresponding 'Module',
1975 -- using the algorithm that is used for an @import@ declaration.
1976 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1977 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1979 dflags = hsc_dflags hsc_env
1980 hpt = hsc_HPT hsc_env
1981 this_pkg = thisPackage dflags
1983 case lookupUFM hpt mod_name of
1984 Just mod_info -> return (mi_module (hm_iface mod_info))
1985 _not_a_home_module -> do
1986 res <- findImportedModule hsc_env mod_name maybe_pkg
1988 Found _ m | modulePackageId m /= this_pkg -> return m
1989 | otherwise -> throwDyn (CmdLineError (showSDoc $
1990 text "module" <+> pprModule m <+>
1991 text "is not loaded"))
1992 err -> let msg = cannotFindModule dflags mod_name err in
1993 throwDyn (CmdLineError (showSDoc msg))
1996 getHistorySpan :: Session -> History -> IO SrcSpan
1997 getHistorySpan sess h = withSession sess $ \hsc_env ->
1998 return$ InteractiveEval.getHistorySpan hsc_env h
2000 obtainTerm :: Session -> Bool -> Id -> IO Term
2001 obtainTerm sess force id = withSession sess $ \hsc_env ->
2002 InteractiveEval.obtainTerm hsc_env force id
2004 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2005 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2006 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2008 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2009 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2010 InteractiveEval.obtainTermB hsc_env bound force id