1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
12 defaultCleanupHandler,
15 Ghc, GhcT, GhcMonad(..),
16 runGhc, runGhcT, initGhcMonad,
17 gcatch, gbracket, gfinally,
18 clearWarnings, getWarnings, hasWarnings,
19 printExceptionAndWarnings, printWarnings,
22 -- * Flags and settings
23 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
24 GhcMode(..), GhcLink(..), defaultObjectTarget,
31 Target(..), TargetId(..), Phase,
38 -- * Extending the program scope
41 extendGlobalTypeScope,
44 -- * Loading\/compiling the program
46 load, loadWithCompiler, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
47 workingDirectoryChanged,
48 parseModule, typecheckModule, desugarModule, loadModule,
49 ParsedModule, TypecheckedModule, DesugaredModule, -- all abstract
50 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
51 moduleInfo, renamedSource, typecheckedSource,
52 parsedSource, coreModule,
53 compileToCoreModule, compileToCoreSimplified,
56 -- * Parsing Haddock comments
59 -- * Inspecting the module structure of the program
60 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
65 -- * Inspecting modules
72 modInfoIsExportedName,
75 mkPrintUnqualifiedForModule,
78 PrintUnqualified, alwaysQualify,
80 -- * Interactive evaluation
81 getBindings, getPrintUnqual,
84 setContext, getContext,
94 runStmt, SingleStep(..),
96 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
97 resumeHistory, resumeHistoryIx),
98 History(historyBreakInfo, historyEnclosingDecl),
99 GHC.getHistorySpan, getHistoryModule,
102 InteractiveEval.back,
103 InteractiveEval.forward,
106 InteractiveEval.compileExpr, HValue, dynCompileExpr,
108 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
110 ModBreaks(..), BreakIndex,
111 BreakInfo(breakInfo_number, breakInfo_module),
112 BreakArray, setBreakOn, setBreakOff, getBreak,
115 -- * Abstract syntax elements
121 Module, mkModule, pprModule, moduleName, modulePackageId,
122 ModuleName, mkModuleName, moduleNameString,
126 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
128 RdrName(Qual,Unqual),
132 isImplicitId, isDeadBinder,
133 isExportedId, isLocalId, isGlobalId,
135 isPrimOpId, isFCallId, isClassOpId_maybe,
136 isDataConWorkId, idDataCon,
137 isBottomingId, isDictonaryId,
138 recordSelectorFieldLabel,
140 -- ** Type constructors
142 tyConTyVars, tyConDataCons, tyConArity,
143 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
145 synTyConDefn, synTyConType, synTyConResKind,
151 -- ** Data constructors
153 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
154 dataConIsInfix, isVanillaDataCon,
156 StrictnessMark(..), isMarkedStrict,
160 classMethods, classSCTheta, classTvsFds,
165 instanceDFunId, pprInstance, pprInstanceHdr,
167 -- ** Types and Kinds
168 Type, splitForAllTys, funResultTy,
169 pprParendType, pprTypeApp,
172 ThetaType, pprThetaArrow,
178 module HsSyn, -- ToDo: remove extraneous bits
182 defaultFixity, maxPrecedence,
186 -- ** Source locations
188 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
189 srcLocFile, srcLocLine, srcLocCol,
191 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
192 srcSpanStart, srcSpanEnd,
194 srcSpanStartLine, srcSpanEndLine,
195 srcSpanStartCol, srcSpanEndCol,
198 GhcException(..), showGhcException,
208 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
209 * what StaticFlags should we expose, if any?
212 #include "HsVersions.h"
215 import qualified Linker
216 import Linker ( HValue )
220 import InteractiveEval
225 import TcRnTypes hiding (LIE)
226 import TcRnMonad ( initIfaceCheck )
230 import qualified HsSyn -- hack as we want to reexport the whole module
231 import HsSyn hiding ((<.>))
232 import Type hiding (typeKind)
233 import TcType hiding (typeKind)
236 import TysPrim ( alphaTyVars )
241 import Name hiding ( varName )
242 import OccName ( parenSymOcc )
243 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
245 import FamInstEnv ( emptyFamInstEnv )
249 import DriverPipeline
250 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
256 import StaticFlagParser
257 import qualified StaticFlags
258 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
267 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
271 import StringBuffer ( StringBuffer, hGetStringBuffer )
274 import Maybes ( expectJust, mapCatMaybes )
276 import HaddockLex ( tokenise )
279 import Control.Concurrent
280 import System.Directory ( getModificationTime, doesFileExist,
281 getCurrentDirectory )
284 import qualified Data.List as List
286 import System.Exit ( exitWith, ExitCode(..) )
287 import System.Time ( ClockTime, getClockTime )
290 import System.FilePath
292 import System.IO.Error ( try, isDoesNotExistError )
293 #if __GLASGOW_HASKELL__ >= 609
294 import Data.Typeable (cast)
296 import Prelude hiding (init)
299 -- -----------------------------------------------------------------------------
300 -- Exception handlers
302 -- | Install some default exception handlers and run the inner computation.
303 -- Unless you want to handle exceptions yourself, you should wrap this around
304 -- the top level of your program. The default handlers output the error
305 -- message(s) to stderr and exit cleanly.
306 defaultErrorHandler :: DynFlags -> IO a -> IO a
307 defaultErrorHandler dflags inner =
308 -- top-level exception handler: any unrecognised exception is a compiler bug.
309 #if __GLASGOW_HASKELL__ < 609
310 handle (\exception -> do
313 -- an IO exception probably isn't our fault, so don't panic
315 fatalErrorMsg dflags (text (show exception))
316 AsyncException StackOverflow ->
317 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
318 ExitException _ -> throw exception
320 fatalErrorMsg dflags (text (show (Panic (show exception))))
321 exitWith (ExitFailure 1)
324 handle (\(SomeException exception) -> do
326 case cast exception of
327 -- an IO exception probably isn't our fault, so don't panic
328 Just (ioe :: IOException) ->
329 fatalErrorMsg dflags (text (show ioe))
330 _ -> case cast exception of
331 Just StackOverflow ->
332 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
333 _ -> case cast exception of
334 Just (ex :: ExitCode) -> throw ex
337 (text (show (Panic (show exception))))
338 exitWith (ExitFailure 1)
342 -- program errors: messages with locations attached. Sometimes it is
343 -- convenient to just throw these as exceptions.
345 (\em -> do printBagOfErrors dflags (unitBag em)
346 exitWith (ExitFailure 1)) $
348 -- error messages propagated as exceptions
353 PhaseFailed _ code -> exitWith code
354 Interrupted -> exitWith (ExitFailure 1)
355 _ -> do fatalErrorMsg dflags (text (show ge))
356 exitWith (ExitFailure 1)
360 -- | Install a default cleanup handler to remove temporary files deposited by
361 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
362 -- want to override the error handling, but still get the ordinary cleanup
364 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
365 DynFlags -> m a -> m a
366 defaultCleanupHandler dflags inner =
367 -- make sure we clean up after ourselves
370 cleanTempFiles dflags
373 -- exceptions will be blocked while we clean the temporary files,
374 -- so there shouldn't be any difficulty if we receive further
377 -- | Print the error message and all warnings. Useful inside exception
378 -- handlers. Clears warnings after printing.
379 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
380 printExceptionAndWarnings err = do
381 let errs = srcErrorMessages err
383 dflags <- getSessionDynFlags
385 -- Empty errors means we failed due to -Werror. (Since this function
386 -- takes a source error as argument, we know for sure _some_ error
387 -- did indeed happen.)
389 printBagOfWarnings dflags warns
390 printBagOfErrors dflags (unitBag warnIsErrorMsg)
391 else liftIO $ printBagOfErrors dflags errs
394 -- | Print all accumulated warnings using 'log_action'.
395 printWarnings :: GhcMonad m => m ()
397 dflags <- getSessionDynFlags
399 liftIO $ printBagOfWarnings dflags warns
402 -- | Run function for the 'Ghc' monad.
404 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
405 -- to this function will create a new session which should not be shared among
408 -- Any errors not handled inside the 'Ghc' action are propagated as IO
411 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
412 -> Ghc a -- ^ The action to perform.
414 runGhc mb_top_dir ghc = do
415 wref <- newIORef emptyBag
416 ref <- newIORef undefined
417 let session = Session ref wref
418 flip unGhc session $ do
419 initGhcMonad mb_top_dir
421 -- XXX: unregister interrupt handlers here?
423 -- | Run function for 'GhcT' monad transformer.
425 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
426 -- to this function will create a new session which should not be shared among
429 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
430 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
431 -> GhcT m a -- ^ The action to perform.
433 runGhcT mb_top_dir ghct = do
434 wref <- liftIO $ newIORef emptyBag
435 ref <- liftIO $ newIORef undefined
436 let session = Session ref wref
437 flip unGhcT session $ do
438 initGhcMonad mb_top_dir
441 -- | Initialise a GHC session.
443 -- If you implement a custom 'GhcMonad' you must call this function in the
444 -- monad run function. It will initialise the session variable and clear all
447 -- The first argument should point to the directory where GHC's library files
448 -- reside. More precisely, this should be the output of @ghc --print-libdir@
449 -- of the version of GHC the module using this API is compiled with. For
450 -- portability, you should use the @ghc-paths@ package, available at
451 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
453 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
454 initGhcMonad mb_top_dir = do
456 main_thread <- liftIO $ myThreadId
457 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
458 liftIO $ installSignalHandlers
460 liftIO $ StaticFlags.initStaticOpts
462 dflags0 <- liftIO $ initDynFlags defaultDynFlags
463 dflags <- liftIO $ initSysTools mb_top_dir dflags0
464 env <- liftIO $ newHscEnv dflags
468 -- -----------------------------------------------------------------------------
471 -- | Grabs the DynFlags from the Session
472 getSessionDynFlags :: GhcMonad m => m DynFlags
473 getSessionDynFlags = withSession (return . hsc_dflags)
475 -- | Updates the DynFlags in a Session. This also reads
476 -- the package database (unless it has already been read),
477 -- and prepares the compilers knowledge about packages. It
478 -- can be called again to load new packages: just add new
479 -- package flags to (packageFlags dflags).
481 -- Returns a list of new packages that may need to be linked in using
482 -- the dynamic linker (see 'linkPackages') as a result of new package
483 -- flags. If you are not doing linking or doing static linking, you
484 -- can ignore the list of packages returned.
486 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
487 setSessionDynFlags dflags = do
488 (dflags', preload) <- liftIO $ initPackages dflags
489 modifySession (\h -> h{ hsc_dflags = dflags' })
492 -- | If there is no -o option, guess the name of target executable
493 -- by using top-level source file name as a base.
494 guessOutputFile :: GhcMonad m => m ()
495 guessOutputFile = modifySession $ \env ->
496 let dflags = hsc_dflags env
497 mod_graph = hsc_mod_graph env
498 mainModuleSrcPath :: Maybe String
499 mainModuleSrcPath = do
500 let isMain = (== mainModIs dflags) . ms_mod
501 [ms] <- return (filter isMain mod_graph)
502 ml_hs_file (ms_location ms)
503 name = fmap dropExtension mainModuleSrcPath
505 #if defined(mingw32_HOST_OS)
506 -- we must add the .exe extention unconditionally here, otherwise
507 -- when name has an extension of its own, the .exe extension will
508 -- not be added by DriverPipeline.exeFileName. See #2248
509 name_exe = fmap (<.> "exe") name
514 case outputFile dflags of
516 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
518 -- -----------------------------------------------------------------------------
521 -- ToDo: think about relative vs. absolute file paths. And what
522 -- happens when the current directory changes.
524 -- | Sets the targets for this session. Each target may be a module name
525 -- or a filename. The targets correspond to the set of root modules for
526 -- the program\/library. Unloading the current program is achieved by
527 -- setting the current set of targets to be empty, followed by 'load'.
528 setTargets :: GhcMonad m => [Target] -> m ()
529 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
531 -- | Returns the current set of targets
532 getTargets :: GhcMonad m => m [Target]
533 getTargets = withSession (return . hsc_targets)
535 -- | Add another target.
536 addTarget :: GhcMonad m => Target -> m ()
538 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
541 removeTarget :: GhcMonad m => TargetId -> m ()
542 removeTarget target_id
543 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
545 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
547 -- | Attempts to guess what Target a string refers to. This function
548 -- implements the @--make@/GHCi command-line syntax for filenames:
550 -- - if the string looks like a Haskell source filename, then interpret it
553 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
556 -- - otherwise interpret the string as a module name
558 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
559 guessTarget str (Just phase)
560 = return (Target (TargetFile str (Just phase)) True Nothing)
561 guessTarget str Nothing
562 | isHaskellSrcFilename file
563 = return (target (TargetFile file Nothing))
565 = do exists <- liftIO $ doesFileExist hs_file
567 then return (target (TargetFile hs_file Nothing))
569 exists <- liftIO $ doesFileExist lhs_file
571 then return (target (TargetFile lhs_file Nothing))
573 if looksLikeModuleName file
574 then return (target (TargetModule (mkModuleName file)))
577 (ProgramError (showSDoc $
578 text "target" <+> quotes (text file) <+>
579 text "is not a module name or a source file"))
582 | '*':rest <- str = (rest, False)
583 | otherwise = (str, True)
585 hs_file = file <.> "hs"
586 lhs_file = file <.> "lhs"
588 target tid = Target tid obj_allowed Nothing
590 -- -----------------------------------------------------------------------------
591 -- Extending the program scope
593 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
594 extendGlobalRdrScope rdrElts
595 = modifySession $ \hscEnv ->
596 let global_rdr = hsc_global_rdr_env hscEnv
597 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
599 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
600 setGlobalRdrScope rdrElts
601 = modifySession $ \hscEnv ->
602 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
604 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
605 extendGlobalTypeScope ids
606 = modifySession $ \hscEnv ->
607 let global_type = hsc_global_type_env hscEnv
608 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
610 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
611 setGlobalTypeScope ids
612 = modifySession $ \hscEnv ->
613 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
615 -- -----------------------------------------------------------------------------
616 -- Parsing Haddock comments
618 parseHaddockComment :: String -> Either String (HsDoc RdrName)
619 parseHaddockComment string =
620 case parseHaddockParagraphs (tokenise string) of
624 -- -----------------------------------------------------------------------------
625 -- Loading the program
627 -- | Perform a dependency analysis starting from the current targets
628 -- and update the session with the new module graph.
629 depanal :: GhcMonad m =>
630 [ModuleName] -- ^ excluded modules
631 -> Bool -- ^ allow duplicate roots
633 depanal excluded_mods allow_dup_roots = do
634 hsc_env <- getSession
636 dflags = hsc_dflags hsc_env
637 targets = hsc_targets hsc_env
638 old_graph = hsc_mod_graph hsc_env
640 liftIO $ showPass dflags "Chasing dependencies"
641 liftIO $ debugTraceMsg dflags 2 (hcat [
642 text "Chasing modules from: ",
643 hcat (punctuate comma (map pprTarget targets))])
645 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
646 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
651 | LoadUpTo ModuleName
652 | LoadDependenciesOf ModuleName
654 -- | Try to load the program. Calls 'loadWithCompiler' with the default
655 -- compiler that just immediately logs all warnings and errors.
656 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
658 loadWithCompiler defaultCompiler how_much
660 defaultCompiler env mod_summary mod_index mod_count
661 mb_old_iface mb_linkable =
662 handleSourceError logErrorsAndRethrowException $ do
663 home_mod_info <- compile env mod_summary mod_index mod_count
664 mb_old_iface mb_linkable
668 logErrorsAndRethrowException err = do
669 printExceptionAndWarnings err
672 -- | Try to load the program. If a Module is supplied, then just
673 -- attempt to load up to this target. If no Module is supplied,
674 -- then try to load all targets.
676 -- The first argument is a function that is called to compile a single module.
677 -- The arguments are the same as 'DriverPipeline.compile'. Use this function
678 -- to intercept warns and errors from a single module compilation. (Don't
679 -- forget to actually call 'DriverPipeline.compile' inside that function.
680 -- XXX: this could be enforced by changing 'ModuleCompiler' to return a static
681 -- capability which can only be obtained by calling 'DriverPipeline.compile'.)
683 loadWithCompiler :: GhcMonad m => ModuleCompiler -> LoadHowMuch -> m SuccessFlag
684 loadWithCompiler module_compiler how_much = do
685 -- Dependency analysis first. Note that this fixes the module graph:
686 -- even if we don't get a fully successful upsweep, the full module
687 -- graph is still retained in the Session. We can tell which modules
688 -- were successfully loaded by inspecting the Session's HPT.
689 mod_graph <- depanal [] False
690 load2 how_much mod_graph module_compiler
692 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary] -> ModuleCompiler
694 load2 how_much mod_graph mod_comp = do
696 hsc_env <- getSession
698 let hpt1 = hsc_HPT hsc_env
699 let dflags = hsc_dflags hsc_env
701 -- The "bad" boot modules are the ones for which we have
702 -- B.hs-boot in the module graph, but no B.hs
703 -- The downsweep should have ensured this does not happen
705 let all_home_mods = [ms_mod_name s
706 | s <- mod_graph, not (isBootSummary s)]
707 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
708 not (ms_mod_name s `elem` all_home_mods)]
709 ASSERT( null bad_boot_mods ) return ()
711 -- check that the module given in HowMuch actually exists, otherwise
712 -- topSortModuleGraph will bomb later.
713 let checkHowMuch (LoadUpTo m) = checkMod m
714 checkHowMuch (LoadDependenciesOf m) = checkMod m
718 | m `elem` all_home_mods = and_then
720 liftIO $ errorMsg dflags (text "no such module:" <+>
724 checkHowMuch how_much $ do
726 -- mg2_with_srcimps drops the hi-boot nodes, returning a
727 -- graph with cycles. Among other things, it is used for
728 -- backing out partially complete cycles following a failed
729 -- upsweep, and for removing from hpt all the modules
730 -- not in strict downwards closure, during calls to compile.
731 let mg2_with_srcimps :: [SCC ModSummary]
732 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
734 -- If we can determine that any of the {-# SOURCE #-} imports
735 -- are definitely unnecessary, then emit a warning.
736 warnUnnecessarySourceImports dflags mg2_with_srcimps
739 -- check the stability property for each module.
740 stable_mods@(stable_obj,stable_bco)
741 = checkStability hpt1 mg2_with_srcimps all_home_mods
743 -- prune bits of the HPT which are definitely redundant now,
745 pruned_hpt = pruneHomePackageTable hpt1
746 (flattenSCCs mg2_with_srcimps)
749 liftIO $ evaluate pruned_hpt
751 -- before we unload anything, make sure we don't leave an old
752 -- interactive context around pointing to dead bindings. Also,
753 -- write the pruned HPT to allow the old HPT to be GC'd.
754 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
755 hsc_HPT = pruned_hpt }
757 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
758 text "Stable BCO:" <+> ppr stable_bco)
760 -- Unload any modules which are going to be re-linked this time around.
761 let stable_linkables = [ linkable
762 | m <- stable_obj++stable_bco,
763 Just hmi <- [lookupUFM pruned_hpt m],
764 Just linkable <- [hm_linkable hmi] ]
765 liftIO $ unload hsc_env stable_linkables
767 -- We could at this point detect cycles which aren't broken by
768 -- a source-import, and complain immediately, but it seems better
769 -- to let upsweep_mods do this, so at least some useful work gets
770 -- done before the upsweep is abandoned.
771 --hPutStrLn stderr "after tsort:\n"
772 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
774 -- Now do the upsweep, calling compile for each module in
775 -- turn. Final result is version 3 of everything.
777 -- Topologically sort the module graph, this time including hi-boot
778 -- nodes, and possibly just including the portion of the graph
779 -- reachable from the module specified in the 2nd argument to load.
780 -- This graph should be cycle-free.
781 -- If we're restricting the upsweep to a portion of the graph, we
782 -- also want to retain everything that is still stable.
783 let full_mg :: [SCC ModSummary]
784 full_mg = topSortModuleGraph False mod_graph Nothing
786 maybe_top_mod = case how_much of
788 LoadDependenciesOf m -> Just m
791 partial_mg0 :: [SCC ModSummary]
792 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
794 -- LoadDependenciesOf m: we want the upsweep to stop just
795 -- short of the specified module (unless the specified module
798 | LoadDependenciesOf _mod <- how_much
799 = ASSERT( case last partial_mg0 of
800 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
801 List.init partial_mg0
807 | AcyclicSCC ms <- full_mg,
808 ms_mod_name ms `elem` stable_obj++stable_bco,
809 ms_mod_name ms `notElem` [ ms_mod_name ms' |
810 AcyclicSCC ms' <- partial_mg ] ]
812 mg = stable_mg ++ partial_mg
814 -- clean up between compilations
815 let cleanup = cleanTempFilesExcept dflags
816 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
818 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
820 (upsweep_ok, hsc_env1, modsUpswept)
822 (hsc_env { hsc_HPT = emptyHomePackageTable })
823 pruned_hpt stable_mods cleanup mg
825 -- Make modsDone be the summaries for each home module now
826 -- available; this should equal the domain of hpt3.
827 -- Get in in a roughly top .. bottom order (hence reverse).
829 let modsDone = reverse modsUpswept
831 -- Try and do linking in some form, depending on whether the
832 -- upsweep was completely or only partially successful.
834 if succeeded upsweep_ok
837 -- Easy; just relink it all.
838 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
840 -- Clean up after ourselves
841 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
843 -- Issue a warning for the confusing case where the user
844 -- said '-o foo' but we're not going to do any linking.
845 -- We attempt linking if either (a) one of the modules is
846 -- called Main, or (b) the user said -no-hs-main, indicating
847 -- that main() is going to come from somewhere else.
849 let ofile = outputFile dflags
850 let no_hs_main = dopt Opt_NoHsMain dflags
852 main_mod = mainModIs dflags
853 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
854 do_linking = a_root_is_Main || no_hs_main
856 when (ghcLink dflags == LinkBinary
857 && isJust ofile && not do_linking) $
858 liftIO $ debugTraceMsg dflags 1 $
859 text ("Warning: output was redirected with -o, " ++
860 "but no output will be generated\n" ++
861 "because there is no " ++
862 moduleNameString (moduleName main_mod) ++ " module.")
864 -- link everything together
865 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
867 loadFinish Succeeded linkresult hsc_env1
870 -- Tricky. We need to back out the effects of compiling any
871 -- half-done cycles, both so as to clean up the top level envs
872 -- and to avoid telling the interactive linker to link them.
873 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
876 = map ms_mod modsDone
877 let mods_to_zap_names
878 = findPartiallyCompletedCycles modsDone_names
881 = filter ((`notElem` mods_to_zap_names).ms_mod)
884 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
887 -- Clean up after ourselves
888 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
890 -- there should be no Nothings where linkables should be, now
891 ASSERT(all (isJust.hm_linkable)
892 (eltsUFM (hsc_HPT hsc_env))) do
894 -- Link everything together
895 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
897 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
898 loadFinish Failed linkresult hsc_env4
900 -- Finish up after a load.
902 -- If the link failed, unload everything and return.
903 loadFinish :: GhcMonad m =>
904 SuccessFlag -> SuccessFlag -> HscEnv
906 loadFinish _all_ok Failed hsc_env
907 = do liftIO $ unload hsc_env []
908 modifySession $ \_ -> discardProg hsc_env
911 -- Empty the interactive context and set the module context to the topmost
912 -- newly loaded module, or the Prelude if none were loaded.
913 loadFinish all_ok Succeeded hsc_env
914 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
918 -- Forget the current program, but retain the persistent info in HscEnv
919 discardProg :: HscEnv -> HscEnv
921 = hsc_env { hsc_mod_graph = emptyMG,
922 hsc_IC = emptyInteractiveContext,
923 hsc_HPT = emptyHomePackageTable }
925 -- used to fish out the preprocess output files for the purposes of
926 -- cleaning up. The preprocessed file *might* be the same as the
927 -- source file, but that doesn't do any harm.
928 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
929 ppFilesFromSummaries summaries = map ms_hspp_file summaries
931 -- -----------------------------------------------------------------------------
933 class ParsedMod m where
934 modSummary :: m -> ModSummary
935 parsedSource :: m -> ParsedSource
937 class ParsedMod m => TypecheckedMod m where
938 renamedSource :: m -> Maybe RenamedSource
939 typecheckedSource :: m -> TypecheckedSource
940 moduleInfo :: m -> ModuleInfo
941 tm_internals :: m -> (TcGblEnv, ModDetails)
942 -- ToDo: improvements that could be made here:
943 -- if the module succeeded renaming but not typechecking,
944 -- we can still get back the GlobalRdrEnv and exports, so
945 -- perhaps the ModuleInfo should be split up into separate
948 class TypecheckedMod m => DesugaredMod m where
949 coreModule :: m -> ModGuts
951 -- | The result of successful parsing.
953 ParsedModule { pm_mod_summary :: ModSummary
954 , pm_parsed_source :: ParsedSource }
956 instance ParsedMod ParsedModule where
957 modSummary m = pm_mod_summary m
958 parsedSource m = pm_parsed_source m
960 -- | The result of successful typechecking. It also contains the parser
962 data TypecheckedModule =
963 TypecheckedModule { tm_parsed_module :: ParsedModule
964 , tm_renamed_source :: Maybe RenamedSource
965 , tm_typechecked_source :: TypecheckedSource
966 , tm_checked_module_info :: ModuleInfo
967 , tm_internals_ :: (TcGblEnv, ModDetails)
970 instance ParsedMod TypecheckedModule where
971 modSummary m = modSummary (tm_parsed_module m)
972 parsedSource m = parsedSource (tm_parsed_module m)
974 instance TypecheckedMod TypecheckedModule where
975 renamedSource m = tm_renamed_source m
976 typecheckedSource m = tm_typechecked_source m
977 moduleInfo m = tm_checked_module_info m
978 tm_internals m = tm_internals_ m
980 -- | The result of successful desugaring (i.e., translation to core). Also
981 -- contains all the information of a typechecked module.
982 data DesugaredModule =
983 DesugaredModule { dm_typechecked_module :: TypecheckedModule
984 , dm_core_module :: ModGuts
987 instance ParsedMod DesugaredModule where
988 modSummary m = modSummary (dm_typechecked_module m)
989 parsedSource m = parsedSource (dm_typechecked_module m)
991 instance TypecheckedMod DesugaredModule where
992 renamedSource m = renamedSource (dm_typechecked_module m)
993 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
994 moduleInfo m = moduleInfo (dm_typechecked_module m)
995 tm_internals m = tm_internals_ (dm_typechecked_module m)
997 instance DesugaredMod DesugaredModule where
998 coreModule m = dm_core_module m
1000 type ParsedSource = Located (HsModule RdrName)
1001 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
1002 Maybe (HsDoc Name), HaddockModInfo Name)
1003 type TypecheckedSource = LHsBinds Id
1006 -- - things that aren't in the output of the typechecker right now:
1007 -- - the export list
1009 -- - type signatures
1010 -- - type/data/newtype declarations
1011 -- - class declarations
1013 -- - extra things in the typechecker's output:
1014 -- - default methods are turned into top-level decls.
1015 -- - dictionary bindings
1017 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1018 getModSummary mod = do
1019 mg <- liftM hsc_mod_graph getSession
1020 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
1021 [] -> throw $ mkApiErr (text "Module not part of module graph")
1024 -- | Parse a module.
1026 -- Throws a 'SourceError' on parse error.
1027 parseModule :: GhcMonad m => ModuleName -> m ParsedModule
1028 parseModule mod = do
1029 ms <- getModSummary mod
1030 hsc_env0 <- getSession
1031 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1032 rdr_module <- parseFile hsc_env ms
1033 return (ParsedModule ms rdr_module)
1035 -- | Typecheck and rename a parsed module.
1037 -- Throws a 'SourceError' if either fails.
1038 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1039 typecheckModule pmod = do
1040 let ms = modSummary pmod
1041 hsc_env0 <- getSession
1042 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1043 (tc_gbl_env, rn_info)
1044 <- typecheckRenameModule hsc_env ms (parsedSource pmod)
1045 details <- liftIO $ makeSimpleDetails hsc_env tc_gbl_env
1048 tm_internals_ = (tc_gbl_env, details),
1049 tm_parsed_module = pmod,
1050 tm_renamed_source = rn_info,
1051 tm_typechecked_source = tcg_binds tc_gbl_env,
1052 tm_checked_module_info =
1054 minf_type_env = md_types details,
1055 minf_exports = availsToNameSet $ md_exports details,
1056 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1057 minf_instances = md_insts details
1059 ,minf_modBreaks = emptyModBreaks
1063 -- | Desugar a typechecked module.
1064 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1065 desugarModule tcm = do
1066 let ms = modSummary tcm
1067 hsc_env0 <- getSession
1068 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1069 let (tcg, _) = tm_internals tcm
1070 guts <- deSugarModule hsc_env ms tcg
1073 dm_typechecked_module = tcm,
1074 dm_core_module = guts
1077 -- | Load a module. Input doesn't need to be desugared.
1079 -- XXX: Describe usage.
1080 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1082 let ms = modSummary tcm
1083 let mod = ms_mod_name ms
1084 hsc_env0 <- getSession
1085 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1086 let (tcg, details) = tm_internals tcm
1087 (iface,_) <- liftIO $ makeSimpleIface hsc_env Nothing tcg details
1088 let mod_info = HomeModInfo {
1090 hm_details = details,
1091 hm_linkable = Nothing }
1092 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
1093 modifySession $ \_ -> hsc_env0{ hsc_HPT = hpt_new }
1096 -- | This is the way to get access to the Core bindings corresponding
1097 -- to a module. 'compileToCore' parses, typechecks, and
1098 -- desugars the module, then returns the resulting Core module (consisting of
1099 -- the module name, type declarations, and function declarations) if
1101 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1102 compileToCoreModule = compileCore False
1104 -- | Like compileToCoreModule, but invokes the simplifier, so
1105 -- as to return simplified and tidied Core.
1106 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1107 compileToCoreSimplified = compileCore True
1109 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1110 -- bindings, but for most purposes, you probably want to call
1111 -- compileToCoreModule.
1112 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1113 compileToCore fn = do
1114 mod <- compileToCoreModule session fn
1115 return $ cm_binds mod
1117 -- | Takes a CoreModule and compiles the bindings therein
1118 -- to object code. The first argument is a bool flag indicating
1119 -- whether to run the simplifier.
1120 -- The resulting .o, .hi, and executable files, if any, are stored in the
1121 -- current directory, and named according to the module name.
1122 -- Returns True iff compilation succeeded.
1123 -- This has only so far been tested with a single self-contained module.
1124 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1125 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1126 hscEnv <- getSession
1127 dflags <- getSessionDynFlags
1128 currentTime <- liftIO $ getClockTime
1129 cwd <- liftIO $ getCurrentDirectory
1130 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1131 ((moduleNameSlashes . moduleName) mName)
1133 let modSummary = ModSummary { ms_mod = mName,
1134 ms_hsc_src = ExtCoreFile,
1135 ms_location = modLocation,
1136 -- By setting the object file timestamp to Nothing,
1137 -- we always force recompilation, which is what we
1138 -- want. (Thus it doesn't matter what the timestamp
1139 -- for the (nonexistent) source file is.)
1140 ms_hs_date = currentTime,
1141 ms_obj_date = Nothing,
1142 -- Only handling the single-module case for now, so no imports.
1147 ms_hspp_opts = dflags,
1148 ms_hspp_buf = Nothing
1151 ioMsgMaybe $ flip evalComp (CompState{ compHscEnv=hscEnv,
1152 compModSummary=modSummary,
1153 compOldIface=Nothing}) $
1154 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1155 | otherwise = return mod_guts
1156 in maybe_simplify (mkModGuts cm)
1162 -- Makes a "vanilla" ModGuts.
1163 mkModGuts :: CoreModule -> ModGuts
1164 mkModGuts coreModule = ModGuts {
1165 mg_module = cm_module coreModule,
1168 mg_deps = noDependencies,
1169 mg_dir_imps = emptyModuleEnv,
1170 mg_used_names = emptyNameSet,
1171 mg_rdr_env = emptyGlobalRdrEnv,
1172 mg_fix_env = emptyFixityEnv,
1173 mg_types = emptyTypeEnv,
1177 mg_binds = cm_binds coreModule,
1178 mg_foreign = NoStubs,
1179 mg_warns = NoWarnings,
1180 mg_hpc_info = emptyHpcInfo False,
1181 mg_modBreaks = emptyModBreaks,
1182 mg_vect_info = noVectInfo,
1183 mg_inst_env = emptyInstEnv,
1184 mg_fam_inst_env = emptyFamInstEnv
1187 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1188 compileCore simplify fn = do
1189 -- First, set the target to the desired filename
1190 target <- guessTarget fn Nothing
1193 -- Then find dependencies
1194 modGraph <- depanal [] True
1195 case find ((== fn) . msHsFilePath) modGraph of
1196 Just modSummary -> do
1197 -- Now we have the module name;
1198 -- parse, typecheck and desugar the module
1199 let mod = ms_mod_name modSummary
1200 mod_guts <- coreModule `fmap`
1201 (desugarModule =<< typecheckModule =<< parseModule mod)
1202 liftM gutsToCoreModule $
1205 -- If simplify is true: simplify (hscSimplify), then tidy
1207 hsc_env <- getSession
1208 simpl_guts <- ioMsg $ evalComp (hscSimplify mod_guts)
1210 compHscEnv = hsc_env,
1211 compModSummary = modSummary,
1212 compOldIface = Nothing})
1213 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1214 return $ Left tidy_guts
1216 return $ Right mod_guts
1218 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1219 module dependency graph"
1220 where -- two versions, based on whether we simplify (thus run tidyProgram,
1221 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1222 -- we just have a ModGuts.
1223 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1224 gutsToCoreModule (Left (cg, md)) = CoreModule {
1225 cm_module = cg_module cg, cm_types = md_types md,
1226 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1228 gutsToCoreModule (Right mg) = CoreModule {
1229 cm_module = mg_module mg, cm_types = mg_types mg,
1230 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1233 -- ---------------------------------------------------------------------------
1236 unload :: HscEnv -> [Linkable] -> IO ()
1237 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1238 = case ghcLink (hsc_dflags hsc_env) of
1240 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1242 LinkInMemory -> panic "unload: no interpreter"
1243 -- urgh. avoid warnings:
1244 hsc_env stable_linkables
1248 -- -----------------------------------------------------------------------------
1252 Stability tells us which modules definitely do not need to be recompiled.
1253 There are two main reasons for having stability:
1255 - avoid doing a complete upsweep of the module graph in GHCi when
1256 modules near the bottom of the tree have not changed.
1258 - to tell GHCi when it can load object code: we can only load object code
1259 for a module when we also load object code fo all of the imports of the
1260 module. So we need to know that we will definitely not be recompiling
1261 any of these modules, and we can use the object code.
1263 The stability check is as follows. Both stableObject and
1264 stableBCO are used during the upsweep phase later.
1267 stable m = stableObject m || stableBCO m
1270 all stableObject (imports m)
1271 && old linkable does not exist, or is == on-disk .o
1272 && date(on-disk .o) > date(.hs)
1275 all stable (imports m)
1276 && date(BCO) > date(.hs)
1279 These properties embody the following ideas:
1281 - if a module is stable, then:
1283 - if it has been compiled in a previous pass (present in HPT)
1284 then it does not need to be compiled or re-linked.
1286 - if it has not been compiled in a previous pass,
1287 then we only need to read its .hi file from disk and
1288 link it to produce a 'ModDetails'.
1290 - if a modules is not stable, we will definitely be at least
1291 re-linking, and possibly re-compiling it during the 'upsweep'.
1292 All non-stable modules can (and should) therefore be unlinked
1293 before the 'upsweep'.
1295 - Note that objects are only considered stable if they only depend
1296 on other objects. We can't link object code against byte code.
1300 :: HomePackageTable -- HPT from last compilation
1301 -> [SCC ModSummary] -- current module graph (cyclic)
1302 -> [ModuleName] -- all home modules
1303 -> ([ModuleName], -- stableObject
1304 [ModuleName]) -- stableBCO
1306 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1308 checkSCC (stable_obj, stable_bco) scc0
1309 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1310 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1311 | otherwise = (stable_obj, stable_bco)
1313 scc = flattenSCC scc0
1314 scc_mods = map ms_mod_name scc
1315 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1317 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1318 -- all imports outside the current SCC, but in the home pkg
1320 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1321 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1325 && all object_ok scc
1328 and (zipWith (||) stable_obj_imps stable_bco_imps)
1332 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1336 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1337 Just hmi | Just l <- hm_linkable hmi
1338 -> isObjectLinkable l && t == linkableTime l
1340 -- why '>=' rather than '>' above? If the filesystem stores
1341 -- times to the nearset second, we may occasionally find that
1342 -- the object & source have the same modification time,
1343 -- especially if the source was automatically generated
1344 -- and compiled. Using >= is slightly unsafe, but it matches
1345 -- make's behaviour.
1348 = case lookupUFM hpt (ms_mod_name ms) of
1349 Just hmi | Just l <- hm_linkable hmi ->
1350 not (isObjectLinkable l) &&
1351 linkableTime l >= ms_hs_date ms
1354 ms_allimps :: ModSummary -> [ModuleName]
1355 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1357 -- -----------------------------------------------------------------------------
1359 -- | Prune the HomePackageTable
1361 -- Before doing an upsweep, we can throw away:
1363 -- - For non-stable modules:
1364 -- - all ModDetails, all linked code
1365 -- - all unlinked code that is out of date with respect to
1368 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1369 -- space at the end of the upsweep, because the topmost ModDetails of the
1370 -- old HPT holds on to the entire type environment from the previous
1373 pruneHomePackageTable
1376 -> ([ModuleName],[ModuleName])
1379 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1382 | is_stable modl = hmi'
1383 | otherwise = hmi'{ hm_details = emptyModDetails }
1385 modl = moduleName (mi_module (hm_iface hmi))
1386 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1387 = hmi{ hm_linkable = Nothing }
1390 where ms = expectJust "prune" (lookupUFM ms_map modl)
1392 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1394 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1396 -- -----------------------------------------------------------------------------
1398 -- Return (names of) all those in modsDone who are part of a cycle
1399 -- as defined by theGraph.
1400 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1401 findPartiallyCompletedCycles modsDone theGraph
1405 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1406 chew ((CyclicSCC vs):rest)
1407 = let names_in_this_cycle = nub (map ms_mod vs)
1409 = nub ([done | done <- modsDone,
1410 done `elem` names_in_this_cycle])
1411 chewed_rest = chew rest
1413 if notNull mods_in_this_cycle
1414 && length mods_in_this_cycle < length names_in_this_cycle
1415 then mods_in_this_cycle ++ chewed_rest
1418 -- -----------------------------------------------------------------------------
1422 -- This is where we compile each module in the module graph, in a pass
1423 -- from the bottom to the top of the graph.
1425 -- There better had not be any cyclic groups here -- we check for them.
1429 ModuleCompiler -- ^ See argument to 'loadWithCompiler'.
1430 -> HscEnv -- ^ Includes initially-empty HPT
1431 -> HomePackageTable -- ^ HPT from last time round (pruned)
1432 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1433 -> IO () -- ^ How to clean up unwanted tmp files
1434 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1436 HscEnv, -- With an updated HPT
1437 [ModSummary]) -- Mods which succeeded
1439 upsweep mod_comp hsc_env old_hpt stable_mods cleanup sccs = do
1440 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1441 return (res, hsc_env, reverse done)
1444 upsweep' hsc_env _old_hpt done
1446 = return (Succeeded, hsc_env, done)
1448 upsweep' hsc_env _old_hpt done
1449 (CyclicSCC ms:_) _ _
1450 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1451 return (Failed, hsc_env, done)
1453 upsweep' hsc_env old_hpt done
1454 (AcyclicSCC mod:mods) mod_index nmods
1455 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1456 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1457 -- (moduleEnvElts (hsc_HPT hsc_env)))
1461 (upsweep_mod mod_comp hsc_env old_hpt stable_mods mod mod_index nmods)
1462 (liftIO cleanup) -- Remove unwanted tmp files between compilations
1465 Left (_ :: SomeException) -> return (Failed, hsc_env, done)
1466 Right mod_info -> do
1467 let this_mod = ms_mod_name mod
1469 -- Add new info to hsc_env
1470 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1471 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1473 -- Space-saving: delete the old HPT entry
1474 -- for mod BUT if mod is a hs-boot
1475 -- node, don't delete it. For the
1476 -- interface, the HPT entry is probaby for the
1477 -- main Haskell source file. Deleting it
1478 -- would force the real module to be recompiled
1480 old_hpt1 | isBootSummary mod = old_hpt
1481 | otherwise = delFromUFM old_hpt this_mod
1485 -- fixup our HomePackageTable after we've finished compiling
1486 -- a mutually-recursive loop. See reTypecheckLoop, below.
1487 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1489 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1491 -- | Same type as 'DriverPipeline.compile'. See its documentation for
1492 -- argument description.
1493 type ModuleCompiler = GhcMonad m =>
1502 -- | Compile a single module. Always produce a Linkable for it if
1503 -- successful. If no compilation happened, return the old Linkable.
1504 upsweep_mod :: GhcMonad m =>
1508 -> ([ModuleName],[ModuleName])
1510 -> Int -- index of module
1511 -> Int -- total number of modules
1514 upsweep_mod compile hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1516 this_mod_name = ms_mod_name summary
1517 this_mod = ms_mod summary
1518 mb_obj_date = ms_obj_date summary
1519 obj_fn = ml_obj_file (ms_location summary)
1520 hs_date = ms_hs_date summary
1522 is_stable_obj = this_mod_name `elem` stable_obj
1523 is_stable_bco = this_mod_name `elem` stable_bco
1525 old_hmi = lookupUFM old_hpt this_mod_name
1527 -- We're using the dflags for this module now, obtained by
1528 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1529 dflags = ms_hspp_opts summary
1530 prevailing_target = hscTarget (hsc_dflags hsc_env)
1531 local_target = hscTarget dflags
1533 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1534 -- we don't do anything dodgy: these should only work to change
1535 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1536 -- end up trying to link object code to byte code.
1537 target = if prevailing_target /= local_target
1538 && (not (isObjectTarget prevailing_target)
1539 || not (isObjectTarget local_target))
1540 then prevailing_target
1543 -- store the corrected hscTarget into the summary
1544 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1546 -- The old interface is ok if
1547 -- a) we're compiling a source file, and the old HPT
1548 -- entry is for a source file
1549 -- b) we're compiling a hs-boot file
1550 -- Case (b) allows an hs-boot file to get the interface of its
1551 -- real source file on the second iteration of the compilation
1552 -- manager, but that does no harm. Otherwise the hs-boot file
1553 -- will always be recompiled
1558 Just hm_info | isBootSummary summary -> Just iface
1559 | not (mi_boot iface) -> Just iface
1560 | otherwise -> Nothing
1562 iface = hm_iface hm_info
1564 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1565 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1567 compile_it_discard_iface :: GhcMonad m =>
1568 Maybe Linkable -> m HomeModInfo
1569 compile_it_discard_iface
1570 = compile hsc_env summary' mod_index nmods Nothing
1576 -- Regardless of whether we're generating object code or
1577 -- byte code, we can always use an existing object file
1578 -- if it is *stable* (see checkStability).
1579 | is_stable_obj, isJust old_hmi ->
1580 let Just hmi = old_hmi in
1582 -- object is stable, and we have an entry in the
1583 -- old HPT: nothing to do
1585 | is_stable_obj, isNothing old_hmi -> do
1586 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1587 (expectJust "upsweep1" mb_obj_date)
1588 compile_it (Just linkable)
1589 -- object is stable, but we need to load the interface
1590 -- off disk to make a HMI.
1594 ASSERT(isJust old_hmi) -- must be in the old_hpt
1595 let Just hmi = old_hmi in
1597 -- BCO is stable: nothing to do
1599 | Just hmi <- old_hmi,
1600 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1601 linkableTime l >= ms_hs_date summary ->
1603 -- we have an old BCO that is up to date with respect
1604 -- to the source: do a recompilation check as normal.
1608 -- no existing code at all: we must recompile.
1610 -- When generating object code, if there's an up-to-date
1611 -- object file on the disk, then we can use it.
1612 -- However, if the object file is new (compared to any
1613 -- linkable we had from a previous compilation), then we
1614 -- must discard any in-memory interface, because this
1615 -- means the user has compiled the source file
1616 -- separately and generated a new interface, that we must
1617 -- read from the disk.
1619 obj | isObjectTarget obj,
1620 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1623 | Just l <- hm_linkable hmi,
1624 isObjectLinkable l && linkableTime l == obj_date
1625 -> compile_it (Just l)
1627 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1628 compile_it_discard_iface (Just linkable)
1635 -- Filter modules in the HPT
1636 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1637 retainInTopLevelEnvs keep_these hpt
1638 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1640 , let mb_mod_info = lookupUFM hpt mod
1641 , isJust mb_mod_info ]
1643 -- ---------------------------------------------------------------------------
1644 -- Typecheck module loops
1647 See bug #930. This code fixes a long-standing bug in --make. The
1648 problem is that when compiling the modules *inside* a loop, a data
1649 type that is only defined at the top of the loop looks opaque; but
1650 after the loop is done, the structure of the data type becomes
1653 The difficulty is then that two different bits of code have
1654 different notions of what the data type looks like.
1656 The idea is that after we compile a module which also has an .hs-boot
1657 file, we re-generate the ModDetails for each of the modules that
1658 depends on the .hs-boot file, so that everyone points to the proper
1659 TyCons, Ids etc. defined by the real module, not the boot module.
1660 Fortunately re-generating a ModDetails from a ModIface is easy: the
1661 function TcIface.typecheckIface does exactly that.
1663 Picking the modules to re-typecheck is slightly tricky. Starting from
1664 the module graph consisting of the modules that have already been
1665 compiled, we reverse the edges (so they point from the imported module
1666 to the importing module), and depth-first-search from the .hs-boot
1667 node. This gives us all the modules that depend transitively on the
1668 .hs-boot module, and those are exactly the modules that we need to
1671 Following this fix, GHC can compile itself with --make -O2.
1674 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1675 reTypecheckLoop hsc_env ms graph
1676 | not (isBootSummary ms) &&
1677 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1679 let mss = reachableBackwards (ms_mod_name ms) graph
1680 non_boot = filter (not.isBootSummary) mss
1681 debugTraceMsg (hsc_dflags hsc_env) 2 $
1682 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1683 typecheckLoop hsc_env (map ms_mod_name non_boot)
1687 this_mod = ms_mod ms
1689 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1690 typecheckLoop hsc_env mods = do
1692 fixIO $ \new_hpt -> do
1693 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1694 mds <- initIfaceCheck new_hsc_env $
1695 mapM (typecheckIface . hm_iface) hmis
1696 let new_hpt = addListToUFM old_hpt
1697 (zip mods [ hmi{ hm_details = details }
1698 | (hmi,details) <- zip hmis mds ])
1700 return hsc_env{ hsc_HPT = new_hpt }
1702 old_hpt = hsc_HPT hsc_env
1703 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1705 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1706 reachableBackwards mod summaries
1707 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1708 where -- the rest just sets up the graph:
1709 (graph, lookup_node) = moduleGraphNodes False summaries
1710 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1712 -- ---------------------------------------------------------------------------
1713 -- Topological sort of the module graph
1715 type SummaryNode = (ModSummary, Int, [Int])
1718 :: Bool -- Drop hi-boot nodes? (see below)
1722 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1723 -- The resulting list of strongly-connected-components is in topologically
1724 -- sorted order, starting with the module(s) at the bottom of the
1725 -- dependency graph (ie compile them first) and ending with the ones at
1728 -- Drop hi-boot nodes (first boolean arg)?
1730 -- False: treat the hi-boot summaries as nodes of the graph,
1731 -- so the graph must be acyclic
1733 -- True: eliminate the hi-boot nodes, and instead pretend
1734 -- the a source-import of Foo is an import of Foo
1735 -- The resulting graph has no hi-boot nodes, but can by cyclic
1737 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1738 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1740 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1742 initial_graph = case mb_root_mod of
1745 -- restrict the graph to just those modules reachable from
1746 -- the specified module. We do this by building a graph with
1747 -- the full set of nodes, and determining the reachable set from
1748 -- the specified node.
1749 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1750 | otherwise = ghcError (ProgramError "module does not exist")
1751 in graphFromEdgedVertices (seq root (reachableG graph root))
1753 summaryNodeKey :: SummaryNode -> Int
1754 summaryNodeKey (_, k, _) = k
1756 summaryNodeSummary :: SummaryNode -> ModSummary
1757 summaryNodeSummary (s, _, _) = s
1759 moduleGraphNodes :: Bool -> [ModSummary]
1760 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1761 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1763 numbered_summaries = zip summaries [1..]
1765 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1766 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1768 lookup_key :: HscSource -> ModuleName -> Maybe Int
1769 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1771 node_map :: NodeMap SummaryNode
1772 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1773 | node@(s, _, _) <- nodes ]
1775 -- We use integers as the keys for the SCC algorithm
1776 nodes :: [SummaryNode]
1777 nodes = [ (s, key, out_keys)
1778 | (s, key) <- numbered_summaries
1779 -- Drop the hi-boot ones if told to do so
1780 , not (isBootSummary s && drop_hs_boot_nodes)
1781 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1782 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1783 (-- see [boot-edges] below
1784 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1786 else case lookup_key HsBootFile (ms_mod_name s) of
1790 -- [boot-edges] if this is a .hs and there is an equivalent
1791 -- .hs-boot, add a link from the former to the latter. This
1792 -- has the effect of detecting bogus cases where the .hs-boot
1793 -- depends on the .hs, by introducing a cycle. Additionally,
1794 -- it ensures that we will always process the .hs-boot before
1795 -- the .hs, and so the HomePackageTable will always have the
1796 -- most up to date information.
1798 -- Drop hs-boot nodes by using HsSrcFile as the key
1799 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1800 | otherwise = HsBootFile
1802 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1803 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1804 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1805 -- the IsBootInterface parameter True; else False
1808 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1809 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1811 msKey :: ModSummary -> NodeKey
1812 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1814 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1815 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1817 nodeMapElts :: NodeMap a -> [a]
1818 nodeMapElts = eltsFM
1820 -- | If there are {-# SOURCE #-} imports between strongly connected
1821 -- components in the topological sort, then those imports can
1822 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1823 -- were necessary, then the edge would be part of a cycle.
1824 warnUnnecessarySourceImports :: GhcMonad m => DynFlags -> [SCC ModSummary] -> m ()
1825 warnUnnecessarySourceImports dflags sccs =
1826 liftIO $ printBagOfWarnings dflags (listToBag (concatMap (check.flattenSCC) sccs))
1828 let mods_in_this_cycle = map ms_mod_name ms in
1829 [ warn i | m <- ms, i <- ms_srcimps m,
1830 unLoc i `notElem` mods_in_this_cycle ]
1832 warn :: Located ModuleName -> WarnMsg
1835 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1836 <+> quotes (ppr mod))
1838 -----------------------------------------------------------------------------
1839 -- Downsweep (dependency analysis)
1841 -- Chase downwards from the specified root set, returning summaries
1842 -- for all home modules encountered. Only follow source-import
1845 -- We pass in the previous collection of summaries, which is used as a
1846 -- cache to avoid recalculating a module summary if the source is
1849 -- The returned list of [ModSummary] nodes has one node for each home-package
1850 -- module, plus one for any hs-boot files. The imports of these nodes
1851 -- are all there, including the imports of non-home-package modules.
1853 downsweep :: GhcMonad m =>
1855 -> [ModSummary] -- Old summaries
1856 -> [ModuleName] -- Ignore dependencies on these; treat
1857 -- them as if they were package modules
1858 -> Bool -- True <=> allow multiple targets to have
1859 -- the same module name; this is
1860 -- very useful for ghc -M
1862 -- The elts of [ModSummary] all have distinct
1863 -- (Modules, IsBoot) identifiers, unless the Bool is true
1864 -- in which case there can be repeats
1865 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1866 = do -- catch error messages and return them
1867 --handleErrMsg -- should be covered by GhcMonad now
1868 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1869 rootSummaries <- mapM getRootSummary roots
1870 let root_map = mkRootMap rootSummaries
1871 checkDuplicates root_map
1872 summs <- loop (concatMap msDeps rootSummaries) root_map
1875 roots = hsc_targets hsc_env
1877 old_summary_map :: NodeMap ModSummary
1878 old_summary_map = mkNodeMap old_summaries
1880 getRootSummary :: GhcMonad m => Target -> m ModSummary
1881 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1882 = do exists <- liftIO $ doesFileExist file
1884 then summariseFile hsc_env old_summaries file mb_phase
1885 obj_allowed maybe_buf
1886 else throwErrMsg $ mkPlainErrMsg noSrcSpan $
1887 text "can't find file:" <+> text file
1888 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1889 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1890 (L rootLoc modl) obj_allowed
1892 case maybe_summary of
1893 Nothing -> packageModErr modl
1896 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1898 -- In a root module, the filename is allowed to diverge from the module
1899 -- name, so we have to check that there aren't multiple root files
1900 -- defining the same module (otherwise the duplicates will be silently
1901 -- ignored, leading to confusing behaviour).
1902 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1903 checkDuplicates root_map
1904 | allow_dup_roots = return ()
1905 | null dup_roots = return ()
1906 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1908 dup_roots :: [[ModSummary]] -- Each at least of length 2
1909 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1911 loop :: GhcMonad m =>
1912 [(Located ModuleName,IsBootInterface)]
1913 -- Work list: process these modules
1914 -> NodeMap [ModSummary]
1915 -- Visited set; the range is a list because
1916 -- the roots can have the same module names
1917 -- if allow_dup_roots is True
1919 -- The result includes the worklist, except
1920 -- for those mentioned in the visited set
1921 loop [] done = return (concat (nodeMapElts done))
1922 loop ((wanted_mod, is_boot) : ss) done
1923 | Just summs <- lookupFM done key
1924 = if isSingleton summs then
1927 do { liftIO $ multiRootsErr summs; return [] }
1929 = do mb_s <- summariseModule hsc_env old_summary_map
1930 is_boot wanted_mod True
1933 Nothing -> loop ss done
1934 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1936 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1938 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1939 mkRootMap summaries = addListToFM_C (++) emptyFM
1940 [ (msKey s, [s]) | s <- summaries ]
1942 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1943 -- (msDeps s) returns the dependencies of the ModSummary s.
1944 -- A wrinkle is that for a {-# SOURCE #-} import we return
1945 -- *both* the hs-boot file
1946 -- *and* the source file
1947 -- as "dependencies". That ensures that the list of all relevant
1948 -- modules always contains B.hs if it contains B.hs-boot.
1949 -- Remember, this pass isn't doing the topological sort. It's
1950 -- just gathering the list of all relevant ModSummaries
1952 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1953 ++ [ (m,False) | m <- ms_imps s ]
1955 -----------------------------------------------------------------------------
1956 -- Summarising modules
1958 -- We have two types of summarisation:
1960 -- * Summarise a file. This is used for the root module(s) passed to
1961 -- cmLoadModules. The file is read, and used to determine the root
1962 -- module name. The module name may differ from the filename.
1964 -- * Summarise a module. We are given a module name, and must provide
1965 -- a summary. The finder is used to locate the file in which the module
1971 -> [ModSummary] -- old summaries
1972 -> FilePath -- source file name
1973 -> Maybe Phase -- start phase
1974 -> Bool -- object code allowed?
1975 -> Maybe (StringBuffer,ClockTime)
1978 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1979 -- we can use a cached summary if one is available and the
1980 -- source file hasn't changed, But we have to look up the summary
1981 -- by source file, rather than module name as we do in summarise.
1982 | Just old_summary <- findSummaryBySourceFile old_summaries file
1984 let location = ms_location old_summary
1986 -- return the cached summary if the source didn't change
1987 src_timestamp <- case maybe_buf of
1988 Just (_,t) -> return t
1989 Nothing -> liftIO $ getModificationTime file
1990 -- The file exists; we checked in getRootSummary above.
1991 -- If it gets removed subsequently, then this
1992 -- getModificationTime may fail, but that's the right
1995 if ms_hs_date old_summary == src_timestamp
1996 then do -- update the object-file timestamp
1998 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1999 || obj_allowed -- bug #1205
2000 then liftIO $ getObjTimestamp location False
2002 return old_summary{ ms_obj_date = obj_timestamp }
2010 let dflags = hsc_dflags hsc_env
2012 (dflags', hspp_fn, buf)
2013 <- preprocessFile hsc_env file mb_phase maybe_buf
2015 (srcimps,the_imps, L _ mod_name) <- liftIO $ getImports dflags' buf hspp_fn file
2017 -- Make a ModLocation for this file
2018 location <- liftIO $ mkHomeModLocation dflags mod_name file
2020 -- Tell the Finder cache where it is, so that subsequent calls
2021 -- to findModule will find it, even if it's not on any search path
2022 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2024 src_timestamp <- case maybe_buf of
2025 Just (_,t) -> return t
2026 Nothing -> liftIO $ getModificationTime file
2027 -- getMofificationTime may fail
2029 -- when the user asks to load a source file by name, we only
2030 -- use an object file if -fobject-code is on. See #1205.
2032 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2033 || obj_allowed -- bug #1205
2034 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2037 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2038 ms_location = location,
2039 ms_hspp_file = hspp_fn,
2040 ms_hspp_opts = dflags',
2041 ms_hspp_buf = Just buf,
2042 ms_srcimps = srcimps, ms_imps = the_imps,
2043 ms_hs_date = src_timestamp,
2044 ms_obj_date = obj_timestamp })
2046 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2047 findSummaryBySourceFile summaries file
2048 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2049 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2053 -- Summarise a module, and pick up source and timestamp.
2057 -> NodeMap ModSummary -- Map of old summaries
2058 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2059 -> Located ModuleName -- Imported module to be summarised
2060 -> Bool -- object code allowed?
2061 -> Maybe (StringBuffer, ClockTime)
2062 -> [ModuleName] -- Modules to exclude
2063 -> m (Maybe ModSummary) -- Its new summary
2065 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2066 obj_allowed maybe_buf excl_mods
2067 | wanted_mod `elem` excl_mods
2070 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2071 = do -- Find its new timestamp; all the
2072 -- ModSummaries in the old map have valid ml_hs_files
2073 let location = ms_location old_summary
2074 src_fn = expectJust "summariseModule" (ml_hs_file location)
2076 -- check the modification time on the source file, and
2077 -- return the cached summary if it hasn't changed. If the
2078 -- file has disappeared, we need to call the Finder again.
2080 Just (_,t) -> check_timestamp old_summary location src_fn t
2082 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2084 Right t -> check_timestamp old_summary location src_fn t
2085 Left e | isDoesNotExistError e -> find_it
2086 | otherwise -> liftIO $ ioError e
2088 | otherwise = find_it
2090 dflags = hsc_dflags hsc_env
2092 hsc_src = if is_boot then HsBootFile else HsSrcFile
2094 check_timestamp old_summary location src_fn src_timestamp
2095 | ms_hs_date old_summary == src_timestamp = do
2096 -- update the object-file timestamp
2097 obj_timestamp <- liftIO $
2098 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2099 || obj_allowed -- bug #1205
2100 then getObjTimestamp location is_boot
2102 return (Just old_summary{ ms_obj_date = obj_timestamp })
2104 -- source changed: re-summarise.
2105 new_summary location (ms_mod old_summary) src_fn src_timestamp
2108 -- Don't use the Finder's cache this time. If the module was
2109 -- previously a package module, it may have now appeared on the
2110 -- search path, so we want to consider it to be a home module. If
2111 -- the module was previously a home module, it may have moved.
2112 liftIO $ uncacheModule hsc_env wanted_mod
2113 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2116 | isJust (ml_hs_file location) ->
2118 just_found location mod
2120 -- Drop external-pkg
2121 ASSERT(modulePackageId mod /= thisPackage dflags)
2124 err -> liftIO $ noModError dflags loc wanted_mod err
2127 just_found location mod = do
2128 -- Adjust location to point to the hs-boot source file,
2129 -- hi file, object file, when is_boot says so
2130 let location' | is_boot = addBootSuffixLocn location
2131 | otherwise = location
2132 src_fn = expectJust "summarise2" (ml_hs_file location')
2134 -- Check that it exists
2135 -- It might have been deleted since the Finder last found it
2136 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2138 Nothing -> noHsFileErr loc src_fn
2139 Just t -> new_summary location' mod src_fn t
2142 new_summary location mod src_fn src_timestamp
2144 -- Preprocess the source file and get its imports
2145 -- The dflags' contains the OPTIONS pragmas
2146 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2147 (srcimps, the_imps, L mod_loc mod_name) <- liftIO $ getImports dflags' buf hspp_fn src_fn
2149 when (mod_name /= wanted_mod) $
2150 throwErrMsg $ mkPlainErrMsg mod_loc $
2151 text "File name does not match module name:"
2152 $$ text "Saw:" <+> quotes (ppr mod_name)
2153 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2155 -- Find the object timestamp, and return the summary
2156 obj_timestamp <- liftIO $
2157 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2158 || obj_allowed -- bug #1205
2159 then getObjTimestamp location is_boot
2162 return (Just (ModSummary { ms_mod = mod,
2163 ms_hsc_src = hsc_src,
2164 ms_location = location,
2165 ms_hspp_file = hspp_fn,
2166 ms_hspp_opts = dflags',
2167 ms_hspp_buf = Just buf,
2168 ms_srcimps = srcimps,
2170 ms_hs_date = src_timestamp,
2171 ms_obj_date = obj_timestamp }))
2174 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2175 getObjTimestamp location is_boot
2176 = if is_boot then return Nothing
2177 else modificationTimeIfExists (ml_obj_file location)
2180 preprocessFile :: GhcMonad m =>
2183 -> Maybe Phase -- ^ Starting phase
2184 -> Maybe (StringBuffer,ClockTime)
2185 -> m (DynFlags, FilePath, StringBuffer)
2186 preprocessFile hsc_env src_fn mb_phase Nothing
2188 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2189 buf <- liftIO $ hGetStringBuffer hspp_fn
2190 return (dflags', hspp_fn, buf)
2192 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2194 let dflags = hsc_dflags hsc_env
2195 -- case we bypass the preprocessing stage?
2197 local_opts = getOptions dflags buf src_fn
2199 (dflags', leftovers, warns)
2200 <- parseDynamicFlags dflags local_opts
2201 liftIO $ checkProcessArgsResult leftovers -- XXX: throws exceptions
2202 liftIO $ handleFlagWarnings dflags' warns -- XXX: throws exceptions
2206 | Just (Unlit _) <- mb_phase = True
2207 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2208 -- note: local_opts is only required if there's no Unlit phase
2209 | dopt Opt_Cpp dflags' = True
2210 | dopt Opt_Pp dflags' = True
2213 when needs_preprocessing $
2214 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2216 return (dflags', src_fn, buf)
2219 -----------------------------------------------------------------------------
2221 -----------------------------------------------------------------------------
2223 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2224 -- ToDo: we don't have a proper line number for this error
2225 noModError dflags loc wanted_mod err
2226 = throwErrMsg $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2228 noHsFileErr :: SrcSpan -> String -> a
2229 noHsFileErr loc path
2230 = throwErrMsg $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2232 packageModErr :: ModuleName -> a
2234 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2235 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2237 multiRootsErr :: [ModSummary] -> IO ()
2238 multiRootsErr [] = panic "multiRootsErr"
2239 multiRootsErr summs@(summ1:_)
2240 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2241 text "module" <+> quotes (ppr mod) <+>
2242 text "is defined in multiple files:" <+>
2243 sep (map text files)
2246 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2248 cyclicModuleErr :: [ModSummary] -> SDoc
2250 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2251 2 (vcat (map show_one ms))
2253 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2254 nest 2 $ ptext (sLit "imports:") <+>
2255 (pp_imps HsBootFile (ms_srcimps ms)
2256 $$ pp_imps HsSrcFile (ms_imps ms))]
2257 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2258 pp_imps src mods = fsep (map (show_mod src) mods)
2261 -- | Inform GHC that the working directory has changed. GHC will flush
2262 -- its cache of module locations, since it may no longer be valid.
2263 -- Note: if you change the working directory, you should also unload
2264 -- the current program (set targets to empty, followed by load).
2265 workingDirectoryChanged :: GhcMonad m => m ()
2266 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2268 -- -----------------------------------------------------------------------------
2269 -- inspecting the session
2271 -- | Get the module dependency graph.
2272 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2273 getModuleGraph = liftM hsc_mod_graph getSession
2275 -- | Return @True@ <==> module is loaded.
2276 isLoaded :: GhcMonad m => ModuleName -> m Bool
2277 isLoaded m = withSession $ \hsc_env ->
2278 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2280 -- | Return the bindings for the current interactive session.
2281 getBindings :: GhcMonad m => m [TyThing]
2282 getBindings = withSession $ \hsc_env ->
2283 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2284 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2286 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2287 filtered = foldr f (const []) tmp_ids emptyUniqSet
2289 | uniq `elementOfUniqSet` set = rest set
2290 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2291 where uniq = getUnique (nameOccName (idName id))
2295 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2296 getPrintUnqual = withSession $ \hsc_env ->
2297 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2299 -- | Container for information about a 'Module'.
2300 data ModuleInfo = ModuleInfo {
2301 minf_type_env :: TypeEnv,
2302 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2303 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2304 minf_instances :: [Instance]
2306 ,minf_modBreaks :: ModBreaks
2308 -- ToDo: this should really contain the ModIface too
2310 -- We don't want HomeModInfo here, because a ModuleInfo applies
2311 -- to package modules too.
2313 -- | Request information about a loaded 'Module'
2314 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2315 getModuleInfo mdl = withSession $ \hsc_env -> do
2316 let mg = hsc_mod_graph hsc_env
2317 if mdl `elem` map ms_mod mg
2318 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2320 {- if isHomeModule (hsc_dflags hsc_env) mdl
2322 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2323 -- getPackageModuleInfo will attempt to find the interface, so
2324 -- we don't want to call it for a home module, just in case there
2325 -- was a problem loading the module and the interface doesn't
2326 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2328 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2330 getPackageModuleInfo hsc_env mdl = do
2331 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2333 Nothing -> return Nothing
2335 eps <- readIORef (hsc_EPS hsc_env)
2337 names = availsToNameSet avails
2339 tys = [ ty | name <- concatMap availNames avails,
2340 Just ty <- [lookupTypeEnv pte name] ]
2342 return (Just (ModuleInfo {
2343 minf_type_env = mkTypeEnv tys,
2344 minf_exports = names,
2345 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2346 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2347 minf_modBreaks = emptyModBreaks
2350 getPackageModuleInfo _hsc_env _mdl = do
2351 -- bogusly different for non-GHCI (ToDo)
2355 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2356 getHomeModuleInfo hsc_env mdl =
2357 case lookupUFM (hsc_HPT hsc_env) mdl of
2358 Nothing -> return Nothing
2360 let details = hm_details hmi
2361 return (Just (ModuleInfo {
2362 minf_type_env = md_types details,
2363 minf_exports = availsToNameSet (md_exports details),
2364 minf_rdr_env = mi_globals $! hm_iface hmi,
2365 minf_instances = md_insts details
2367 ,minf_modBreaks = getModBreaks hmi
2371 -- | The list of top-level entities defined in a module
2372 modInfoTyThings :: ModuleInfo -> [TyThing]
2373 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2375 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2376 modInfoTopLevelScope minf
2377 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2379 modInfoExports :: ModuleInfo -> [Name]
2380 modInfoExports minf = nameSetToList $! minf_exports minf
2382 -- | Returns the instances defined by the specified module.
2383 -- Warning: currently unimplemented for package modules.
2384 modInfoInstances :: ModuleInfo -> [Instance]
2385 modInfoInstances = minf_instances
2387 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2388 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2390 mkPrintUnqualifiedForModule :: GhcMonad m =>
2392 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2393 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2394 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2396 modInfoLookupName :: GhcMonad m =>
2398 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2399 modInfoLookupName minf name = withSession $ \hsc_env -> do
2400 case lookupTypeEnv (minf_type_env minf) name of
2401 Just tyThing -> return (Just tyThing)
2403 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2404 return $! lookupType (hsc_dflags hsc_env)
2405 (hsc_HPT hsc_env) (eps_PTE eps) name
2408 modInfoModBreaks :: ModuleInfo -> ModBreaks
2409 modInfoModBreaks = minf_modBreaks
2412 isDictonaryId :: Id -> Bool
2414 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2416 -- | Looks up a global name: that is, any top-level name in any
2417 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2418 -- the interactive context, and therefore does not require a preceding
2420 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2421 lookupGlobalName name = withSession $ \hsc_env -> do
2422 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2423 return $! lookupType (hsc_dflags hsc_env)
2424 (hsc_HPT hsc_env) (eps_PTE eps) name
2427 -- | get the GlobalRdrEnv for a session
2428 getGRE :: GhcMonad m => m GlobalRdrEnv
2429 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2432 -- -----------------------------------------------------------------------------
2433 -- Misc exported utils
2435 dataConType :: DataCon -> Type
2436 dataConType dc = idType (dataConWrapId dc)
2438 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2439 pprParenSymName :: NamedThing a => a -> SDoc
2440 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2442 -- ----------------------------------------------------------------------------
2447 -- - Data and Typeable instances for HsSyn.
2449 -- ToDo: check for small transformations that happen to the syntax in
2450 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2452 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2453 -- to get from TyCons, Ids etc. to TH syntax (reify).
2455 -- :browse will use either lm_toplev or inspect lm_interface, depending
2456 -- on whether the module is interpreted or not.
2458 -- This is for reconstructing refactored source code
2459 -- Calls the lexer repeatedly.
2460 -- ToDo: add comment tokens to token stream
2461 getTokenStream :: Session -> Module -> IO [Located Token]
2464 -- -----------------------------------------------------------------------------
2465 -- Interactive evaluation
2467 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2468 -- filesystem and package database to find the corresponding 'Module',
2469 -- using the algorithm that is used for an @import@ declaration.
2470 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2471 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2473 dflags = hsc_dflags hsc_env
2474 hpt = hsc_HPT hsc_env
2475 this_pkg = thisPackage dflags
2477 case lookupUFM hpt mod_name of
2478 Just mod_info -> return (mi_module (hm_iface mod_info))
2479 _not_a_home_module -> do
2480 res <- findImportedModule hsc_env mod_name maybe_pkg
2482 Found _ m | modulePackageId m /= this_pkg -> return m
2483 | otherwise -> ghcError (CmdLineError (showSDoc $
2484 text "module" <+> quotes (ppr (moduleName m)) <+>
2485 text "is not loaded"))
2486 err -> let msg = cannotFindModule dflags mod_name err in
2487 ghcError (CmdLineError (showSDoc msg))
2490 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2491 getHistorySpan h = withSession $ \hsc_env ->
2492 return$ InteractiveEval.getHistorySpan hsc_env h
2494 obtainTerm :: GhcMonad m => Bool -> Id -> m Term
2495 obtainTerm force id = withSession $ \hsc_env ->
2496 liftIO $ InteractiveEval.obtainTerm hsc_env force id
2498 obtainTerm1 :: GhcMonad m => Bool -> Maybe Type -> a -> m Term
2499 obtainTerm1 force mb_ty a =
2500 withSession $ \hsc_env ->
2501 liftIO $ InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2503 obtainTermB :: GhcMonad m => Int -> Bool -> Id -> m Term
2504 obtainTermB bound force id =
2505 withSession $ \hsc_env ->
2506 liftIO $ InteractiveEval.obtainTermB hsc_env bound force id