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, loadWithLogger, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
47 defaultWarnErrLogger, WarnErrLogger,
48 workingDirectoryChanged,
49 parseModule, typecheckModule, desugarModule, loadModule,
50 ParsedModule, TypecheckedModule, DesugaredModule, -- all abstract
51 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
52 moduleInfo, renamedSource, typecheckedSource,
53 parsedSource, coreModule,
54 compileToCoreModule, compileToCoreSimplified,
57 -- * Parsing Haddock comments
60 -- * Inspecting the module structure of the program
61 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
66 -- * Inspecting modules
73 modInfoIsExportedName,
76 mkPrintUnqualifiedForModule,
79 PrintUnqualified, alwaysQualify,
81 -- * Interactive evaluation
82 getBindings, getPrintUnqual,
85 setContext, getContext,
95 runStmt, SingleStep(..),
97 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
98 resumeHistory, resumeHistoryIx),
99 History(historyBreakInfo, historyEnclosingDecl),
100 GHC.getHistorySpan, getHistoryModule,
103 InteractiveEval.back,
104 InteractiveEval.forward,
107 InteractiveEval.compileExpr, HValue, dynCompileExpr,
109 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
111 ModBreaks(..), BreakIndex,
112 BreakInfo(breakInfo_number, breakInfo_module),
113 BreakArray, setBreakOn, setBreakOff, getBreak,
116 -- * Abstract syntax elements
122 Module, mkModule, pprModule, moduleName, modulePackageId,
123 ModuleName, mkModuleName, moduleNameString,
127 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
129 RdrName(Qual,Unqual),
133 isImplicitId, isDeadBinder,
134 isExportedId, isLocalId, isGlobalId,
136 isPrimOpId, isFCallId, isClassOpId_maybe,
137 isDataConWorkId, idDataCon,
138 isBottomingId, isDictonaryId,
139 recordSelectorFieldLabel,
141 -- ** Type constructors
143 tyConTyVars, tyConDataCons, tyConArity,
144 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
146 synTyConDefn, synTyConType, synTyConResKind,
152 -- ** Data constructors
154 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
155 dataConIsInfix, isVanillaDataCon,
157 StrictnessMark(..), isMarkedStrict,
161 classMethods, classSCTheta, classTvsFds,
166 instanceDFunId, pprInstance, pprInstanceHdr,
168 -- ** Types and Kinds
169 Type, splitForAllTys, funResultTy,
170 pprParendType, pprTypeApp,
173 ThetaType, pprThetaArrow,
179 module HsSyn, -- ToDo: remove extraneous bits
183 defaultFixity, maxPrecedence,
187 -- ** Source locations
189 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
190 srcLocFile, srcLocLine, srcLocCol,
192 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
193 srcSpanStart, srcSpanEnd,
195 srcSpanStartLine, srcSpanEndLine,
196 srcSpanStartCol, srcSpanEndCol,
199 GhcException(..), showGhcException,
209 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
210 * what StaticFlags should we expose, if any?
213 #include "HsVersions.h"
216 import qualified Linker
217 import Linker ( HValue )
221 import InteractiveEval
226 import TcRnTypes hiding (LIE)
227 import TcRnMonad ( initIfaceCheck )
231 import qualified HsSyn -- hack as we want to reexport the whole module
232 import HsSyn hiding ((<.>))
233 import Type hiding (typeKind)
234 import TcType hiding (typeKind)
237 import TysPrim ( alphaTyVars )
242 import Name hiding ( varName )
243 import OccName ( parenSymOcc )
244 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
246 import FamInstEnv ( emptyFamInstEnv )
250 import DriverPipeline
251 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
257 import StaticFlagParser
258 import qualified StaticFlags
259 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
268 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
272 import StringBuffer ( StringBuffer, hGetStringBuffer )
275 import Maybes ( expectJust, mapCatMaybes )
277 import HaddockLex ( tokenise )
280 import Control.Concurrent
281 import System.Directory ( getModificationTime, doesFileExist,
282 getCurrentDirectory )
285 import qualified Data.List as List
287 import System.Exit ( exitWith, ExitCode(..) )
288 import System.Time ( ClockTime, getClockTime )
291 import System.FilePath
293 import System.IO.Error ( try, isDoesNotExistError )
294 #if __GLASGOW_HASKELL__ >= 609
295 import Data.Typeable (cast)
297 import Prelude hiding (init)
300 -- -----------------------------------------------------------------------------
301 -- Exception handlers
303 -- | Install some default exception handlers and run the inner computation.
304 -- Unless you want to handle exceptions yourself, you should wrap this around
305 -- the top level of your program. The default handlers output the error
306 -- message(s) to stderr and exit cleanly.
307 defaultErrorHandler :: DynFlags -> IO a -> IO a
308 defaultErrorHandler dflags inner =
309 -- top-level exception handler: any unrecognised exception is a compiler bug.
310 #if __GLASGOW_HASKELL__ < 609
311 handle (\exception -> do
314 -- an IO exception probably isn't our fault, so don't panic
316 fatalErrorMsg dflags (text (show exception))
317 AsyncException StackOverflow ->
318 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
319 ExitException _ -> throw exception
321 fatalErrorMsg dflags (text (show (Panic (show exception))))
322 exitWith (ExitFailure 1)
325 handle (\(SomeException exception) -> do
327 case cast exception of
328 -- an IO exception probably isn't our fault, so don't panic
329 Just (ioe :: IOException) ->
330 fatalErrorMsg dflags (text (show ioe))
331 _ -> case cast exception of
332 Just StackOverflow ->
333 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
334 _ -> case cast exception of
335 Just (ex :: ExitCode) -> throw ex
338 (text (show (Panic (show exception))))
339 exitWith (ExitFailure 1)
343 -- program errors: messages with locations attached. Sometimes it is
344 -- convenient to just throw these as exceptions.
346 (\em -> do printBagOfErrors dflags (unitBag em)
347 exitWith (ExitFailure 1)) $
349 -- error messages propagated as exceptions
354 PhaseFailed _ code -> exitWith code
355 Interrupted -> exitWith (ExitFailure 1)
356 _ -> do fatalErrorMsg dflags (text (show ge))
357 exitWith (ExitFailure 1)
361 -- | Install a default cleanup handler to remove temporary files deposited by
362 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
363 -- want to override the error handling, but still get the ordinary cleanup
365 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
366 DynFlags -> m a -> m a
367 defaultCleanupHandler dflags inner =
368 -- make sure we clean up after ourselves
371 cleanTempFiles dflags
374 -- exceptions will be blocked while we clean the temporary files,
375 -- so there shouldn't be any difficulty if we receive further
378 -- | Print the error message and all warnings. Useful inside exception
379 -- handlers. Clears warnings after printing.
380 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
381 printExceptionAndWarnings err = do
382 let errs = srcErrorMessages err
384 dflags <- getSessionDynFlags
386 -- Empty errors means we failed due to -Werror. (Since this function
387 -- takes a source error as argument, we know for sure _some_ error
388 -- did indeed happen.)
390 printBagOfWarnings dflags warns
391 printBagOfErrors dflags (unitBag warnIsErrorMsg)
392 else liftIO $ printBagOfErrors dflags errs
395 -- | Print all accumulated warnings using 'log_action'.
396 printWarnings :: GhcMonad m => m ()
398 dflags <- getSessionDynFlags
400 liftIO $ printBagOfWarnings dflags warns
403 -- | Run function for the 'Ghc' monad.
405 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
406 -- to this function will create a new session which should not be shared among
409 -- Any errors not handled inside the 'Ghc' action are propagated as IO
412 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
413 -> Ghc a -- ^ The action to perform.
415 runGhc mb_top_dir ghc = do
416 wref <- newIORef emptyBag
417 ref <- newIORef undefined
418 let session = Session ref wref
419 flip unGhc session $ do
420 initGhcMonad mb_top_dir
422 -- XXX: unregister interrupt handlers here?
424 -- | Run function for 'GhcT' monad transformer.
426 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
427 -- to this function will create a new session which should not be shared among
430 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
431 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
432 -> GhcT m a -- ^ The action to perform.
434 runGhcT mb_top_dir ghct = do
435 wref <- liftIO $ newIORef emptyBag
436 ref <- liftIO $ newIORef undefined
437 let session = Session ref wref
438 flip unGhcT session $ do
439 initGhcMonad mb_top_dir
442 -- | Initialise a GHC session.
444 -- If you implement a custom 'GhcMonad' you must call this function in the
445 -- monad run function. It will initialise the session variable and clear all
448 -- The first argument should point to the directory where GHC's library files
449 -- reside. More precisely, this should be the output of @ghc --print-libdir@
450 -- of the version of GHC the module using this API is compiled with. For
451 -- portability, you should use the @ghc-paths@ package, available at
452 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
454 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
455 initGhcMonad mb_top_dir = do
457 main_thread <- liftIO $ myThreadId
458 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
459 liftIO $ installSignalHandlers
461 liftIO $ StaticFlags.initStaticOpts
463 dflags0 <- liftIO $ initDynFlags defaultDynFlags
464 dflags <- liftIO $ initSysTools mb_top_dir dflags0
465 env <- liftIO $ newHscEnv dflags
469 -- -----------------------------------------------------------------------------
472 -- | Grabs the DynFlags from the Session
473 getSessionDynFlags :: GhcMonad m => m DynFlags
474 getSessionDynFlags = withSession (return . hsc_dflags)
476 -- | Updates the DynFlags in a Session. This also reads
477 -- the package database (unless it has already been read),
478 -- and prepares the compilers knowledge about packages. It
479 -- can be called again to load new packages: just add new
480 -- package flags to (packageFlags dflags).
482 -- Returns a list of new packages that may need to be linked in using
483 -- the dynamic linker (see 'linkPackages') as a result of new package
484 -- flags. If you are not doing linking or doing static linking, you
485 -- can ignore the list of packages returned.
487 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
488 setSessionDynFlags dflags = do
489 (dflags', preload) <- liftIO $ initPackages dflags
490 modifySession (\h -> h{ hsc_dflags = dflags' })
493 -- | If there is no -o option, guess the name of target executable
494 -- by using top-level source file name as a base.
495 guessOutputFile :: GhcMonad m => m ()
496 guessOutputFile = modifySession $ \env ->
497 let dflags = hsc_dflags env
498 mod_graph = hsc_mod_graph env
499 mainModuleSrcPath :: Maybe String
500 mainModuleSrcPath = do
501 let isMain = (== mainModIs dflags) . ms_mod
502 [ms] <- return (filter isMain mod_graph)
503 ml_hs_file (ms_location ms)
504 name = fmap dropExtension mainModuleSrcPath
506 #if defined(mingw32_HOST_OS)
507 -- we must add the .exe extention unconditionally here, otherwise
508 -- when name has an extension of its own, the .exe extension will
509 -- not be added by DriverPipeline.exeFileName. See #2248
510 name_exe = fmap (<.> "exe") name
515 case outputFile dflags of
517 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
519 -- -----------------------------------------------------------------------------
522 -- ToDo: think about relative vs. absolute file paths. And what
523 -- happens when the current directory changes.
525 -- | Sets the targets for this session. Each target may be a module name
526 -- or a filename. The targets correspond to the set of root modules for
527 -- the program\/library. Unloading the current program is achieved by
528 -- setting the current set of targets to be empty, followed by 'load'.
529 setTargets :: GhcMonad m => [Target] -> m ()
530 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
532 -- | Returns the current set of targets
533 getTargets :: GhcMonad m => m [Target]
534 getTargets = withSession (return . hsc_targets)
536 -- | Add another target.
537 addTarget :: GhcMonad m => Target -> m ()
539 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
542 removeTarget :: GhcMonad m => TargetId -> m ()
543 removeTarget target_id
544 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
546 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
548 -- | Attempts to guess what Target a string refers to. This function
549 -- implements the @--make@/GHCi command-line syntax for filenames:
551 -- - if the string looks like a Haskell source filename, then interpret it
554 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
557 -- - otherwise interpret the string as a module name
559 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
560 guessTarget str (Just phase)
561 = return (Target (TargetFile str (Just phase)) True Nothing)
562 guessTarget str Nothing
563 | isHaskellSrcFilename file
564 = return (target (TargetFile file Nothing))
566 = do exists <- liftIO $ doesFileExist hs_file
568 then return (target (TargetFile hs_file Nothing))
570 exists <- liftIO $ doesFileExist lhs_file
572 then return (target (TargetFile lhs_file Nothing))
574 if looksLikeModuleName file
575 then return (target (TargetModule (mkModuleName file)))
578 (ProgramError (showSDoc $
579 text "target" <+> quotes (text file) <+>
580 text "is not a module name or a source file"))
583 | '*':rest <- str = (rest, False)
584 | otherwise = (str, True)
586 hs_file = file <.> "hs"
587 lhs_file = file <.> "lhs"
589 target tid = Target tid obj_allowed Nothing
591 -- -----------------------------------------------------------------------------
592 -- Extending the program scope
594 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
595 extendGlobalRdrScope rdrElts
596 = modifySession $ \hscEnv ->
597 let global_rdr = hsc_global_rdr_env hscEnv
598 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
600 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
601 setGlobalRdrScope rdrElts
602 = modifySession $ \hscEnv ->
603 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
605 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
606 extendGlobalTypeScope ids
607 = modifySession $ \hscEnv ->
608 let global_type = hsc_global_type_env hscEnv
609 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
611 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
612 setGlobalTypeScope ids
613 = modifySession $ \hscEnv ->
614 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
616 -- -----------------------------------------------------------------------------
617 -- Parsing Haddock comments
619 parseHaddockComment :: String -> Either String (HsDoc RdrName)
620 parseHaddockComment string =
621 case parseHaddockParagraphs (tokenise string) of
625 -- -----------------------------------------------------------------------------
626 -- Loading the program
628 -- | Perform a dependency analysis starting from the current targets
629 -- and update the session with the new module graph.
630 depanal :: GhcMonad m =>
631 [ModuleName] -- ^ excluded modules
632 -> Bool -- ^ allow duplicate roots
634 depanal excluded_mods allow_dup_roots = do
635 hsc_env <- getSession
637 dflags = hsc_dflags hsc_env
638 targets = hsc_targets hsc_env
639 old_graph = hsc_mod_graph hsc_env
641 liftIO $ showPass dflags "Chasing dependencies"
642 liftIO $ debugTraceMsg dflags 2 (hcat [
643 text "Chasing modules from: ",
644 hcat (punctuate comma (map pprTarget targets))])
646 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
647 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
652 | LoadUpTo ModuleName
653 | LoadDependenciesOf ModuleName
655 -- | Try to load the program. Calls 'loadWithLogger' with the default
656 -- compiler that just immediately logs all warnings and errors.
657 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
659 loadWithLogger defaultWarnErrLogger how_much
661 -- | A function called to log warnings and errors.
662 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
664 defaultWarnErrLogger :: WarnErrLogger
665 defaultWarnErrLogger Nothing = printWarnings
666 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
668 -- | Try to load the program. If a Module is supplied, then just
669 -- attempt to load up to this target. If no Module is supplied,
670 -- then try to load all targets.
672 -- The first argument is a function that is called after compiling each
673 -- module to print wanrings and errors.
675 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
676 loadWithLogger logger how_much = do
677 -- Dependency analysis first. Note that this fixes the module graph:
678 -- even if we don't get a fully successful upsweep, the full module
679 -- graph is still retained in the Session. We can tell which modules
680 -- were successfully loaded by inspecting the Session's HPT.
681 mod_graph <- depanal [] False
682 load2 how_much mod_graph logger
684 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary] -> WarnErrLogger
686 load2 how_much mod_graph logger = do
688 hsc_env <- getSession
690 let hpt1 = hsc_HPT hsc_env
691 let dflags = hsc_dflags hsc_env
693 -- The "bad" boot modules are the ones for which we have
694 -- B.hs-boot in the module graph, but no B.hs
695 -- The downsweep should have ensured this does not happen
697 let all_home_mods = [ms_mod_name s
698 | s <- mod_graph, not (isBootSummary s)]
699 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
700 not (ms_mod_name s `elem` all_home_mods)]
701 ASSERT( null bad_boot_mods ) return ()
703 -- check that the module given in HowMuch actually exists, otherwise
704 -- topSortModuleGraph will bomb later.
705 let checkHowMuch (LoadUpTo m) = checkMod m
706 checkHowMuch (LoadDependenciesOf m) = checkMod m
710 | m `elem` all_home_mods = and_then
712 liftIO $ errorMsg dflags (text "no such module:" <+>
716 checkHowMuch how_much $ do
718 -- mg2_with_srcimps drops the hi-boot nodes, returning a
719 -- graph with cycles. Among other things, it is used for
720 -- backing out partially complete cycles following a failed
721 -- upsweep, and for removing from hpt all the modules
722 -- not in strict downwards closure, during calls to compile.
723 let mg2_with_srcimps :: [SCC ModSummary]
724 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
726 -- If we can determine that any of the {-# SOURCE #-} imports
727 -- are definitely unnecessary, then emit a warning.
728 warnUnnecessarySourceImports dflags mg2_with_srcimps
731 -- check the stability property for each module.
732 stable_mods@(stable_obj,stable_bco)
733 = checkStability hpt1 mg2_with_srcimps all_home_mods
735 -- prune bits of the HPT which are definitely redundant now,
737 pruned_hpt = pruneHomePackageTable hpt1
738 (flattenSCCs mg2_with_srcimps)
741 liftIO $ evaluate pruned_hpt
743 -- before we unload anything, make sure we don't leave an old
744 -- interactive context around pointing to dead bindings. Also,
745 -- write the pruned HPT to allow the old HPT to be GC'd.
746 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
747 hsc_HPT = pruned_hpt }
749 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
750 text "Stable BCO:" <+> ppr stable_bco)
752 -- Unload any modules which are going to be re-linked this time around.
753 let stable_linkables = [ linkable
754 | m <- stable_obj++stable_bco,
755 Just hmi <- [lookupUFM pruned_hpt m],
756 Just linkable <- [hm_linkable hmi] ]
757 liftIO $ unload hsc_env stable_linkables
759 -- We could at this point detect cycles which aren't broken by
760 -- a source-import, and complain immediately, but it seems better
761 -- to let upsweep_mods do this, so at least some useful work gets
762 -- done before the upsweep is abandoned.
763 --hPutStrLn stderr "after tsort:\n"
764 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
766 -- Now do the upsweep, calling compile for each module in
767 -- turn. Final result is version 3 of everything.
769 -- Topologically sort the module graph, this time including hi-boot
770 -- nodes, and possibly just including the portion of the graph
771 -- reachable from the module specified in the 2nd argument to load.
772 -- This graph should be cycle-free.
773 -- If we're restricting the upsweep to a portion of the graph, we
774 -- also want to retain everything that is still stable.
775 let full_mg :: [SCC ModSummary]
776 full_mg = topSortModuleGraph False mod_graph Nothing
778 maybe_top_mod = case how_much of
780 LoadDependenciesOf m -> Just m
783 partial_mg0 :: [SCC ModSummary]
784 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
786 -- LoadDependenciesOf m: we want the upsweep to stop just
787 -- short of the specified module (unless the specified module
790 | LoadDependenciesOf _mod <- how_much
791 = ASSERT( case last partial_mg0 of
792 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
793 List.init partial_mg0
799 | AcyclicSCC ms <- full_mg,
800 ms_mod_name ms `elem` stable_obj++stable_bco,
801 ms_mod_name ms `notElem` [ ms_mod_name ms' |
802 AcyclicSCC ms' <- partial_mg ] ]
804 mg = stable_mg ++ partial_mg
806 -- clean up between compilations
807 let cleanup = cleanTempFilesExcept dflags
808 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
810 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
812 (upsweep_ok, hsc_env1, modsUpswept)
814 (hsc_env { hsc_HPT = emptyHomePackageTable })
815 pruned_hpt stable_mods cleanup mg
817 -- Make modsDone be the summaries for each home module now
818 -- available; this should equal the domain of hpt3.
819 -- Get in in a roughly top .. bottom order (hence reverse).
821 let modsDone = reverse modsUpswept
823 -- Try and do linking in some form, depending on whether the
824 -- upsweep was completely or only partially successful.
826 if succeeded upsweep_ok
829 -- Easy; just relink it all.
830 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
832 -- Clean up after ourselves
833 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
835 -- Issue a warning for the confusing case where the user
836 -- said '-o foo' but we're not going to do any linking.
837 -- We attempt linking if either (a) one of the modules is
838 -- called Main, or (b) the user said -no-hs-main, indicating
839 -- that main() is going to come from somewhere else.
841 let ofile = outputFile dflags
842 let no_hs_main = dopt Opt_NoHsMain dflags
844 main_mod = mainModIs dflags
845 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
846 do_linking = a_root_is_Main || no_hs_main
848 when (ghcLink dflags == LinkBinary
849 && isJust ofile && not do_linking) $
850 liftIO $ debugTraceMsg dflags 1 $
851 text ("Warning: output was redirected with -o, " ++
852 "but no output will be generated\n" ++
853 "because there is no " ++
854 moduleNameString (moduleName main_mod) ++ " module.")
856 -- link everything together
857 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
859 loadFinish Succeeded linkresult hsc_env1
862 -- Tricky. We need to back out the effects of compiling any
863 -- half-done cycles, both so as to clean up the top level envs
864 -- and to avoid telling the interactive linker to link them.
865 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
868 = map ms_mod modsDone
869 let mods_to_zap_names
870 = findPartiallyCompletedCycles modsDone_names
873 = filter ((`notElem` mods_to_zap_names).ms_mod)
876 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
879 -- Clean up after ourselves
880 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
882 -- there should be no Nothings where linkables should be, now
883 ASSERT(all (isJust.hm_linkable)
884 (eltsUFM (hsc_HPT hsc_env))) do
886 -- Link everything together
887 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
889 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
890 loadFinish Failed linkresult hsc_env4
892 -- Finish up after a load.
894 -- If the link failed, unload everything and return.
895 loadFinish :: GhcMonad m =>
896 SuccessFlag -> SuccessFlag -> HscEnv
898 loadFinish _all_ok Failed hsc_env
899 = do liftIO $ unload hsc_env []
900 modifySession $ \_ -> discardProg hsc_env
903 -- Empty the interactive context and set the module context to the topmost
904 -- newly loaded module, or the Prelude if none were loaded.
905 loadFinish all_ok Succeeded hsc_env
906 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
910 -- Forget the current program, but retain the persistent info in HscEnv
911 discardProg :: HscEnv -> HscEnv
913 = hsc_env { hsc_mod_graph = emptyMG,
914 hsc_IC = emptyInteractiveContext,
915 hsc_HPT = emptyHomePackageTable }
917 -- used to fish out the preprocess output files for the purposes of
918 -- cleaning up. The preprocessed file *might* be the same as the
919 -- source file, but that doesn't do any harm.
920 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
921 ppFilesFromSummaries summaries = map ms_hspp_file summaries
923 -- -----------------------------------------------------------------------------
925 class ParsedMod m where
926 modSummary :: m -> ModSummary
927 parsedSource :: m -> ParsedSource
929 class ParsedMod m => TypecheckedMod m where
930 renamedSource :: m -> Maybe RenamedSource
931 typecheckedSource :: m -> TypecheckedSource
932 moduleInfo :: m -> ModuleInfo
933 tm_internals :: m -> (TcGblEnv, ModDetails)
934 -- ToDo: improvements that could be made here:
935 -- if the module succeeded renaming but not typechecking,
936 -- we can still get back the GlobalRdrEnv and exports, so
937 -- perhaps the ModuleInfo should be split up into separate
940 class TypecheckedMod m => DesugaredMod m where
941 coreModule :: m -> ModGuts
943 -- | The result of successful parsing.
945 ParsedModule { pm_mod_summary :: ModSummary
946 , pm_parsed_source :: ParsedSource }
948 instance ParsedMod ParsedModule where
949 modSummary m = pm_mod_summary m
950 parsedSource m = pm_parsed_source m
952 -- | The result of successful typechecking. It also contains the parser
954 data TypecheckedModule =
955 TypecheckedModule { tm_parsed_module :: ParsedModule
956 , tm_renamed_source :: Maybe RenamedSource
957 , tm_typechecked_source :: TypecheckedSource
958 , tm_checked_module_info :: ModuleInfo
959 , tm_internals_ :: (TcGblEnv, ModDetails)
962 instance ParsedMod TypecheckedModule where
963 modSummary m = modSummary (tm_parsed_module m)
964 parsedSource m = parsedSource (tm_parsed_module m)
966 instance TypecheckedMod TypecheckedModule where
967 renamedSource m = tm_renamed_source m
968 typecheckedSource m = tm_typechecked_source m
969 moduleInfo m = tm_checked_module_info m
970 tm_internals m = tm_internals_ m
972 -- | The result of successful desugaring (i.e., translation to core). Also
973 -- contains all the information of a typechecked module.
974 data DesugaredModule =
975 DesugaredModule { dm_typechecked_module :: TypecheckedModule
976 , dm_core_module :: ModGuts
979 instance ParsedMod DesugaredModule where
980 modSummary m = modSummary (dm_typechecked_module m)
981 parsedSource m = parsedSource (dm_typechecked_module m)
983 instance TypecheckedMod DesugaredModule where
984 renamedSource m = renamedSource (dm_typechecked_module m)
985 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
986 moduleInfo m = moduleInfo (dm_typechecked_module m)
987 tm_internals m = tm_internals_ (dm_typechecked_module m)
989 instance DesugaredMod DesugaredModule where
990 coreModule m = dm_core_module m
992 type ParsedSource = Located (HsModule RdrName)
993 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
994 Maybe (HsDoc Name), HaddockModInfo Name)
995 type TypecheckedSource = LHsBinds Id
998 -- - things that aren't in the output of the typechecker right now:
1001 -- - type signatures
1002 -- - type/data/newtype declarations
1003 -- - class declarations
1005 -- - extra things in the typechecker's output:
1006 -- - default methods are turned into top-level decls.
1007 -- - dictionary bindings
1009 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1010 getModSummary mod = do
1011 mg <- liftM hsc_mod_graph getSession
1012 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
1013 [] -> throw $ mkApiErr (text "Module not part of module graph")
1016 -- | Parse a module.
1018 -- Throws a 'SourceError' on parse error.
1019 parseModule :: GhcMonad m => ModuleName -> m ParsedModule
1020 parseModule mod = do
1021 ms <- getModSummary mod
1022 hsc_env0 <- getSession
1023 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1024 rdr_module <- parseFile hsc_env ms
1025 return (ParsedModule ms rdr_module)
1027 -- | Typecheck and rename a parsed module.
1029 -- Throws a 'SourceError' if either fails.
1030 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1031 typecheckModule pmod = do
1032 let ms = modSummary pmod
1033 hsc_env0 <- getSession
1034 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1035 (tc_gbl_env, rn_info)
1036 <- typecheckRenameModule hsc_env ms (parsedSource pmod)
1037 details <- liftIO $ makeSimpleDetails hsc_env tc_gbl_env
1040 tm_internals_ = (tc_gbl_env, details),
1041 tm_parsed_module = pmod,
1042 tm_renamed_source = rn_info,
1043 tm_typechecked_source = tcg_binds tc_gbl_env,
1044 tm_checked_module_info =
1046 minf_type_env = md_types details,
1047 minf_exports = availsToNameSet $ md_exports details,
1048 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1049 minf_instances = md_insts details
1051 ,minf_modBreaks = emptyModBreaks
1055 -- | Desugar a typechecked module.
1056 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1057 desugarModule tcm = do
1058 let ms = modSummary tcm
1059 hsc_env0 <- getSession
1060 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1061 let (tcg, _) = tm_internals tcm
1062 guts <- deSugarModule hsc_env ms tcg
1065 dm_typechecked_module = tcm,
1066 dm_core_module = guts
1069 -- | Load a module. Input doesn't need to be desugared.
1071 -- XXX: Describe usage.
1072 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1074 let ms = modSummary tcm
1075 let mod = ms_mod_name ms
1076 hsc_env0 <- getSession
1077 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1078 let (tcg, details) = tm_internals tcm
1079 (iface,_) <- liftIO $ makeSimpleIface hsc_env Nothing tcg details
1080 let mod_info = HomeModInfo {
1082 hm_details = details,
1083 hm_linkable = Nothing }
1084 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
1085 modifySession $ \_ -> hsc_env0{ hsc_HPT = hpt_new }
1088 -- | This is the way to get access to the Core bindings corresponding
1089 -- to a module. 'compileToCore' parses, typechecks, and
1090 -- desugars the module, then returns the resulting Core module (consisting of
1091 -- the module name, type declarations, and function declarations) if
1093 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1094 compileToCoreModule = compileCore False
1096 -- | Like compileToCoreModule, but invokes the simplifier, so
1097 -- as to return simplified and tidied Core.
1098 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1099 compileToCoreSimplified = compileCore True
1101 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1102 -- bindings, but for most purposes, you probably want to call
1103 -- compileToCoreModule.
1104 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1105 compileToCore fn = do
1106 mod <- compileToCoreModule session fn
1107 return $ cm_binds mod
1109 -- | Takes a CoreModule and compiles the bindings therein
1110 -- to object code. The first argument is a bool flag indicating
1111 -- whether to run the simplifier.
1112 -- The resulting .o, .hi, and executable files, if any, are stored in the
1113 -- current directory, and named according to the module name.
1114 -- Returns True iff compilation succeeded.
1115 -- This has only so far been tested with a single self-contained module.
1116 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1117 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1118 hscEnv <- getSession
1119 dflags <- getSessionDynFlags
1120 currentTime <- liftIO $ getClockTime
1121 cwd <- liftIO $ getCurrentDirectory
1122 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1123 ((moduleNameSlashes . moduleName) mName)
1125 let modSummary = ModSummary { ms_mod = mName,
1126 ms_hsc_src = ExtCoreFile,
1127 ms_location = modLocation,
1128 -- By setting the object file timestamp to Nothing,
1129 -- we always force recompilation, which is what we
1130 -- want. (Thus it doesn't matter what the timestamp
1131 -- for the (nonexistent) source file is.)
1132 ms_hs_date = currentTime,
1133 ms_obj_date = Nothing,
1134 -- Only handling the single-module case for now, so no imports.
1139 ms_hspp_opts = dflags,
1140 ms_hspp_buf = Nothing
1143 ioMsgMaybe $ flip evalComp (CompState{ compHscEnv=hscEnv,
1144 compModSummary=modSummary,
1145 compOldIface=Nothing}) $
1146 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1147 | otherwise = return mod_guts
1148 in maybe_simplify (mkModGuts cm)
1154 -- Makes a "vanilla" ModGuts.
1155 mkModGuts :: CoreModule -> ModGuts
1156 mkModGuts coreModule = ModGuts {
1157 mg_module = cm_module coreModule,
1160 mg_deps = noDependencies,
1161 mg_dir_imps = emptyModuleEnv,
1162 mg_used_names = emptyNameSet,
1163 mg_rdr_env = emptyGlobalRdrEnv,
1164 mg_fix_env = emptyFixityEnv,
1165 mg_types = emptyTypeEnv,
1169 mg_binds = cm_binds coreModule,
1170 mg_foreign = NoStubs,
1171 mg_warns = NoWarnings,
1172 mg_hpc_info = emptyHpcInfo False,
1173 mg_modBreaks = emptyModBreaks,
1174 mg_vect_info = noVectInfo,
1175 mg_inst_env = emptyInstEnv,
1176 mg_fam_inst_env = emptyFamInstEnv
1179 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1180 compileCore simplify fn = do
1181 -- First, set the target to the desired filename
1182 target <- guessTarget fn Nothing
1185 -- Then find dependencies
1186 modGraph <- depanal [] True
1187 case find ((== fn) . msHsFilePath) modGraph of
1188 Just modSummary -> do
1189 -- Now we have the module name;
1190 -- parse, typecheck and desugar the module
1191 let mod = ms_mod_name modSummary
1192 mod_guts <- coreModule `fmap`
1193 (desugarModule =<< typecheckModule =<< parseModule mod)
1194 liftM gutsToCoreModule $
1197 -- If simplify is true: simplify (hscSimplify), then tidy
1199 hsc_env <- getSession
1200 simpl_guts <- ioMsg $ evalComp (hscSimplify mod_guts)
1202 compHscEnv = hsc_env,
1203 compModSummary = modSummary,
1204 compOldIface = Nothing})
1205 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1206 return $ Left tidy_guts
1208 return $ Right mod_guts
1210 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1211 module dependency graph"
1212 where -- two versions, based on whether we simplify (thus run tidyProgram,
1213 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1214 -- we just have a ModGuts.
1215 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1216 gutsToCoreModule (Left (cg, md)) = CoreModule {
1217 cm_module = cg_module cg, cm_types = md_types md,
1218 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1220 gutsToCoreModule (Right mg) = CoreModule {
1221 cm_module = mg_module mg, cm_types = mg_types mg,
1222 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1225 -- ---------------------------------------------------------------------------
1228 unload :: HscEnv -> [Linkable] -> IO ()
1229 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1230 = case ghcLink (hsc_dflags hsc_env) of
1232 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1234 LinkInMemory -> panic "unload: no interpreter"
1235 -- urgh. avoid warnings:
1236 hsc_env stable_linkables
1240 -- -----------------------------------------------------------------------------
1244 Stability tells us which modules definitely do not need to be recompiled.
1245 There are two main reasons for having stability:
1247 - avoid doing a complete upsweep of the module graph in GHCi when
1248 modules near the bottom of the tree have not changed.
1250 - to tell GHCi when it can load object code: we can only load object code
1251 for a module when we also load object code fo all of the imports of the
1252 module. So we need to know that we will definitely not be recompiling
1253 any of these modules, and we can use the object code.
1255 The stability check is as follows. Both stableObject and
1256 stableBCO are used during the upsweep phase later.
1259 stable m = stableObject m || stableBCO m
1262 all stableObject (imports m)
1263 && old linkable does not exist, or is == on-disk .o
1264 && date(on-disk .o) > date(.hs)
1267 all stable (imports m)
1268 && date(BCO) > date(.hs)
1271 These properties embody the following ideas:
1273 - if a module is stable, then:
1275 - if it has been compiled in a previous pass (present in HPT)
1276 then it does not need to be compiled or re-linked.
1278 - if it has not been compiled in a previous pass,
1279 then we only need to read its .hi file from disk and
1280 link it to produce a 'ModDetails'.
1282 - if a modules is not stable, we will definitely be at least
1283 re-linking, and possibly re-compiling it during the 'upsweep'.
1284 All non-stable modules can (and should) therefore be unlinked
1285 before the 'upsweep'.
1287 - Note that objects are only considered stable if they only depend
1288 on other objects. We can't link object code against byte code.
1292 :: HomePackageTable -- HPT from last compilation
1293 -> [SCC ModSummary] -- current module graph (cyclic)
1294 -> [ModuleName] -- all home modules
1295 -> ([ModuleName], -- stableObject
1296 [ModuleName]) -- stableBCO
1298 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1300 checkSCC (stable_obj, stable_bco) scc0
1301 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1302 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1303 | otherwise = (stable_obj, stable_bco)
1305 scc = flattenSCC scc0
1306 scc_mods = map ms_mod_name scc
1307 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1309 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1310 -- all imports outside the current SCC, but in the home pkg
1312 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1313 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1317 && all object_ok scc
1320 and (zipWith (||) stable_obj_imps stable_bco_imps)
1324 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1328 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1329 Just hmi | Just l <- hm_linkable hmi
1330 -> isObjectLinkable l && t == linkableTime l
1332 -- why '>=' rather than '>' above? If the filesystem stores
1333 -- times to the nearset second, we may occasionally find that
1334 -- the object & source have the same modification time,
1335 -- especially if the source was automatically generated
1336 -- and compiled. Using >= is slightly unsafe, but it matches
1337 -- make's behaviour.
1340 = case lookupUFM hpt (ms_mod_name ms) of
1341 Just hmi | Just l <- hm_linkable hmi ->
1342 not (isObjectLinkable l) &&
1343 linkableTime l >= ms_hs_date ms
1346 ms_allimps :: ModSummary -> [ModuleName]
1347 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1349 -- -----------------------------------------------------------------------------
1351 -- | Prune the HomePackageTable
1353 -- Before doing an upsweep, we can throw away:
1355 -- - For non-stable modules:
1356 -- - all ModDetails, all linked code
1357 -- - all unlinked code that is out of date with respect to
1360 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1361 -- space at the end of the upsweep, because the topmost ModDetails of the
1362 -- old HPT holds on to the entire type environment from the previous
1365 pruneHomePackageTable
1368 -> ([ModuleName],[ModuleName])
1371 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1374 | is_stable modl = hmi'
1375 | otherwise = hmi'{ hm_details = emptyModDetails }
1377 modl = moduleName (mi_module (hm_iface hmi))
1378 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1379 = hmi{ hm_linkable = Nothing }
1382 where ms = expectJust "prune" (lookupUFM ms_map modl)
1384 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1386 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1388 -- -----------------------------------------------------------------------------
1390 -- Return (names of) all those in modsDone who are part of a cycle
1391 -- as defined by theGraph.
1392 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1393 findPartiallyCompletedCycles modsDone theGraph
1397 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1398 chew ((CyclicSCC vs):rest)
1399 = let names_in_this_cycle = nub (map ms_mod vs)
1401 = nub ([done | done <- modsDone,
1402 done `elem` names_in_this_cycle])
1403 chewed_rest = chew rest
1405 if notNull mods_in_this_cycle
1406 && length mods_in_this_cycle < length names_in_this_cycle
1407 then mods_in_this_cycle ++ chewed_rest
1410 -- -----------------------------------------------------------------------------
1414 -- This is where we compile each module in the module graph, in a pass
1415 -- from the bottom to the top of the graph.
1417 -- There better had not be any cyclic groups here -- we check for them.
1421 WarnErrLogger -- ^ Called to print warnings and errors.
1422 -> HscEnv -- ^ Includes initially-empty HPT
1423 -> HomePackageTable -- ^ HPT from last time round (pruned)
1424 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1425 -> IO () -- ^ How to clean up unwanted tmp files
1426 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1428 HscEnv, -- With an updated HPT
1429 [ModSummary]) -- Mods which succeeded
1431 upsweep logger hsc_env old_hpt stable_mods cleanup sccs = do
1432 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1433 return (res, hsc_env, reverse done)
1436 upsweep' hsc_env _old_hpt done
1438 = return (Succeeded, hsc_env, done)
1440 upsweep' hsc_env _old_hpt done
1441 (CyclicSCC ms:_) _ _
1442 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1443 return (Failed, hsc_env, done)
1445 upsweep' hsc_env old_hpt done
1446 (AcyclicSCC mod:mods) mod_index nmods
1447 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1448 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1449 -- (moduleEnvElts (hsc_HPT hsc_env)))
1452 <- handleSourceError
1453 (\err -> do logger (Just err); return Nothing) $ do
1454 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1456 logger Nothing -- log warnings
1457 return (Just mod_info)
1459 liftIO cleanup -- Remove unwanted tmp files between compilations
1462 Nothing -> return (Failed, hsc_env, done)
1464 let this_mod = ms_mod_name mod
1466 -- Add new info to hsc_env
1467 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1468 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1470 -- Space-saving: delete the old HPT entry
1471 -- for mod BUT if mod is a hs-boot
1472 -- node, don't delete it. For the
1473 -- interface, the HPT entry is probaby for the
1474 -- main Haskell source file. Deleting it
1475 -- would force the real module to be recompiled
1477 old_hpt1 | isBootSummary mod = old_hpt
1478 | otherwise = delFromUFM old_hpt this_mod
1482 -- fixup our HomePackageTable after we've finished compiling
1483 -- a mutually-recursive loop. See reTypecheckLoop, below.
1484 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1486 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1488 -- | Compile a single module. Always produce a Linkable for it if
1489 -- successful. If no compilation happened, return the old Linkable.
1490 upsweep_mod :: GhcMonad m =>
1493 -> ([ModuleName],[ModuleName])
1495 -> Int -- index of module
1496 -> Int -- total number of modules
1499 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1501 this_mod_name = ms_mod_name summary
1502 this_mod = ms_mod summary
1503 mb_obj_date = ms_obj_date summary
1504 obj_fn = ml_obj_file (ms_location summary)
1505 hs_date = ms_hs_date summary
1507 is_stable_obj = this_mod_name `elem` stable_obj
1508 is_stable_bco = this_mod_name `elem` stable_bco
1510 old_hmi = lookupUFM old_hpt this_mod_name
1512 -- We're using the dflags for this module now, obtained by
1513 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1514 dflags = ms_hspp_opts summary
1515 prevailing_target = hscTarget (hsc_dflags hsc_env)
1516 local_target = hscTarget dflags
1518 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1519 -- we don't do anything dodgy: these should only work to change
1520 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1521 -- end up trying to link object code to byte code.
1522 target = if prevailing_target /= local_target
1523 && (not (isObjectTarget prevailing_target)
1524 || not (isObjectTarget local_target))
1525 then prevailing_target
1528 -- store the corrected hscTarget into the summary
1529 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1531 -- The old interface is ok if
1532 -- a) we're compiling a source file, and the old HPT
1533 -- entry is for a source file
1534 -- b) we're compiling a hs-boot file
1535 -- Case (b) allows an hs-boot file to get the interface of its
1536 -- real source file on the second iteration of the compilation
1537 -- manager, but that does no harm. Otherwise the hs-boot file
1538 -- will always be recompiled
1543 Just hm_info | isBootSummary summary -> Just iface
1544 | not (mi_boot iface) -> Just iface
1545 | otherwise -> Nothing
1547 iface = hm_iface hm_info
1549 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1550 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1552 compile_it_discard_iface :: GhcMonad m =>
1553 Maybe Linkable -> m HomeModInfo
1554 compile_it_discard_iface
1555 = compile hsc_env summary' mod_index nmods Nothing
1561 -- Regardless of whether we're generating object code or
1562 -- byte code, we can always use an existing object file
1563 -- if it is *stable* (see checkStability).
1564 | is_stable_obj, isJust old_hmi ->
1565 let Just hmi = old_hmi in
1567 -- object is stable, and we have an entry in the
1568 -- old HPT: nothing to do
1570 | is_stable_obj, isNothing old_hmi -> do
1571 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1572 (expectJust "upsweep1" mb_obj_date)
1573 compile_it (Just linkable)
1574 -- object is stable, but we need to load the interface
1575 -- off disk to make a HMI.
1579 ASSERT(isJust old_hmi) -- must be in the old_hpt
1580 let Just hmi = old_hmi in
1582 -- BCO is stable: nothing to do
1584 | Just hmi <- old_hmi,
1585 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1586 linkableTime l >= ms_hs_date summary ->
1588 -- we have an old BCO that is up to date with respect
1589 -- to the source: do a recompilation check as normal.
1593 -- no existing code at all: we must recompile.
1595 -- When generating object code, if there's an up-to-date
1596 -- object file on the disk, then we can use it.
1597 -- However, if the object file is new (compared to any
1598 -- linkable we had from a previous compilation), then we
1599 -- must discard any in-memory interface, because this
1600 -- means the user has compiled the source file
1601 -- separately and generated a new interface, that we must
1602 -- read from the disk.
1604 obj | isObjectTarget obj,
1605 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1608 | Just l <- hm_linkable hmi,
1609 isObjectLinkable l && linkableTime l == obj_date
1610 -> compile_it (Just l)
1612 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1613 compile_it_discard_iface (Just linkable)
1620 -- Filter modules in the HPT
1621 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1622 retainInTopLevelEnvs keep_these hpt
1623 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1625 , let mb_mod_info = lookupUFM hpt mod
1626 , isJust mb_mod_info ]
1628 -- ---------------------------------------------------------------------------
1629 -- Typecheck module loops
1632 See bug #930. This code fixes a long-standing bug in --make. The
1633 problem is that when compiling the modules *inside* a loop, a data
1634 type that is only defined at the top of the loop looks opaque; but
1635 after the loop is done, the structure of the data type becomes
1638 The difficulty is then that two different bits of code have
1639 different notions of what the data type looks like.
1641 The idea is that after we compile a module which also has an .hs-boot
1642 file, we re-generate the ModDetails for each of the modules that
1643 depends on the .hs-boot file, so that everyone points to the proper
1644 TyCons, Ids etc. defined by the real module, not the boot module.
1645 Fortunately re-generating a ModDetails from a ModIface is easy: the
1646 function TcIface.typecheckIface does exactly that.
1648 Picking the modules to re-typecheck is slightly tricky. Starting from
1649 the module graph consisting of the modules that have already been
1650 compiled, we reverse the edges (so they point from the imported module
1651 to the importing module), and depth-first-search from the .hs-boot
1652 node. This gives us all the modules that depend transitively on the
1653 .hs-boot module, and those are exactly the modules that we need to
1656 Following this fix, GHC can compile itself with --make -O2.
1659 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1660 reTypecheckLoop hsc_env ms graph
1661 | not (isBootSummary ms) &&
1662 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1664 let mss = reachableBackwards (ms_mod_name ms) graph
1665 non_boot = filter (not.isBootSummary) mss
1666 debugTraceMsg (hsc_dflags hsc_env) 2 $
1667 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1668 typecheckLoop hsc_env (map ms_mod_name non_boot)
1672 this_mod = ms_mod ms
1674 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1675 typecheckLoop hsc_env mods = do
1677 fixIO $ \new_hpt -> do
1678 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1679 mds <- initIfaceCheck new_hsc_env $
1680 mapM (typecheckIface . hm_iface) hmis
1681 let new_hpt = addListToUFM old_hpt
1682 (zip mods [ hmi{ hm_details = details }
1683 | (hmi,details) <- zip hmis mds ])
1685 return hsc_env{ hsc_HPT = new_hpt }
1687 old_hpt = hsc_HPT hsc_env
1688 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1690 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1691 reachableBackwards mod summaries
1692 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1693 where -- the rest just sets up the graph:
1694 (graph, lookup_node) = moduleGraphNodes False summaries
1695 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1697 -- ---------------------------------------------------------------------------
1698 -- Topological sort of the module graph
1700 type SummaryNode = (ModSummary, Int, [Int])
1703 :: Bool -- Drop hi-boot nodes? (see below)
1707 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1708 -- The resulting list of strongly-connected-components is in topologically
1709 -- sorted order, starting with the module(s) at the bottom of the
1710 -- dependency graph (ie compile them first) and ending with the ones at
1713 -- Drop hi-boot nodes (first boolean arg)?
1715 -- False: treat the hi-boot summaries as nodes of the graph,
1716 -- so the graph must be acyclic
1718 -- True: eliminate the hi-boot nodes, and instead pretend
1719 -- the a source-import of Foo is an import of Foo
1720 -- The resulting graph has no hi-boot nodes, but can by cyclic
1722 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1723 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1725 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1727 initial_graph = case mb_root_mod of
1730 -- restrict the graph to just those modules reachable from
1731 -- the specified module. We do this by building a graph with
1732 -- the full set of nodes, and determining the reachable set from
1733 -- the specified node.
1734 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1735 | otherwise = ghcError (ProgramError "module does not exist")
1736 in graphFromEdgedVertices (seq root (reachableG graph root))
1738 summaryNodeKey :: SummaryNode -> Int
1739 summaryNodeKey (_, k, _) = k
1741 summaryNodeSummary :: SummaryNode -> ModSummary
1742 summaryNodeSummary (s, _, _) = s
1744 moduleGraphNodes :: Bool -> [ModSummary]
1745 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1746 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1748 numbered_summaries = zip summaries [1..]
1750 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1751 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1753 lookup_key :: HscSource -> ModuleName -> Maybe Int
1754 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1756 node_map :: NodeMap SummaryNode
1757 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1758 | node@(s, _, _) <- nodes ]
1760 -- We use integers as the keys for the SCC algorithm
1761 nodes :: [SummaryNode]
1762 nodes = [ (s, key, out_keys)
1763 | (s, key) <- numbered_summaries
1764 -- Drop the hi-boot ones if told to do so
1765 , not (isBootSummary s && drop_hs_boot_nodes)
1766 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1767 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1768 (-- see [boot-edges] below
1769 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1771 else case lookup_key HsBootFile (ms_mod_name s) of
1775 -- [boot-edges] if this is a .hs and there is an equivalent
1776 -- .hs-boot, add a link from the former to the latter. This
1777 -- has the effect of detecting bogus cases where the .hs-boot
1778 -- depends on the .hs, by introducing a cycle. Additionally,
1779 -- it ensures that we will always process the .hs-boot before
1780 -- the .hs, and so the HomePackageTable will always have the
1781 -- most up to date information.
1783 -- Drop hs-boot nodes by using HsSrcFile as the key
1784 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1785 | otherwise = HsBootFile
1787 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1788 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1789 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1790 -- the IsBootInterface parameter True; else False
1793 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1794 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1796 msKey :: ModSummary -> NodeKey
1797 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1799 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1800 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1802 nodeMapElts :: NodeMap a -> [a]
1803 nodeMapElts = eltsFM
1805 -- | If there are {-# SOURCE #-} imports between strongly connected
1806 -- components in the topological sort, then those imports can
1807 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1808 -- were necessary, then the edge would be part of a cycle.
1809 warnUnnecessarySourceImports :: GhcMonad m => DynFlags -> [SCC ModSummary] -> m ()
1810 warnUnnecessarySourceImports dflags sccs =
1811 liftIO $ printBagOfWarnings dflags (listToBag (concatMap (check.flattenSCC) sccs))
1813 let mods_in_this_cycle = map ms_mod_name ms in
1814 [ warn i | m <- ms, i <- ms_srcimps m,
1815 unLoc i `notElem` mods_in_this_cycle ]
1817 warn :: Located ModuleName -> WarnMsg
1820 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1821 <+> quotes (ppr mod))
1823 -----------------------------------------------------------------------------
1824 -- Downsweep (dependency analysis)
1826 -- Chase downwards from the specified root set, returning summaries
1827 -- for all home modules encountered. Only follow source-import
1830 -- We pass in the previous collection of summaries, which is used as a
1831 -- cache to avoid recalculating a module summary if the source is
1834 -- The returned list of [ModSummary] nodes has one node for each home-package
1835 -- module, plus one for any hs-boot files. The imports of these nodes
1836 -- are all there, including the imports of non-home-package modules.
1838 downsweep :: GhcMonad m =>
1840 -> [ModSummary] -- Old summaries
1841 -> [ModuleName] -- Ignore dependencies on these; treat
1842 -- them as if they were package modules
1843 -> Bool -- True <=> allow multiple targets to have
1844 -- the same module name; this is
1845 -- very useful for ghc -M
1847 -- The elts of [ModSummary] all have distinct
1848 -- (Modules, IsBoot) identifiers, unless the Bool is true
1849 -- in which case there can be repeats
1850 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1851 = do -- catch error messages and return them
1852 --handleErrMsg -- should be covered by GhcMonad now
1853 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1854 rootSummaries <- mapM getRootSummary roots
1855 let root_map = mkRootMap rootSummaries
1856 checkDuplicates root_map
1857 summs <- loop (concatMap msDeps rootSummaries) root_map
1860 roots = hsc_targets hsc_env
1862 old_summary_map :: NodeMap ModSummary
1863 old_summary_map = mkNodeMap old_summaries
1865 getRootSummary :: GhcMonad m => Target -> m ModSummary
1866 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1867 = do exists <- liftIO $ doesFileExist file
1869 then summariseFile hsc_env old_summaries file mb_phase
1870 obj_allowed maybe_buf
1871 else throwErrMsg $ mkPlainErrMsg noSrcSpan $
1872 text "can't find file:" <+> text file
1873 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1874 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1875 (L rootLoc modl) obj_allowed
1877 case maybe_summary of
1878 Nothing -> packageModErr modl
1881 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1883 -- In a root module, the filename is allowed to diverge from the module
1884 -- name, so we have to check that there aren't multiple root files
1885 -- defining the same module (otherwise the duplicates will be silently
1886 -- ignored, leading to confusing behaviour).
1887 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1888 checkDuplicates root_map
1889 | allow_dup_roots = return ()
1890 | null dup_roots = return ()
1891 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1893 dup_roots :: [[ModSummary]] -- Each at least of length 2
1894 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1896 loop :: GhcMonad m =>
1897 [(Located ModuleName,IsBootInterface)]
1898 -- Work list: process these modules
1899 -> NodeMap [ModSummary]
1900 -- Visited set; the range is a list because
1901 -- the roots can have the same module names
1902 -- if allow_dup_roots is True
1904 -- The result includes the worklist, except
1905 -- for those mentioned in the visited set
1906 loop [] done = return (concat (nodeMapElts done))
1907 loop ((wanted_mod, is_boot) : ss) done
1908 | Just summs <- lookupFM done key
1909 = if isSingleton summs then
1912 do { liftIO $ multiRootsErr summs; return [] }
1914 = do mb_s <- summariseModule hsc_env old_summary_map
1915 is_boot wanted_mod True
1918 Nothing -> loop ss done
1919 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1921 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1923 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1924 mkRootMap summaries = addListToFM_C (++) emptyFM
1925 [ (msKey s, [s]) | s <- summaries ]
1927 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1928 -- (msDeps s) returns the dependencies of the ModSummary s.
1929 -- A wrinkle is that for a {-# SOURCE #-} import we return
1930 -- *both* the hs-boot file
1931 -- *and* the source file
1932 -- as "dependencies". That ensures that the list of all relevant
1933 -- modules always contains B.hs if it contains B.hs-boot.
1934 -- Remember, this pass isn't doing the topological sort. It's
1935 -- just gathering the list of all relevant ModSummaries
1937 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1938 ++ [ (m,False) | m <- ms_imps s ]
1940 -----------------------------------------------------------------------------
1941 -- Summarising modules
1943 -- We have two types of summarisation:
1945 -- * Summarise a file. This is used for the root module(s) passed to
1946 -- cmLoadModules. The file is read, and used to determine the root
1947 -- module name. The module name may differ from the filename.
1949 -- * Summarise a module. We are given a module name, and must provide
1950 -- a summary. The finder is used to locate the file in which the module
1956 -> [ModSummary] -- old summaries
1957 -> FilePath -- source file name
1958 -> Maybe Phase -- start phase
1959 -> Bool -- object code allowed?
1960 -> Maybe (StringBuffer,ClockTime)
1963 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1964 -- we can use a cached summary if one is available and the
1965 -- source file hasn't changed, But we have to look up the summary
1966 -- by source file, rather than module name as we do in summarise.
1967 | Just old_summary <- findSummaryBySourceFile old_summaries file
1969 let location = ms_location old_summary
1971 -- return the cached summary if the source didn't change
1972 src_timestamp <- case maybe_buf of
1973 Just (_,t) -> return t
1974 Nothing -> liftIO $ getModificationTime file
1975 -- The file exists; we checked in getRootSummary above.
1976 -- If it gets removed subsequently, then this
1977 -- getModificationTime may fail, but that's the right
1980 if ms_hs_date old_summary == src_timestamp
1981 then do -- update the object-file timestamp
1983 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1984 || obj_allowed -- bug #1205
1985 then liftIO $ getObjTimestamp location False
1987 return old_summary{ ms_obj_date = obj_timestamp }
1995 let dflags = hsc_dflags hsc_env
1997 (dflags', hspp_fn, buf)
1998 <- preprocessFile hsc_env file mb_phase maybe_buf
2000 (srcimps,the_imps, L _ mod_name) <- liftIO $ getImports dflags' buf hspp_fn file
2002 -- Make a ModLocation for this file
2003 location <- liftIO $ mkHomeModLocation dflags mod_name file
2005 -- Tell the Finder cache where it is, so that subsequent calls
2006 -- to findModule will find it, even if it's not on any search path
2007 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2009 src_timestamp <- case maybe_buf of
2010 Just (_,t) -> return t
2011 Nothing -> liftIO $ getModificationTime file
2012 -- getMofificationTime may fail
2014 -- when the user asks to load a source file by name, we only
2015 -- use an object file if -fobject-code is on. See #1205.
2017 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2018 || obj_allowed -- bug #1205
2019 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2022 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2023 ms_location = location,
2024 ms_hspp_file = hspp_fn,
2025 ms_hspp_opts = dflags',
2026 ms_hspp_buf = Just buf,
2027 ms_srcimps = srcimps, ms_imps = the_imps,
2028 ms_hs_date = src_timestamp,
2029 ms_obj_date = obj_timestamp })
2031 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2032 findSummaryBySourceFile summaries file
2033 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2034 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2038 -- Summarise a module, and pick up source and timestamp.
2042 -> NodeMap ModSummary -- Map of old summaries
2043 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2044 -> Located ModuleName -- Imported module to be summarised
2045 -> Bool -- object code allowed?
2046 -> Maybe (StringBuffer, ClockTime)
2047 -> [ModuleName] -- Modules to exclude
2048 -> m (Maybe ModSummary) -- Its new summary
2050 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2051 obj_allowed maybe_buf excl_mods
2052 | wanted_mod `elem` excl_mods
2055 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2056 = do -- Find its new timestamp; all the
2057 -- ModSummaries in the old map have valid ml_hs_files
2058 let location = ms_location old_summary
2059 src_fn = expectJust "summariseModule" (ml_hs_file location)
2061 -- check the modification time on the source file, and
2062 -- return the cached summary if it hasn't changed. If the
2063 -- file has disappeared, we need to call the Finder again.
2065 Just (_,t) -> check_timestamp old_summary location src_fn t
2067 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2069 Right t -> check_timestamp old_summary location src_fn t
2070 Left e | isDoesNotExistError e -> find_it
2071 | otherwise -> liftIO $ ioError e
2073 | otherwise = find_it
2075 dflags = hsc_dflags hsc_env
2077 hsc_src = if is_boot then HsBootFile else HsSrcFile
2079 check_timestamp old_summary location src_fn src_timestamp
2080 | ms_hs_date old_summary == src_timestamp = do
2081 -- update the object-file timestamp
2082 obj_timestamp <- liftIO $
2083 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2084 || obj_allowed -- bug #1205
2085 then getObjTimestamp location is_boot
2087 return (Just old_summary{ ms_obj_date = obj_timestamp })
2089 -- source changed: re-summarise.
2090 new_summary location (ms_mod old_summary) src_fn src_timestamp
2093 -- Don't use the Finder's cache this time. If the module was
2094 -- previously a package module, it may have now appeared on the
2095 -- search path, so we want to consider it to be a home module. If
2096 -- the module was previously a home module, it may have moved.
2097 liftIO $ uncacheModule hsc_env wanted_mod
2098 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2101 | isJust (ml_hs_file location) ->
2103 just_found location mod
2105 -- Drop external-pkg
2106 ASSERT(modulePackageId mod /= thisPackage dflags)
2109 err -> liftIO $ noModError dflags loc wanted_mod err
2112 just_found location mod = do
2113 -- Adjust location to point to the hs-boot source file,
2114 -- hi file, object file, when is_boot says so
2115 let location' | is_boot = addBootSuffixLocn location
2116 | otherwise = location
2117 src_fn = expectJust "summarise2" (ml_hs_file location')
2119 -- Check that it exists
2120 -- It might have been deleted since the Finder last found it
2121 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2123 Nothing -> noHsFileErr loc src_fn
2124 Just t -> new_summary location' mod src_fn t
2127 new_summary location mod src_fn src_timestamp
2129 -- Preprocess the source file and get its imports
2130 -- The dflags' contains the OPTIONS pragmas
2131 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2132 (srcimps, the_imps, L mod_loc mod_name) <- liftIO $ getImports dflags' buf hspp_fn src_fn
2134 when (mod_name /= wanted_mod) $
2135 throwErrMsg $ mkPlainErrMsg mod_loc $
2136 text "File name does not match module name:"
2137 $$ text "Saw:" <+> quotes (ppr mod_name)
2138 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2140 -- Find the object timestamp, and return the summary
2141 obj_timestamp <- liftIO $
2142 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2143 || obj_allowed -- bug #1205
2144 then getObjTimestamp location is_boot
2147 return (Just (ModSummary { ms_mod = mod,
2148 ms_hsc_src = hsc_src,
2149 ms_location = location,
2150 ms_hspp_file = hspp_fn,
2151 ms_hspp_opts = dflags',
2152 ms_hspp_buf = Just buf,
2153 ms_srcimps = srcimps,
2155 ms_hs_date = src_timestamp,
2156 ms_obj_date = obj_timestamp }))
2159 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2160 getObjTimestamp location is_boot
2161 = if is_boot then return Nothing
2162 else modificationTimeIfExists (ml_obj_file location)
2165 preprocessFile :: GhcMonad m =>
2168 -> Maybe Phase -- ^ Starting phase
2169 -> Maybe (StringBuffer,ClockTime)
2170 -> m (DynFlags, FilePath, StringBuffer)
2171 preprocessFile hsc_env src_fn mb_phase Nothing
2173 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2174 buf <- liftIO $ hGetStringBuffer hspp_fn
2175 return (dflags', hspp_fn, buf)
2177 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2179 let dflags = hsc_dflags hsc_env
2180 -- case we bypass the preprocessing stage?
2182 local_opts = getOptions dflags buf src_fn
2184 (dflags', leftovers, warns)
2185 <- parseDynamicFlags dflags local_opts
2186 liftIO $ checkProcessArgsResult leftovers -- XXX: throws exceptions
2187 liftIO $ handleFlagWarnings dflags' warns -- XXX: throws exceptions
2191 | Just (Unlit _) <- mb_phase = True
2192 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2193 -- note: local_opts is only required if there's no Unlit phase
2194 | dopt Opt_Cpp dflags' = True
2195 | dopt Opt_Pp dflags' = True
2198 when needs_preprocessing $
2199 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2201 return (dflags', src_fn, buf)
2204 -----------------------------------------------------------------------------
2206 -----------------------------------------------------------------------------
2208 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2209 -- ToDo: we don't have a proper line number for this error
2210 noModError dflags loc wanted_mod err
2211 = throwErrMsg $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2213 noHsFileErr :: SrcSpan -> String -> a
2214 noHsFileErr loc path
2215 = throwErrMsg $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2217 packageModErr :: ModuleName -> a
2219 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2220 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2222 multiRootsErr :: [ModSummary] -> IO ()
2223 multiRootsErr [] = panic "multiRootsErr"
2224 multiRootsErr summs@(summ1:_)
2225 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2226 text "module" <+> quotes (ppr mod) <+>
2227 text "is defined in multiple files:" <+>
2228 sep (map text files)
2231 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2233 cyclicModuleErr :: [ModSummary] -> SDoc
2235 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2236 2 (vcat (map show_one ms))
2238 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2239 nest 2 $ ptext (sLit "imports:") <+>
2240 (pp_imps HsBootFile (ms_srcimps ms)
2241 $$ pp_imps HsSrcFile (ms_imps ms))]
2242 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2243 pp_imps src mods = fsep (map (show_mod src) mods)
2246 -- | Inform GHC that the working directory has changed. GHC will flush
2247 -- its cache of module locations, since it may no longer be valid.
2248 -- Note: if you change the working directory, you should also unload
2249 -- the current program (set targets to empty, followed by load).
2250 workingDirectoryChanged :: GhcMonad m => m ()
2251 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2253 -- -----------------------------------------------------------------------------
2254 -- inspecting the session
2256 -- | Get the module dependency graph.
2257 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2258 getModuleGraph = liftM hsc_mod_graph getSession
2260 -- | Return @True@ <==> module is loaded.
2261 isLoaded :: GhcMonad m => ModuleName -> m Bool
2262 isLoaded m = withSession $ \hsc_env ->
2263 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2265 -- | Return the bindings for the current interactive session.
2266 getBindings :: GhcMonad m => m [TyThing]
2267 getBindings = withSession $ \hsc_env ->
2268 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2269 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2271 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2272 filtered = foldr f (const []) tmp_ids emptyUniqSet
2274 | uniq `elementOfUniqSet` set = rest set
2275 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2276 where uniq = getUnique (nameOccName (idName id))
2280 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2281 getPrintUnqual = withSession $ \hsc_env ->
2282 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2284 -- | Container for information about a 'Module'.
2285 data ModuleInfo = ModuleInfo {
2286 minf_type_env :: TypeEnv,
2287 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2288 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2289 minf_instances :: [Instance]
2291 ,minf_modBreaks :: ModBreaks
2293 -- ToDo: this should really contain the ModIface too
2295 -- We don't want HomeModInfo here, because a ModuleInfo applies
2296 -- to package modules too.
2298 -- | Request information about a loaded 'Module'
2299 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2300 getModuleInfo mdl = withSession $ \hsc_env -> do
2301 let mg = hsc_mod_graph hsc_env
2302 if mdl `elem` map ms_mod mg
2303 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2305 {- if isHomeModule (hsc_dflags hsc_env) mdl
2307 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2308 -- getPackageModuleInfo will attempt to find the interface, so
2309 -- we don't want to call it for a home module, just in case there
2310 -- was a problem loading the module and the interface doesn't
2311 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2313 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2315 getPackageModuleInfo hsc_env mdl = do
2316 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2318 Nothing -> return Nothing
2320 eps <- readIORef (hsc_EPS hsc_env)
2322 names = availsToNameSet avails
2324 tys = [ ty | name <- concatMap availNames avails,
2325 Just ty <- [lookupTypeEnv pte name] ]
2327 return (Just (ModuleInfo {
2328 minf_type_env = mkTypeEnv tys,
2329 minf_exports = names,
2330 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2331 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2332 minf_modBreaks = emptyModBreaks
2335 getPackageModuleInfo _hsc_env _mdl = do
2336 -- bogusly different for non-GHCI (ToDo)
2340 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2341 getHomeModuleInfo hsc_env mdl =
2342 case lookupUFM (hsc_HPT hsc_env) mdl of
2343 Nothing -> return Nothing
2345 let details = hm_details hmi
2346 return (Just (ModuleInfo {
2347 minf_type_env = md_types details,
2348 minf_exports = availsToNameSet (md_exports details),
2349 minf_rdr_env = mi_globals $! hm_iface hmi,
2350 minf_instances = md_insts details
2352 ,minf_modBreaks = getModBreaks hmi
2356 -- | The list of top-level entities defined in a module
2357 modInfoTyThings :: ModuleInfo -> [TyThing]
2358 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2360 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2361 modInfoTopLevelScope minf
2362 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2364 modInfoExports :: ModuleInfo -> [Name]
2365 modInfoExports minf = nameSetToList $! minf_exports minf
2367 -- | Returns the instances defined by the specified module.
2368 -- Warning: currently unimplemented for package modules.
2369 modInfoInstances :: ModuleInfo -> [Instance]
2370 modInfoInstances = minf_instances
2372 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2373 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2375 mkPrintUnqualifiedForModule :: GhcMonad m =>
2377 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2378 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2379 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2381 modInfoLookupName :: GhcMonad m =>
2383 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2384 modInfoLookupName minf name = withSession $ \hsc_env -> do
2385 case lookupTypeEnv (minf_type_env minf) name of
2386 Just tyThing -> return (Just tyThing)
2388 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2389 return $! lookupType (hsc_dflags hsc_env)
2390 (hsc_HPT hsc_env) (eps_PTE eps) name
2393 modInfoModBreaks :: ModuleInfo -> ModBreaks
2394 modInfoModBreaks = minf_modBreaks
2397 isDictonaryId :: Id -> Bool
2399 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2401 -- | Looks up a global name: that is, any top-level name in any
2402 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2403 -- the interactive context, and therefore does not require a preceding
2405 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2406 lookupGlobalName name = withSession $ \hsc_env -> do
2407 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2408 return $! lookupType (hsc_dflags hsc_env)
2409 (hsc_HPT hsc_env) (eps_PTE eps) name
2412 -- | get the GlobalRdrEnv for a session
2413 getGRE :: GhcMonad m => m GlobalRdrEnv
2414 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2417 -- -----------------------------------------------------------------------------
2418 -- Misc exported utils
2420 dataConType :: DataCon -> Type
2421 dataConType dc = idType (dataConWrapId dc)
2423 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2424 pprParenSymName :: NamedThing a => a -> SDoc
2425 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2427 -- ----------------------------------------------------------------------------
2432 -- - Data and Typeable instances for HsSyn.
2434 -- ToDo: check for small transformations that happen to the syntax in
2435 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2437 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2438 -- to get from TyCons, Ids etc. to TH syntax (reify).
2440 -- :browse will use either lm_toplev or inspect lm_interface, depending
2441 -- on whether the module is interpreted or not.
2443 -- This is for reconstructing refactored source code
2444 -- Calls the lexer repeatedly.
2445 -- ToDo: add comment tokens to token stream
2446 getTokenStream :: Session -> Module -> IO [Located Token]
2449 -- -----------------------------------------------------------------------------
2450 -- Interactive evaluation
2452 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2453 -- filesystem and package database to find the corresponding 'Module',
2454 -- using the algorithm that is used for an @import@ declaration.
2455 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2456 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2458 dflags = hsc_dflags hsc_env
2459 hpt = hsc_HPT hsc_env
2460 this_pkg = thisPackage dflags
2462 case lookupUFM hpt mod_name of
2463 Just mod_info -> return (mi_module (hm_iface mod_info))
2464 _not_a_home_module -> do
2465 res <- findImportedModule hsc_env mod_name maybe_pkg
2467 Found _ m | modulePackageId m /= this_pkg -> return m
2468 | otherwise -> ghcError (CmdLineError (showSDoc $
2469 text "module" <+> quotes (ppr (moduleName m)) <+>
2470 text "is not loaded"))
2471 err -> let msg = cannotFindModule dflags mod_name err in
2472 ghcError (CmdLineError (showSDoc msg))
2475 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2476 getHistorySpan h = withSession $ \hsc_env ->
2477 return$ InteractiveEval.getHistorySpan hsc_env h
2479 obtainTerm :: GhcMonad m => Bool -> Id -> m Term
2480 obtainTerm force id = withSession $ \hsc_env ->
2481 liftIO $ InteractiveEval.obtainTerm hsc_env force id
2483 obtainTerm1 :: GhcMonad m => Bool -> Maybe Type -> a -> m Term
2484 obtainTerm1 force mb_ty a =
2485 withSession $ \hsc_env ->
2486 liftIO $ InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2488 obtainTermB :: GhcMonad m => Int -> Bool -> Id -> m Term
2489 obtainTermB bound force id =
2490 withSession $ \hsc_env ->
2491 liftIO $ InteractiveEval.obtainTermB hsc_env bound force id