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,
20 handleSourceError, defaultCallbacks, GhcApiCallbacks(..),
23 -- * Flags and settings
24 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
25 GhcMode(..), GhcLink(..), defaultObjectTarget,
32 Target(..), TargetId(..), Phase,
39 -- * Extending the program scope
42 extendGlobalTypeScope,
45 -- * Loading\/compiling the program
47 load, loadWithLogger, LoadHowMuch(..),
48 SuccessFlag(..), succeeded, failed,
49 defaultWarnErrLogger, WarnErrLogger,
50 workingDirectoryChanged,
51 parseModule, typecheckModule, desugarModule, loadModule,
52 ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
53 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
54 TypecheckedMod, ParsedMod,
55 moduleInfo, renamedSource, typecheckedSource,
56 parsedSource, coreModule,
57 compileToCoreModule, compileToCoreSimplified,
61 -- * Inspecting the module structure of the program
62 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
67 -- * Inspecting modules
74 modInfoIsExportedName,
78 mkPrintUnqualifiedForModule,
80 -- * Querying the environment
84 PrintUnqualified, alwaysQualify,
86 -- * Interactive evaluation
87 getBindings, getPrintUnqual,
91 setContext, getContext,
101 runStmt, SingleStep(..),
103 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
104 resumeHistory, resumeHistoryIx),
105 History(historyBreakInfo, historyEnclosingDecl),
106 GHC.getHistorySpan, getHistoryModule,
109 InteractiveEval.back,
110 InteractiveEval.forward,
113 InteractiveEval.compileExpr, HValue, dynCompileExpr,
115 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
117 ModBreaks(..), BreakIndex,
118 BreakInfo(breakInfo_number, breakInfo_module),
119 BreakArray, setBreakOn, setBreakOff, getBreak,
122 -- * Abstract syntax elements
128 Module, mkModule, pprModule, moduleName, modulePackageId,
129 ModuleName, mkModuleName, moduleNameString,
133 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
135 RdrName(Qual,Unqual),
139 isImplicitId, isDeadBinder,
140 isExportedId, isLocalId, isGlobalId,
142 isPrimOpId, isFCallId, isClassOpId_maybe,
143 isDataConWorkId, idDataCon,
144 isBottomingId, isDictonaryId,
145 recordSelectorFieldLabel,
147 -- ** Type constructors
149 tyConTyVars, tyConDataCons, tyConArity,
150 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
152 synTyConDefn, synTyConType, synTyConResKind,
158 -- ** Data constructors
160 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
161 dataConIsInfix, isVanillaDataCon,
163 StrictnessMark(..), isMarkedStrict,
167 classMethods, classSCTheta, classTvsFds,
172 instanceDFunId, pprInstance, pprInstanceHdr,
174 -- ** Types and Kinds
175 Type, splitForAllTys, funResultTy,
176 pprParendType, pprTypeApp,
179 ThetaType, pprThetaArrow,
185 module HsSyn, -- ToDo: remove extraneous bits
189 defaultFixity, maxPrecedence,
193 -- ** Source locations
195 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
196 srcLocFile, srcLocLine, srcLocCol,
198 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
199 srcSpanStart, srcSpanEnd,
201 srcSpanStartLine, srcSpanEndLine,
202 srcSpanStartCol, srcSpanEndCol,
207 -- *** Constructing Located
208 noLoc, mkGeneralLocated,
210 -- *** Deconstructing Located
213 -- *** Combining and comparing Located values
214 eqLocated, cmpLocated, combineLocs, addCLoc,
215 leftmost_smallest, leftmost_largest, rightmost,
219 GhcException(..), showGhcException,
221 -- * Token stream manipulations
223 getTokenStream, getRichTokenStream,
224 showRichTokenStream, addSourceToTokens,
234 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
235 * what StaticFlags should we expose, if any?
238 #include "HsVersions.h"
241 import qualified Linker
242 import Linker ( HValue )
245 import InteractiveEval
250 import TcRnTypes hiding (LIE)
251 import TcRnMonad ( initIfaceCheck )
255 import qualified HsSyn -- hack as we want to reexport the whole module
256 import HsSyn hiding ((<.>))
257 import Type hiding (typeKind)
258 import TcType hiding (typeKind)
261 import TysPrim ( alphaTyVars )
266 import Name hiding ( varName )
267 -- import OccName ( parenSymOcc )
268 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
270 import FamInstEnv ( emptyFamInstEnv )
274 import DriverPipeline
275 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
281 import StaticFlagParser
282 import qualified StaticFlags
283 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
288 import qualified UniqFM as UFM
292 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
296 import StringBuffer ( StringBuffer, hGetStringBuffer, nextChar )
299 import Maybes ( expectJust, mapCatMaybes )
303 import Control.Concurrent
304 import System.Directory ( getModificationTime, doesFileExist,
305 getCurrentDirectory )
308 import qualified Data.List as List
309 import Data.Typeable ( Typeable )
310 import Data.Word ( Word8 )
312 import System.Exit ( exitWith, ExitCode(..) )
313 import System.Time ( ClockTime, getClockTime )
316 import System.FilePath
318 import System.IO.Error ( try, isDoesNotExistError )
319 import Prelude hiding (init)
322 -- -----------------------------------------------------------------------------
323 -- Exception handlers
325 -- | Install some default exception handlers and run the inner computation.
326 -- Unless you want to handle exceptions yourself, you should wrap this around
327 -- the top level of your program. The default handlers output the error
328 -- message(s) to stderr and exit cleanly.
329 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
330 defaultErrorHandler dflags inner =
331 -- top-level exception handler: any unrecognised exception is a compiler bug.
332 ghandle (\exception -> liftIO $ do
334 case fromException exception of
335 -- an IO exception probably isn't our fault, so don't panic
336 Just (ioe :: IOException) ->
337 fatalErrorMsg dflags (text (show ioe))
338 _ -> case fromException exception of
339 Just StackOverflow ->
340 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
341 _ -> case fromException exception of
342 Just (ex :: ExitCode) -> throw ex
345 (text (show (Panic (show exception))))
346 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 defaultCallbacks dflags
469 defaultCallbacks :: GhcApiCallbacks
472 reportModuleCompilationResult =
473 \_ mb_err -> defaultWarnErrLogger mb_err
476 -- -----------------------------------------------------------------------------
479 -- | Grabs the DynFlags from the Session
480 getSessionDynFlags :: GhcMonad m => m DynFlags
481 getSessionDynFlags = withSession (return . hsc_dflags)
483 -- | Updates the DynFlags in a Session. This also reads
484 -- the package database (unless it has already been read),
485 -- and prepares the compilers knowledge about packages. It
486 -- can be called again to load new packages: just add new
487 -- package flags to (packageFlags dflags).
489 -- Returns a list of new packages that may need to be linked in using
490 -- the dynamic linker (see 'linkPackages') as a result of new package
491 -- flags. If you are not doing linking or doing static linking, you
492 -- can ignore the list of packages returned.
494 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
495 setSessionDynFlags dflags = do
496 (dflags', preload) <- liftIO $ initPackages dflags
497 modifySession (\h -> h{ hsc_dflags = dflags' })
500 -- | If there is no -o option, guess the name of target executable
501 -- by using top-level source file name as a base.
502 guessOutputFile :: GhcMonad m => m ()
503 guessOutputFile = modifySession $ \env ->
504 let dflags = hsc_dflags env
505 mod_graph = hsc_mod_graph env
506 mainModuleSrcPath :: Maybe String
507 mainModuleSrcPath = do
508 let isMain = (== mainModIs dflags) . ms_mod
509 [ms] <- return (filter isMain mod_graph)
510 ml_hs_file (ms_location ms)
511 name = fmap dropExtension mainModuleSrcPath
513 #if defined(mingw32_HOST_OS)
514 -- we must add the .exe extention unconditionally here, otherwise
515 -- when name has an extension of its own, the .exe extension will
516 -- not be added by DriverPipeline.exeFileName. See #2248
517 name_exe = fmap (<.> "exe") name
522 case outputFile dflags of
524 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
526 -- -----------------------------------------------------------------------------
529 -- ToDo: think about relative vs. absolute file paths. And what
530 -- happens when the current directory changes.
532 -- | Sets the targets for this session. Each target may be a module name
533 -- or a filename. The targets correspond to the set of root modules for
534 -- the program\/library. Unloading the current program is achieved by
535 -- setting the current set of targets to be empty, followed by 'load'.
536 setTargets :: GhcMonad m => [Target] -> m ()
537 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
539 -- | Returns the current set of targets
540 getTargets :: GhcMonad m => m [Target]
541 getTargets = withSession (return . hsc_targets)
543 -- | Add another target.
544 addTarget :: GhcMonad m => Target -> m ()
546 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
549 removeTarget :: GhcMonad m => TargetId -> m ()
550 removeTarget target_id
551 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
553 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
555 -- | Attempts to guess what Target a string refers to. This function
556 -- implements the @--make@/GHCi command-line syntax for filenames:
558 -- - if the string looks like a Haskell source filename, then interpret it
561 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
564 -- - otherwise interpret the string as a module name
566 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
567 guessTarget str (Just phase)
568 = return (Target (TargetFile str (Just phase)) True Nothing)
569 guessTarget str Nothing
570 | isHaskellSrcFilename file
571 = return (target (TargetFile file Nothing))
573 = do exists <- liftIO $ doesFileExist hs_file
575 then return (target (TargetFile hs_file Nothing))
577 exists <- liftIO $ doesFileExist lhs_file
579 then return (target (TargetFile lhs_file Nothing))
581 if looksLikeModuleName file
582 then return (target (TargetModule (mkModuleName file)))
585 (ProgramError (showSDoc $
586 text "target" <+> quotes (text file) <+>
587 text "is not a module name or a source file"))
590 | '*':rest <- str = (rest, False)
591 | otherwise = (str, True)
593 hs_file = file <.> "hs"
594 lhs_file = file <.> "lhs"
596 target tid = Target tid obj_allowed Nothing
598 -- -----------------------------------------------------------------------------
599 -- Extending the program scope
601 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
602 extendGlobalRdrScope rdrElts
603 = modifySession $ \hscEnv ->
604 let global_rdr = hsc_global_rdr_env hscEnv
605 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
607 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
608 setGlobalRdrScope rdrElts
609 = modifySession $ \hscEnv ->
610 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
612 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
613 extendGlobalTypeScope ids
614 = modifySession $ \hscEnv ->
615 let global_type = hsc_global_type_env hscEnv
616 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
618 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
619 setGlobalTypeScope ids
620 = modifySession $ \hscEnv ->
621 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
623 -- -----------------------------------------------------------------------------
624 -- Loading the program
626 -- | Perform a dependency analysis starting from the current targets
627 -- and update the session with the new module graph.
629 -- Dependency analysis entails parsing the @import@ directives and may
630 -- therefore require running certain preprocessors.
632 -- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
633 -- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
634 -- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want to
635 -- changes to the 'DynFlags' to take effect you need to call this function
638 depanal :: GhcMonad m =>
639 [ModuleName] -- ^ excluded modules
640 -> Bool -- ^ allow duplicate roots
642 depanal excluded_mods allow_dup_roots = do
643 hsc_env <- getSession
645 dflags = hsc_dflags hsc_env
646 targets = hsc_targets hsc_env
647 old_graph = hsc_mod_graph hsc_env
649 liftIO $ showPass dflags "Chasing dependencies"
650 liftIO $ debugTraceMsg dflags 2 (hcat [
651 text "Chasing modules from: ",
652 hcat (punctuate comma (map pprTarget targets))])
654 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
655 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
658 -- | Describes which modules of the module graph need to be loaded.
661 -- ^ Load all targets and its dependencies.
662 | LoadUpTo ModuleName
663 -- ^ Load only the given module and its dependencies.
664 | LoadDependenciesOf ModuleName
665 -- ^ Load only the dependencies of the given module, but not the module
668 -- | Try to load the program. See 'LoadHowMuch' for the different modes.
670 -- This function implements the core of GHC's @--make@ mode. It preprocesses,
671 -- compiles and loads the specified modules, avoiding re-compilation wherever
672 -- possible. Depending on the target (see 'DynFlags.hscTarget') compilating
673 -- and loading may result in files being created on disk.
675 -- Calls the 'reportModuleCompilationResult' callback after each compiling
676 -- each module, whether successful or not.
678 -- Throw a 'SourceError' if errors are encountered before the actual
679 -- compilation starts (e.g., during dependency analysis). All other errors
680 -- are reported using the callback.
682 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
684 mod_graph <- depanal [] False
685 load2 how_much mod_graph
687 -- | A function called to log warnings and errors.
688 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
690 defaultWarnErrLogger :: WarnErrLogger
691 defaultWarnErrLogger Nothing = printWarnings
692 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
694 -- | Try to load the program. If a Module is supplied, then just
695 -- attempt to load up to this target. If no Module is supplied,
696 -- then try to load all targets.
698 -- The first argument is a function that is called after compiling each
699 -- module to print wanrings and errors.
701 -- While compiling a module, all 'SourceError's are caught and passed to the
702 -- logger, however, this function may still throw a 'SourceError' if
703 -- dependency analysis failed (e.g., due to a parse error).
705 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
706 loadWithLogger logger how_much = do
707 -- Dependency analysis first. Note that this fixes the module graph:
708 -- even if we don't get a fully successful upsweep, the full module
709 -- graph is still retained in the Session. We can tell which modules
710 -- were successfully loaded by inspecting the Session's HPT.
711 withLocalCallbacks (\cbs -> cbs { reportModuleCompilationResult =
715 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary]
717 load2 how_much mod_graph = do
719 hsc_env <- getSession
721 let hpt1 = hsc_HPT hsc_env
722 let dflags = hsc_dflags hsc_env
724 -- The "bad" boot modules are the ones for which we have
725 -- B.hs-boot in the module graph, but no B.hs
726 -- The downsweep should have ensured this does not happen
728 let all_home_mods = [ms_mod_name s
729 | s <- mod_graph, not (isBootSummary s)]
730 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
731 not (ms_mod_name s `elem` all_home_mods)]
732 ASSERT( null bad_boot_mods ) return ()
734 -- check that the module given in HowMuch actually exists, otherwise
735 -- topSortModuleGraph will bomb later.
736 let checkHowMuch (LoadUpTo m) = checkMod m
737 checkHowMuch (LoadDependenciesOf m) = checkMod m
741 | m `elem` all_home_mods = and_then
743 liftIO $ errorMsg dflags (text "no such module:" <+>
747 checkHowMuch how_much $ do
749 -- mg2_with_srcimps drops the hi-boot nodes, returning a
750 -- graph with cycles. Among other things, it is used for
751 -- backing out partially complete cycles following a failed
752 -- upsweep, and for removing from hpt all the modules
753 -- not in strict downwards closure, during calls to compile.
754 let mg2_with_srcimps :: [SCC ModSummary]
755 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
757 -- If we can determine that any of the {-# SOURCE #-} imports
758 -- are definitely unnecessary, then emit a warning.
759 warnUnnecessarySourceImports mg2_with_srcimps
762 -- check the stability property for each module.
763 stable_mods@(stable_obj,stable_bco)
764 = checkStability hpt1 mg2_with_srcimps all_home_mods
766 -- prune bits of the HPT which are definitely redundant now,
768 pruned_hpt = pruneHomePackageTable hpt1
769 (flattenSCCs mg2_with_srcimps)
772 _ <- liftIO $ evaluate pruned_hpt
774 -- before we unload anything, make sure we don't leave an old
775 -- interactive context around pointing to dead bindings. Also,
776 -- write the pruned HPT to allow the old HPT to be GC'd.
777 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
778 hsc_HPT = pruned_hpt }
780 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
781 text "Stable BCO:" <+> ppr stable_bco)
783 -- Unload any modules which are going to be re-linked this time around.
784 let stable_linkables = [ linkable
785 | m <- stable_obj++stable_bco,
786 Just hmi <- [lookupUFM pruned_hpt m],
787 Just linkable <- [hm_linkable hmi] ]
788 liftIO $ unload hsc_env stable_linkables
790 -- We could at this point detect cycles which aren't broken by
791 -- a source-import, and complain immediately, but it seems better
792 -- to let upsweep_mods do this, so at least some useful work gets
793 -- done before the upsweep is abandoned.
794 --hPutStrLn stderr "after tsort:\n"
795 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
797 -- Now do the upsweep, calling compile for each module in
798 -- turn. Final result is version 3 of everything.
800 -- Topologically sort the module graph, this time including hi-boot
801 -- nodes, and possibly just including the portion of the graph
802 -- reachable from the module specified in the 2nd argument to load.
803 -- This graph should be cycle-free.
804 -- If we're restricting the upsweep to a portion of the graph, we
805 -- also want to retain everything that is still stable.
806 let full_mg :: [SCC ModSummary]
807 full_mg = topSortModuleGraph False mod_graph Nothing
809 maybe_top_mod = case how_much of
811 LoadDependenciesOf m -> Just m
814 partial_mg0 :: [SCC ModSummary]
815 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
817 -- LoadDependenciesOf m: we want the upsweep to stop just
818 -- short of the specified module (unless the specified module
821 | LoadDependenciesOf _mod <- how_much
822 = ASSERT( case last partial_mg0 of
823 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
824 List.init partial_mg0
830 | AcyclicSCC ms <- full_mg,
831 ms_mod_name ms `elem` stable_obj++stable_bco,
832 ms_mod_name ms `notElem` [ ms_mod_name ms' |
833 AcyclicSCC ms' <- partial_mg ] ]
835 mg = stable_mg ++ partial_mg
837 -- clean up between compilations
838 let cleanup = cleanTempFilesExcept dflags
839 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
841 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
843 (upsweep_ok, hsc_env1, modsUpswept)
844 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
845 pruned_hpt stable_mods cleanup mg
847 -- Make modsDone be the summaries for each home module now
848 -- available; this should equal the domain of hpt3.
849 -- Get in in a roughly top .. bottom order (hence reverse).
851 let modsDone = reverse modsUpswept
853 -- Try and do linking in some form, depending on whether the
854 -- upsweep was completely or only partially successful.
856 if succeeded upsweep_ok
859 -- Easy; just relink it all.
860 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
862 -- Clean up after ourselves
863 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
865 -- Issue a warning for the confusing case where the user
866 -- said '-o foo' but we're not going to do any linking.
867 -- We attempt linking if either (a) one of the modules is
868 -- called Main, or (b) the user said -no-hs-main, indicating
869 -- that main() is going to come from somewhere else.
871 let ofile = outputFile dflags
872 let no_hs_main = dopt Opt_NoHsMain dflags
874 main_mod = mainModIs dflags
875 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
876 do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib
878 when (ghcLink dflags == LinkBinary
879 && isJust ofile && not do_linking) $
880 liftIO $ debugTraceMsg dflags 1 $
881 text ("Warning: output was redirected with -o, " ++
882 "but no output will be generated\n" ++
883 "because there is no " ++
884 moduleNameString (moduleName main_mod) ++ " module.")
886 -- link everything together
887 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
889 loadFinish Succeeded linkresult hsc_env1
892 -- Tricky. We need to back out the effects of compiling any
893 -- half-done cycles, both so as to clean up the top level envs
894 -- and to avoid telling the interactive linker to link them.
895 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
898 = map ms_mod modsDone
899 let mods_to_zap_names
900 = findPartiallyCompletedCycles modsDone_names
903 = filter ((`notElem` mods_to_zap_names).ms_mod)
906 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
909 -- Clean up after ourselves
910 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
912 -- there should be no Nothings where linkables should be, now
913 ASSERT(all (isJust.hm_linkable)
914 (eltsUFM (hsc_HPT hsc_env))) do
916 -- Link everything together
917 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
919 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
920 loadFinish Failed linkresult hsc_env4
922 -- Finish up after a load.
924 -- If the link failed, unload everything and return.
925 loadFinish :: GhcMonad m =>
926 SuccessFlag -> SuccessFlag -> HscEnv
928 loadFinish _all_ok Failed hsc_env
929 = do liftIO $ unload hsc_env []
930 modifySession $ \_ -> discardProg hsc_env
933 -- Empty the interactive context and set the module context to the topmost
934 -- newly loaded module, or the Prelude if none were loaded.
935 loadFinish all_ok Succeeded hsc_env
936 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
940 -- Forget the current program, but retain the persistent info in HscEnv
941 discardProg :: HscEnv -> HscEnv
943 = hsc_env { hsc_mod_graph = emptyMG,
944 hsc_IC = emptyInteractiveContext,
945 hsc_HPT = emptyHomePackageTable }
947 -- used to fish out the preprocess output files for the purposes of
948 -- cleaning up. The preprocessed file *might* be the same as the
949 -- source file, but that doesn't do any harm.
950 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
951 ppFilesFromSummaries summaries = map ms_hspp_file summaries
953 -- -----------------------------------------------------------------------------
955 class ParsedMod m where
956 modSummary :: m -> ModSummary
957 parsedSource :: m -> ParsedSource
959 class ParsedMod m => TypecheckedMod m where
960 renamedSource :: m -> Maybe RenamedSource
961 typecheckedSource :: m -> TypecheckedSource
962 moduleInfo :: m -> ModuleInfo
963 tm_internals :: m -> (TcGblEnv, ModDetails)
964 -- ToDo: improvements that could be made here:
965 -- if the module succeeded renaming but not typechecking,
966 -- we can still get back the GlobalRdrEnv and exports, so
967 -- perhaps the ModuleInfo should be split up into separate
970 class TypecheckedMod m => DesugaredMod m where
971 coreModule :: m -> ModGuts
973 -- | The result of successful parsing.
975 ParsedModule { pm_mod_summary :: ModSummary
976 , pm_parsed_source :: ParsedSource }
978 instance ParsedMod ParsedModule where
979 modSummary m = pm_mod_summary m
980 parsedSource m = pm_parsed_source m
982 -- | The result of successful typechecking. It also contains the parser
984 data TypecheckedModule =
985 TypecheckedModule { tm_parsed_module :: ParsedModule
986 , tm_renamed_source :: Maybe RenamedSource
987 , tm_typechecked_source :: TypecheckedSource
988 , tm_checked_module_info :: ModuleInfo
989 , tm_internals_ :: (TcGblEnv, ModDetails)
992 instance ParsedMod TypecheckedModule where
993 modSummary m = modSummary (tm_parsed_module m)
994 parsedSource m = parsedSource (tm_parsed_module m)
996 instance TypecheckedMod TypecheckedModule where
997 renamedSource m = tm_renamed_source m
998 typecheckedSource m = tm_typechecked_source m
999 moduleInfo m = tm_checked_module_info m
1000 tm_internals m = tm_internals_ m
1002 -- | The result of successful desugaring (i.e., translation to core). Also
1003 -- contains all the information of a typechecked module.
1004 data DesugaredModule =
1005 DesugaredModule { dm_typechecked_module :: TypecheckedModule
1006 , dm_core_module :: ModGuts
1009 instance ParsedMod DesugaredModule where
1010 modSummary m = modSummary (dm_typechecked_module m)
1011 parsedSource m = parsedSource (dm_typechecked_module m)
1013 instance TypecheckedMod DesugaredModule where
1014 renamedSource m = renamedSource (dm_typechecked_module m)
1015 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
1016 moduleInfo m = moduleInfo (dm_typechecked_module m)
1017 tm_internals m = tm_internals_ (dm_typechecked_module m)
1019 instance DesugaredMod DesugaredModule where
1020 coreModule m = dm_core_module m
1022 type ParsedSource = Located (HsModule RdrName)
1023 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
1025 type TypecheckedSource = LHsBinds Id
1028 -- - things that aren't in the output of the typechecker right now:
1029 -- - the export list
1031 -- - type signatures
1032 -- - type/data/newtype declarations
1033 -- - class declarations
1035 -- - extra things in the typechecker's output:
1036 -- - default methods are turned into top-level decls.
1037 -- - dictionary bindings
1039 -- | Return the 'ModSummary' of a module with the given name.
1041 -- The module must be part of the module graph (see 'hsc_mod_graph' and
1042 -- 'ModuleGraph'). If this is not the case, this function will throw a
1045 -- This function ignores boot modules and requires that there is only one
1046 -- non-boot module with the given name.
1047 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1048 getModSummary mod = do
1049 mg <- liftM hsc_mod_graph getSession
1050 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
1051 [] -> throw $ mkApiErr (text "Module not part of module graph")
1053 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
1055 -- | Parse a module.
1057 -- Throws a 'SourceError' on parse error.
1058 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
1060 rdr_module <- withTempSession
1061 (\e -> e { hsc_dflags = ms_hspp_opts ms }) $
1063 return (ParsedModule ms rdr_module)
1065 -- | Typecheck and rename a parsed module.
1067 -- Throws a 'SourceError' if either fails.
1068 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1069 typecheckModule pmod = do
1070 let ms = modSummary pmod
1071 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1072 (tc_gbl_env, rn_info)
1073 <- hscTypecheckRename ms (parsedSource pmod)
1074 details <- makeSimpleDetails tc_gbl_env
1077 tm_internals_ = (tc_gbl_env, details),
1078 tm_parsed_module = pmod,
1079 tm_renamed_source = rn_info,
1080 tm_typechecked_source = tcg_binds tc_gbl_env,
1081 tm_checked_module_info =
1083 minf_type_env = md_types details,
1084 minf_exports = availsToNameSet $ md_exports details,
1085 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1086 minf_instances = md_insts details
1088 ,minf_modBreaks = emptyModBreaks
1092 -- | Desugar a typechecked module.
1093 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1094 desugarModule tcm = do
1095 let ms = modSummary tcm
1096 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1097 let (tcg, _) = tm_internals tcm
1098 guts <- hscDesugar ms tcg
1101 dm_typechecked_module = tcm,
1102 dm_core_module = guts
1105 -- | Load a module. Input doesn't need to be desugared.
1107 -- A module must be loaded before dependent modules can be typechecked. This
1108 -- always includes generating a 'ModIface' and, depending on the
1109 -- 'DynFlags.hscTarget', may also include code generation.
1111 -- This function will always cause recompilation and will always overwrite
1112 -- previous compilation results (potentially files on disk).
1114 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1116 let ms = modSummary tcm
1117 let mod = ms_mod_name ms
1118 let (tcg, _details) = tm_internals tcm
1120 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1122 let compilerBackend comp env ms' _ _mb_old_iface _ =
1123 withTempSession (\_ -> env) $
1124 hscBackend comp tcg ms'
1126 hsc_env <- getSession
1128 <- compile' (compilerBackend hscNothingCompiler
1129 ,compilerBackend hscInteractiveCompiler
1130 ,compilerBackend hscBatchCompiler)
1131 hsc_env ms 1 1 Nothing Nothing
1132 -- compile' shouldn't change the environment
1133 return $ addToUFM (hsc_HPT hsc_env) mod mod_info
1134 modifySession $ \e -> e{ hsc_HPT = hpt_new }
1137 -- | This is the way to get access to the Core bindings corresponding
1138 -- to a module. 'compileToCore' parses, typechecks, and
1139 -- desugars the module, then returns the resulting Core module (consisting of
1140 -- the module name, type declarations, and function declarations) if
1142 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1143 compileToCoreModule = compileCore False
1145 -- | Like compileToCoreModule, but invokes the simplifier, so
1146 -- as to return simplified and tidied Core.
1147 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1148 compileToCoreSimplified = compileCore True
1150 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1151 -- bindings, but for most purposes, you probably want to call
1152 -- compileToCoreModule.
1153 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1154 compileToCore fn = do
1155 mod <- compileToCoreModule session fn
1156 return $ cm_binds mod
1158 -- | Takes a CoreModule and compiles the bindings therein
1159 -- to object code. The first argument is a bool flag indicating
1160 -- whether to run the simplifier.
1161 -- The resulting .o, .hi, and executable files, if any, are stored in the
1162 -- current directory, and named according to the module name.
1163 -- This has only so far been tested with a single self-contained module.
1164 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1165 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1166 dflags <- getSessionDynFlags
1167 currentTime <- liftIO $ getClockTime
1168 cwd <- liftIO $ getCurrentDirectory
1169 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1170 ((moduleNameSlashes . moduleName) mName)
1172 let modSummary = ModSummary { ms_mod = mName,
1173 ms_hsc_src = ExtCoreFile,
1174 ms_location = modLocation,
1175 -- By setting the object file timestamp to Nothing,
1176 -- we always force recompilation, which is what we
1177 -- want. (Thus it doesn't matter what the timestamp
1178 -- for the (nonexistent) source file is.)
1179 ms_hs_date = currentTime,
1180 ms_obj_date = Nothing,
1181 -- Only handling the single-module case for now, so no imports.
1186 ms_hspp_opts = dflags,
1187 ms_hspp_buf = Nothing
1190 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1191 | otherwise = return mod_guts
1192 guts <- maybe_simplify (mkModGuts cm)
1193 (iface, changed, _details, cgguts)
1194 <- hscNormalIface guts Nothing
1195 hscWriteIface iface changed modSummary
1196 _ <- hscGenHardCode cgguts modSummary
1199 -- Makes a "vanilla" ModGuts.
1200 mkModGuts :: CoreModule -> ModGuts
1201 mkModGuts coreModule = ModGuts {
1202 mg_module = cm_module coreModule,
1205 mg_deps = noDependencies,
1206 mg_dir_imps = emptyModuleEnv,
1207 mg_used_names = emptyNameSet,
1208 mg_rdr_env = emptyGlobalRdrEnv,
1209 mg_fix_env = emptyFixityEnv,
1210 mg_types = emptyTypeEnv,
1214 mg_binds = cm_binds coreModule,
1215 mg_foreign = NoStubs,
1216 mg_warns = NoWarnings,
1218 mg_hpc_info = emptyHpcInfo False,
1219 mg_modBreaks = emptyModBreaks,
1220 mg_vect_info = noVectInfo,
1221 mg_inst_env = emptyInstEnv,
1222 mg_fam_inst_env = emptyFamInstEnv
1225 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1226 compileCore simplify fn = do
1227 -- First, set the target to the desired filename
1228 target <- guessTarget fn Nothing
1230 _ <- load LoadAllTargets
1231 -- Then find dependencies
1232 modGraph <- depanal [] True
1233 case find ((== fn) . msHsFilePath) modGraph of
1234 Just modSummary -> do
1235 -- Now we have the module name;
1236 -- parse, typecheck and desugar the module
1237 mod_guts <- coreModule `fmap`
1238 -- TODO: space leaky: call hsc* directly?
1239 (desugarModule =<< typecheckModule =<< parseModule modSummary)
1240 liftM gutsToCoreModule $
1243 -- If simplify is true: simplify (hscSimplify), then tidy
1245 hsc_env <- getSession
1246 simpl_guts <- hscSimplify mod_guts
1247 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1248 return $ Left tidy_guts
1250 return $ Right mod_guts
1252 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1253 module dependency graph"
1254 where -- two versions, based on whether we simplify (thus run tidyProgram,
1255 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1256 -- we just have a ModGuts.
1257 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1258 gutsToCoreModule (Left (cg, md)) = CoreModule {
1259 cm_module = cg_module cg, cm_types = md_types md,
1260 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1262 gutsToCoreModule (Right mg) = CoreModule {
1263 cm_module = mg_module mg, cm_types = mg_types mg,
1264 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1267 -- ---------------------------------------------------------------------------
1270 unload :: HscEnv -> [Linkable] -> IO ()
1271 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1272 = case ghcLink (hsc_dflags hsc_env) of
1274 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1276 LinkInMemory -> panic "unload: no interpreter"
1277 -- urgh. avoid warnings:
1278 hsc_env stable_linkables
1282 -- -----------------------------------------------------------------------------
1286 Stability tells us which modules definitely do not need to be recompiled.
1287 There are two main reasons for having stability:
1289 - avoid doing a complete upsweep of the module graph in GHCi when
1290 modules near the bottom of the tree have not changed.
1292 - to tell GHCi when it can load object code: we can only load object code
1293 for a module when we also load object code fo all of the imports of the
1294 module. So we need to know that we will definitely not be recompiling
1295 any of these modules, and we can use the object code.
1297 The stability check is as follows. Both stableObject and
1298 stableBCO are used during the upsweep phase later.
1301 stable m = stableObject m || stableBCO m
1304 all stableObject (imports m)
1305 && old linkable does not exist, or is == on-disk .o
1306 && date(on-disk .o) > date(.hs)
1309 all stable (imports m)
1310 && date(BCO) > date(.hs)
1313 These properties embody the following ideas:
1315 - if a module is stable, then:
1317 - if it has been compiled in a previous pass (present in HPT)
1318 then it does not need to be compiled or re-linked.
1320 - if it has not been compiled in a previous pass,
1321 then we only need to read its .hi file from disk and
1322 link it to produce a 'ModDetails'.
1324 - if a modules is not stable, we will definitely be at least
1325 re-linking, and possibly re-compiling it during the 'upsweep'.
1326 All non-stable modules can (and should) therefore be unlinked
1327 before the 'upsweep'.
1329 - Note that objects are only considered stable if they only depend
1330 on other objects. We can't link object code against byte code.
1334 :: HomePackageTable -- HPT from last compilation
1335 -> [SCC ModSummary] -- current module graph (cyclic)
1336 -> [ModuleName] -- all home modules
1337 -> ([ModuleName], -- stableObject
1338 [ModuleName]) -- stableBCO
1340 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1342 checkSCC (stable_obj, stable_bco) scc0
1343 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1344 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1345 | otherwise = (stable_obj, stable_bco)
1347 scc = flattenSCC scc0
1348 scc_mods = map ms_mod_name scc
1349 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1351 scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
1352 -- all imports outside the current SCC, but in the home pkg
1354 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1355 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1359 && all object_ok scc
1362 and (zipWith (||) stable_obj_imps stable_bco_imps)
1366 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1370 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1371 Just hmi | Just l <- hm_linkable hmi
1372 -> isObjectLinkable l && t == linkableTime l
1374 -- why '>=' rather than '>' above? If the filesystem stores
1375 -- times to the nearset second, we may occasionally find that
1376 -- the object & source have the same modification time,
1377 -- especially if the source was automatically generated
1378 -- and compiled. Using >= is slightly unsafe, but it matches
1379 -- make's behaviour.
1382 = case lookupUFM hpt (ms_mod_name ms) of
1383 Just hmi | Just l <- hm_linkable hmi ->
1384 not (isObjectLinkable l) &&
1385 linkableTime l >= ms_hs_date ms
1388 -- -----------------------------------------------------------------------------
1390 -- | Prune the HomePackageTable
1392 -- Before doing an upsweep, we can throw away:
1394 -- - For non-stable modules:
1395 -- - all ModDetails, all linked code
1396 -- - all unlinked code that is out of date with respect to
1399 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1400 -- space at the end of the upsweep, because the topmost ModDetails of the
1401 -- old HPT holds on to the entire type environment from the previous
1404 pruneHomePackageTable
1407 -> ([ModuleName],[ModuleName])
1410 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1413 | is_stable modl = hmi'
1414 | otherwise = hmi'{ hm_details = emptyModDetails }
1416 modl = moduleName (mi_module (hm_iface hmi))
1417 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1418 = hmi{ hm_linkable = Nothing }
1421 where ms = expectJust "prune" (lookupUFM ms_map modl)
1423 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1425 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1427 -- -----------------------------------------------------------------------------
1429 -- Return (names of) all those in modsDone who are part of a cycle
1430 -- as defined by theGraph.
1431 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1432 findPartiallyCompletedCycles modsDone theGraph
1436 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1437 chew ((CyclicSCC vs):rest)
1438 = let names_in_this_cycle = nub (map ms_mod vs)
1440 = nub ([done | done <- modsDone,
1441 done `elem` names_in_this_cycle])
1442 chewed_rest = chew rest
1444 if notNull mods_in_this_cycle
1445 && length mods_in_this_cycle < length names_in_this_cycle
1446 then mods_in_this_cycle ++ chewed_rest
1449 -- -----------------------------------------------------------------------------
1453 -- This is where we compile each module in the module graph, in a pass
1454 -- from the bottom to the top of the graph.
1456 -- There better had not be any cyclic groups here -- we check for them.
1460 HscEnv -- ^ Includes initially-empty HPT
1461 -> HomePackageTable -- ^ HPT from last time round (pruned)
1462 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1463 -> IO () -- ^ How to clean up unwanted tmp files
1464 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1470 -- 1. A flag whether the complete upsweep was successful.
1471 -- 2. The 'HscEnv' with an updated HPT
1472 -- 3. A list of modules which succeeded loading.
1474 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1475 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1476 return (res, hsc_env, reverse done)
1479 upsweep' hsc_env _old_hpt done
1481 = return (Succeeded, hsc_env, done)
1483 upsweep' hsc_env _old_hpt done
1484 (CyclicSCC ms:_) _ _
1485 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1486 return (Failed, hsc_env, done)
1488 upsweep' hsc_env old_hpt done
1489 (AcyclicSCC mod:mods) mod_index nmods
1490 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1491 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1492 -- (moduleEnvElts (hsc_HPT hsc_env)))
1493 let logger = reportModuleCompilationResult (hsc_callbacks hsc_env)
1496 <- handleSourceError
1497 (\err -> do logger mod (Just err); return Nothing) $ do
1498 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1500 logger mod Nothing -- log warnings
1501 return (Just mod_info)
1503 liftIO cleanup -- Remove unwanted tmp files between compilations
1506 Nothing -> return (Failed, hsc_env, done)
1508 let this_mod = ms_mod_name mod
1510 -- Add new info to hsc_env
1511 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1512 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1514 -- Space-saving: delete the old HPT entry
1515 -- for mod BUT if mod is a hs-boot
1516 -- node, don't delete it. For the
1517 -- interface, the HPT entry is probaby for the
1518 -- main Haskell source file. Deleting it
1519 -- would force the real module to be recompiled
1521 old_hpt1 | isBootSummary mod = old_hpt
1522 | otherwise = delFromUFM old_hpt this_mod
1526 -- fixup our HomePackageTable after we've finished compiling
1527 -- a mutually-recursive loop. See reTypecheckLoop, below.
1528 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1530 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1532 -- | Compile a single module. Always produce a Linkable for it if
1533 -- successful. If no compilation happened, return the old Linkable.
1534 upsweep_mod :: GhcMonad m =>
1537 -> ([ModuleName],[ModuleName])
1539 -> Int -- index of module
1540 -> Int -- total number of modules
1543 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1545 this_mod_name = ms_mod_name summary
1546 this_mod = ms_mod summary
1547 mb_obj_date = ms_obj_date summary
1548 obj_fn = ml_obj_file (ms_location summary)
1549 hs_date = ms_hs_date summary
1551 is_stable_obj = this_mod_name `elem` stable_obj
1552 is_stable_bco = this_mod_name `elem` stable_bco
1554 old_hmi = lookupUFM old_hpt this_mod_name
1556 -- We're using the dflags for this module now, obtained by
1557 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1558 dflags = ms_hspp_opts summary
1559 prevailing_target = hscTarget (hsc_dflags hsc_env)
1560 local_target = hscTarget dflags
1562 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1563 -- we don't do anything dodgy: these should only work to change
1564 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1565 -- end up trying to link object code to byte code.
1566 target = if prevailing_target /= local_target
1567 && (not (isObjectTarget prevailing_target)
1568 || not (isObjectTarget local_target))
1569 then prevailing_target
1572 -- store the corrected hscTarget into the summary
1573 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1575 -- The old interface is ok if
1576 -- a) we're compiling a source file, and the old HPT
1577 -- entry is for a source file
1578 -- b) we're compiling a hs-boot file
1579 -- Case (b) allows an hs-boot file to get the interface of its
1580 -- real source file on the second iteration of the compilation
1581 -- manager, but that does no harm. Otherwise the hs-boot file
1582 -- will always be recompiled
1587 Just hm_info | isBootSummary summary -> Just iface
1588 | not (mi_boot iface) -> Just iface
1589 | otherwise -> Nothing
1591 iface = hm_iface hm_info
1593 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1594 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1596 compile_it_discard_iface :: GhcMonad m =>
1597 Maybe Linkable -> m HomeModInfo
1598 compile_it_discard_iface
1599 = compile hsc_env summary' mod_index nmods Nothing
1601 -- With the HscNothing target we create empty linkables to avoid
1602 -- recompilation. We have to detect these to recompile anyway if
1603 -- the target changed since the last compile.
1605 | Just hmi <- old_hmi, Just l <- hm_linkable hmi =
1606 null (linkableUnlinked l)
1608 -- we have no linkable, so it cannot be fake
1611 implies False _ = True
1617 -- Regardless of whether we're generating object code or
1618 -- byte code, we can always use an existing object file
1619 -- if it is *stable* (see checkStability).
1620 | is_stable_obj, Just hmi <- old_hmi -> do
1621 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1622 (text "skipping stable obj mod:" <+> ppr this_mod_name)
1624 -- object is stable, and we have an entry in the
1625 -- old HPT: nothing to do
1627 | is_stable_obj, isNothing old_hmi -> do
1628 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1629 (text "compiling stable on-disk mod:" <+> ppr this_mod_name)
1630 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1631 (expectJust "upsweep1" mb_obj_date)
1632 compile_it (Just linkable)
1633 -- object is stable, but we need to load the interface
1634 -- off disk to make a HMI.
1636 | not (isObjectTarget target), is_stable_bco,
1637 (target /= HscNothing) `implies` not is_fake_linkable ->
1638 ASSERT(isJust old_hmi) -- must be in the old_hpt
1639 let Just hmi = old_hmi in do
1640 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1641 (text "skipping stable BCO mod:" <+> ppr this_mod_name)
1643 -- BCO is stable: nothing to do
1645 | not (isObjectTarget target),
1646 Just hmi <- old_hmi,
1647 Just l <- hm_linkable hmi,
1648 not (isObjectLinkable l),
1649 (target /= HscNothing) `implies` not is_fake_linkable,
1650 linkableTime l >= ms_hs_date summary -> do
1651 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1652 (text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
1654 -- we have an old BCO that is up to date with respect
1655 -- to the source: do a recompilation check as normal.
1657 -- When generating object code, if there's an up-to-date
1658 -- object file on the disk, then we can use it.
1659 -- However, if the object file is new (compared to any
1660 -- linkable we had from a previous compilation), then we
1661 -- must discard any in-memory interface, because this
1662 -- means the user has compiled the source file
1663 -- separately and generated a new interface, that we must
1664 -- read from the disk.
1666 | isObjectTarget target,
1667 Just obj_date <- mb_obj_date,
1668 obj_date >= hs_date -> do
1671 | Just l <- hm_linkable hmi,
1672 isObjectLinkable l && linkableTime l == obj_date -> do
1673 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1674 (text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
1677 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1678 (text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
1679 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1680 compile_it_discard_iface (Just linkable)
1683 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1684 (text "compiling mod:" <+> ppr this_mod_name)
1689 -- Filter modules in the HPT
1690 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1691 retainInTopLevelEnvs keep_these hpt
1692 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1694 , let mb_mod_info = lookupUFM hpt mod
1695 , isJust mb_mod_info ]
1697 -- ---------------------------------------------------------------------------
1698 -- Typecheck module loops
1701 See bug #930. This code fixes a long-standing bug in --make. The
1702 problem is that when compiling the modules *inside* a loop, a data
1703 type that is only defined at the top of the loop looks opaque; but
1704 after the loop is done, the structure of the data type becomes
1707 The difficulty is then that two different bits of code have
1708 different notions of what the data type looks like.
1710 The idea is that after we compile a module which also has an .hs-boot
1711 file, we re-generate the ModDetails for each of the modules that
1712 depends on the .hs-boot file, so that everyone points to the proper
1713 TyCons, Ids etc. defined by the real module, not the boot module.
1714 Fortunately re-generating a ModDetails from a ModIface is easy: the
1715 function TcIface.typecheckIface does exactly that.
1717 Picking the modules to re-typecheck is slightly tricky. Starting from
1718 the module graph consisting of the modules that have already been
1719 compiled, we reverse the edges (so they point from the imported module
1720 to the importing module), and depth-first-search from the .hs-boot
1721 node. This gives us all the modules that depend transitively on the
1722 .hs-boot module, and those are exactly the modules that we need to
1725 Following this fix, GHC can compile itself with --make -O2.
1728 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1729 reTypecheckLoop hsc_env ms graph
1730 | not (isBootSummary ms) &&
1731 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1733 let mss = reachableBackwards (ms_mod_name ms) graph
1734 non_boot = filter (not.isBootSummary) mss
1735 debugTraceMsg (hsc_dflags hsc_env) 2 $
1736 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1737 typecheckLoop hsc_env (map ms_mod_name non_boot)
1741 this_mod = ms_mod ms
1743 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1744 typecheckLoop hsc_env mods = do
1746 fixIO $ \new_hpt -> do
1747 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1748 mds <- initIfaceCheck new_hsc_env $
1749 mapM (typecheckIface . hm_iface) hmis
1750 let new_hpt = addListToUFM old_hpt
1751 (zip mods [ hmi{ hm_details = details }
1752 | (hmi,details) <- zip hmis mds ])
1754 return hsc_env{ hsc_HPT = new_hpt }
1756 old_hpt = hsc_HPT hsc_env
1757 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1759 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1760 reachableBackwards mod summaries
1761 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1762 where -- the rest just sets up the graph:
1763 (graph, lookup_node) = moduleGraphNodes False summaries
1764 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1766 -- ---------------------------------------------------------------------------
1767 -- Topological sort of the module graph
1769 type SummaryNode = (ModSummary, Int, [Int])
1773 -- ^ Drop hi-boot nodes? (see below)
1776 -- ^ Root module name. If @Nothing@, use the full graph.
1778 -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1779 -- The resulting list of strongly-connected-components is in topologically
1780 -- sorted order, starting with the module(s) at the bottom of the
1781 -- dependency graph (ie compile them first) and ending with the ones at
1784 -- Drop hi-boot nodes (first boolean arg)?
1786 -- - @False@: treat the hi-boot summaries as nodes of the graph,
1787 -- so the graph must be acyclic
1789 -- - @True@: eliminate the hi-boot nodes, and instead pretend
1790 -- the a source-import of Foo is an import of Foo
1791 -- The resulting graph has no hi-boot nodes, but can be cyclic
1793 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1794 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1796 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1798 initial_graph = case mb_root_mod of
1801 -- restrict the graph to just those modules reachable from
1802 -- the specified module. We do this by building a graph with
1803 -- the full set of nodes, and determining the reachable set from
1804 -- the specified node.
1805 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1806 | otherwise = ghcError (ProgramError "module does not exist")
1807 in graphFromEdgedVertices (seq root (reachableG graph root))
1809 summaryNodeKey :: SummaryNode -> Int
1810 summaryNodeKey (_, k, _) = k
1812 summaryNodeSummary :: SummaryNode -> ModSummary
1813 summaryNodeSummary (s, _, _) = s
1815 moduleGraphNodes :: Bool -> [ModSummary]
1816 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1817 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1819 numbered_summaries = zip summaries [1..]
1821 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1822 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1824 lookup_key :: HscSource -> ModuleName -> Maybe Int
1825 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1827 node_map :: NodeMap SummaryNode
1828 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1829 | node@(s, _, _) <- nodes ]
1831 -- We use integers as the keys for the SCC algorithm
1832 nodes :: [SummaryNode]
1833 nodes = [ (s, key, out_keys)
1834 | (s, key) <- numbered_summaries
1835 -- Drop the hi-boot ones if told to do so
1836 , not (isBootSummary s && drop_hs_boot_nodes)
1837 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
1838 out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
1839 (-- see [boot-edges] below
1840 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1842 else case lookup_key HsBootFile (ms_mod_name s) of
1846 -- [boot-edges] if this is a .hs and there is an equivalent
1847 -- .hs-boot, add a link from the former to the latter. This
1848 -- has the effect of detecting bogus cases where the .hs-boot
1849 -- depends on the .hs, by introducing a cycle. Additionally,
1850 -- it ensures that we will always process the .hs-boot before
1851 -- the .hs, and so the HomePackageTable will always have the
1852 -- most up to date information.
1854 -- Drop hs-boot nodes by using HsSrcFile as the key
1855 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1856 | otherwise = HsBootFile
1858 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1859 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1860 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1861 -- the IsBootInterface parameter True; else False
1864 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1865 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1867 msKey :: ModSummary -> NodeKey
1868 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1870 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1871 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1873 nodeMapElts :: NodeMap a -> [a]
1874 nodeMapElts = eltsFM
1876 -- | If there are {-# SOURCE #-} imports between strongly connected
1877 -- components in the topological sort, then those imports can
1878 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1879 -- were necessary, then the edge would be part of a cycle.
1880 warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
1881 warnUnnecessarySourceImports sccs =
1882 logWarnings (listToBag (concatMap (check.flattenSCC) sccs))
1884 let mods_in_this_cycle = map ms_mod_name ms in
1885 [ warn i | m <- ms, i <- ms_home_srcimps m,
1886 unLoc i `notElem` mods_in_this_cycle ]
1888 warn :: Located ModuleName -> WarnMsg
1891 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1892 <+> quotes (ppr mod))
1894 -----------------------------------------------------------------------------
1895 -- Downsweep (dependency analysis)
1897 -- Chase downwards from the specified root set, returning summaries
1898 -- for all home modules encountered. Only follow source-import
1901 -- We pass in the previous collection of summaries, which is used as a
1902 -- cache to avoid recalculating a module summary if the source is
1905 -- The returned list of [ModSummary] nodes has one node for each home-package
1906 -- module, plus one for any hs-boot files. The imports of these nodes
1907 -- are all there, including the imports of non-home-package modules.
1909 downsweep :: GhcMonad m =>
1911 -> [ModSummary] -- Old summaries
1912 -> [ModuleName] -- Ignore dependencies on these; treat
1913 -- them as if they were package modules
1914 -> Bool -- True <=> allow multiple targets to have
1915 -- the same module name; this is
1916 -- very useful for ghc -M
1918 -- The elts of [ModSummary] all have distinct
1919 -- (Modules, IsBoot) identifiers, unless the Bool is true
1920 -- in which case there can be repeats
1921 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1922 = do -- catch error messages and return them
1923 --handleErrMsg -- should be covered by GhcMonad now
1924 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1925 rootSummaries <- mapM getRootSummary roots
1926 let root_map = mkRootMap rootSummaries
1927 checkDuplicates root_map
1928 summs <- loop (concatMap msDeps rootSummaries) root_map
1931 roots = hsc_targets hsc_env
1933 old_summary_map :: NodeMap ModSummary
1934 old_summary_map = mkNodeMap old_summaries
1936 getRootSummary :: GhcMonad m => Target -> m ModSummary
1937 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1938 = do exists <- liftIO $ doesFileExist file
1940 then summariseFile hsc_env old_summaries file mb_phase
1941 obj_allowed maybe_buf
1942 else throwOneError $ mkPlainErrMsg noSrcSpan $
1943 text "can't find file:" <+> text file
1944 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1945 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1946 (L rootLoc modl) obj_allowed
1948 case maybe_summary of
1949 Nothing -> packageModErr modl
1952 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1954 -- In a root module, the filename is allowed to diverge from the module
1955 -- name, so we have to check that there aren't multiple root files
1956 -- defining the same module (otherwise the duplicates will be silently
1957 -- ignored, leading to confusing behaviour).
1958 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1959 checkDuplicates root_map
1960 | allow_dup_roots = return ()
1961 | null dup_roots = return ()
1962 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1964 dup_roots :: [[ModSummary]] -- Each at least of length 2
1965 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1967 loop :: GhcMonad m =>
1968 [(Located ModuleName,IsBootInterface)]
1969 -- Work list: process these modules
1970 -> NodeMap [ModSummary]
1971 -- Visited set; the range is a list because
1972 -- the roots can have the same module names
1973 -- if allow_dup_roots is True
1975 -- The result includes the worklist, except
1976 -- for those mentioned in the visited set
1977 loop [] done = return (concat (nodeMapElts done))
1978 loop ((wanted_mod, is_boot) : ss) done
1979 | Just summs <- lookupFM done key
1980 = if isSingleton summs then
1983 do { liftIO $ multiRootsErr summs; return [] }
1985 = do mb_s <- summariseModule hsc_env old_summary_map
1986 is_boot wanted_mod True
1989 Nothing -> loop ss done
1990 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1992 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1994 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1995 mkRootMap summaries = addListToFM_C (++) emptyFM
1996 [ (msKey s, [s]) | s <- summaries ]
1998 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1999 -- (msDeps s) returns the dependencies of the ModSummary s.
2000 -- A wrinkle is that for a {-# SOURCE #-} import we return
2001 -- *both* the hs-boot file
2002 -- *and* the source file
2003 -- as "dependencies". That ensures that the list of all relevant
2004 -- modules always contains B.hs if it contains B.hs-boot.
2005 -- Remember, this pass isn't doing the topological sort. It's
2006 -- just gathering the list of all relevant ModSummaries
2008 concat [ [(m,True), (m,False)] | m <- ms_home_srcimps s ]
2009 ++ [ (m,False) | m <- ms_home_imps s ]
2011 home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName]
2012 home_imps imps = [ ideclName i | L _ i <- imps, isNothing (ideclPkgQual i) ]
2014 ms_home_allimps :: ModSummary -> [ModuleName]
2015 ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
2017 ms_home_srcimps :: ModSummary -> [Located ModuleName]
2018 ms_home_srcimps = home_imps . ms_srcimps
2020 ms_home_imps :: ModSummary -> [Located ModuleName]
2021 ms_home_imps = home_imps . ms_imps
2023 -----------------------------------------------------------------------------
2024 -- Summarising modules
2026 -- We have two types of summarisation:
2028 -- * Summarise a file. This is used for the root module(s) passed to
2029 -- cmLoadModules. The file is read, and used to determine the root
2030 -- module name. The module name may differ from the filename.
2032 -- * Summarise a module. We are given a module name, and must provide
2033 -- a summary. The finder is used to locate the file in which the module
2039 -> [ModSummary] -- old summaries
2040 -> FilePath -- source file name
2041 -> Maybe Phase -- start phase
2042 -> Bool -- object code allowed?
2043 -> Maybe (StringBuffer,ClockTime)
2046 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
2047 -- we can use a cached summary if one is available and the
2048 -- source file hasn't changed, But we have to look up the summary
2049 -- by source file, rather than module name as we do in summarise.
2050 | Just old_summary <- findSummaryBySourceFile old_summaries file
2052 let location = ms_location old_summary
2054 -- return the cached summary if the source didn't change
2055 src_timestamp <- case maybe_buf of
2056 Just (_,t) -> return t
2057 Nothing -> liftIO $ getModificationTime file
2058 -- The file exists; we checked in getRootSummary above.
2059 -- If it gets removed subsequently, then this
2060 -- getModificationTime may fail, but that's the right
2063 if ms_hs_date old_summary == src_timestamp
2064 then do -- update the object-file timestamp
2066 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2067 || obj_allowed -- bug #1205
2068 then liftIO $ getObjTimestamp location False
2070 return old_summary{ ms_obj_date = obj_timestamp }
2078 let dflags = hsc_dflags hsc_env
2080 (dflags', hspp_fn, buf)
2081 <- preprocessFile hsc_env file mb_phase maybe_buf
2083 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
2085 -- Make a ModLocation for this file
2086 location <- liftIO $ mkHomeModLocation dflags mod_name file
2088 -- Tell the Finder cache where it is, so that subsequent calls
2089 -- to findModule will find it, even if it's not on any search path
2090 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2092 src_timestamp <- case maybe_buf of
2093 Just (_,t) -> return t
2094 Nothing -> liftIO $ getModificationTime file
2095 -- getMofificationTime may fail
2097 -- when the user asks to load a source file by name, we only
2098 -- use an object file if -fobject-code is on. See #1205.
2100 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2101 || obj_allowed -- bug #1205
2102 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2105 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2106 ms_location = location,
2107 ms_hspp_file = hspp_fn,
2108 ms_hspp_opts = dflags',
2109 ms_hspp_buf = Just buf,
2110 ms_srcimps = srcimps, ms_imps = the_imps,
2111 ms_hs_date = src_timestamp,
2112 ms_obj_date = obj_timestamp })
2114 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2115 findSummaryBySourceFile summaries file
2116 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2117 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2121 -- Summarise a module, and pick up source and timestamp.
2125 -> NodeMap ModSummary -- Map of old summaries
2126 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2127 -> Located ModuleName -- Imported module to be summarised
2128 -> Bool -- object code allowed?
2129 -> Maybe (StringBuffer, ClockTime)
2130 -> [ModuleName] -- Modules to exclude
2131 -> m (Maybe ModSummary) -- Its new summary
2133 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2134 obj_allowed maybe_buf excl_mods
2135 | wanted_mod `elem` excl_mods
2138 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2139 = do -- Find its new timestamp; all the
2140 -- ModSummaries in the old map have valid ml_hs_files
2141 let location = ms_location old_summary
2142 src_fn = expectJust "summariseModule" (ml_hs_file location)
2144 -- check the modification time on the source file, and
2145 -- return the cached summary if it hasn't changed. If the
2146 -- file has disappeared, we need to call the Finder again.
2148 Just (_,t) -> check_timestamp old_summary location src_fn t
2150 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2152 Right t -> check_timestamp old_summary location src_fn t
2153 Left e | isDoesNotExistError e -> find_it
2154 | otherwise -> liftIO $ ioError e
2156 | otherwise = find_it
2158 dflags = hsc_dflags hsc_env
2160 hsc_src = if is_boot then HsBootFile else HsSrcFile
2162 check_timestamp old_summary location src_fn src_timestamp
2163 | ms_hs_date old_summary == src_timestamp = do
2164 -- update the object-file timestamp
2165 obj_timestamp <- liftIO $
2166 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2167 || obj_allowed -- bug #1205
2168 then getObjTimestamp location is_boot
2170 return (Just old_summary{ ms_obj_date = obj_timestamp })
2172 -- source changed: re-summarise.
2173 new_summary location (ms_mod old_summary) src_fn src_timestamp
2176 -- Don't use the Finder's cache this time. If the module was
2177 -- previously a package module, it may have now appeared on the
2178 -- search path, so we want to consider it to be a home module. If
2179 -- the module was previously a home module, it may have moved.
2180 liftIO $ uncacheModule hsc_env wanted_mod
2181 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2184 | isJust (ml_hs_file location) ->
2186 just_found location mod
2188 -- Drop external-pkg
2189 ASSERT(modulePackageId mod /= thisPackage dflags)
2192 err -> liftIO $ noModError dflags loc wanted_mod err
2195 just_found location mod = do
2196 -- Adjust location to point to the hs-boot source file,
2197 -- hi file, object file, when is_boot says so
2198 let location' | is_boot = addBootSuffixLocn location
2199 | otherwise = location
2200 src_fn = expectJust "summarise2" (ml_hs_file location')
2202 -- Check that it exists
2203 -- It might have been deleted since the Finder last found it
2204 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2206 Nothing -> noHsFileErr loc src_fn
2207 Just t -> new_summary location' mod src_fn t
2210 new_summary location mod src_fn src_timestamp
2212 -- Preprocess the source file and get its imports
2213 -- The dflags' contains the OPTIONS pragmas
2214 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2215 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
2217 when (mod_name /= wanted_mod) $
2218 throwOneError $ mkPlainErrMsg mod_loc $
2219 text "File name does not match module name:"
2220 $$ text "Saw:" <+> quotes (ppr mod_name)
2221 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2223 -- Find the object timestamp, and return the summary
2224 obj_timestamp <- liftIO $
2225 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2226 || obj_allowed -- bug #1205
2227 then getObjTimestamp location is_boot
2230 return (Just (ModSummary { ms_mod = mod,
2231 ms_hsc_src = hsc_src,
2232 ms_location = location,
2233 ms_hspp_file = hspp_fn,
2234 ms_hspp_opts = dflags',
2235 ms_hspp_buf = Just buf,
2236 ms_srcimps = srcimps,
2238 ms_hs_date = src_timestamp,
2239 ms_obj_date = obj_timestamp }))
2242 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2243 getObjTimestamp location is_boot
2244 = if is_boot then return Nothing
2245 else modificationTimeIfExists (ml_obj_file location)
2248 preprocessFile :: GhcMonad m =>
2251 -> Maybe Phase -- ^ Starting phase
2252 -> Maybe (StringBuffer,ClockTime)
2253 -> m (DynFlags, FilePath, StringBuffer)
2254 preprocessFile hsc_env src_fn mb_phase Nothing
2256 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2257 buf <- liftIO $ hGetStringBuffer hspp_fn
2258 return (dflags', hspp_fn, buf)
2260 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2262 let dflags = hsc_dflags hsc_env
2263 -- case we bypass the preprocessing stage?
2265 local_opts = getOptions dflags buf src_fn
2267 (dflags', leftovers, warns)
2268 <- parseDynamicNoPackageFlags dflags local_opts
2269 checkProcessArgsResult leftovers
2270 handleFlagWarnings dflags' warns
2274 | Just (Unlit _) <- mb_phase = True
2275 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2276 -- note: local_opts is only required if there's no Unlit phase
2277 | dopt Opt_Cpp dflags' = True
2278 | dopt Opt_Pp dflags' = True
2281 when needs_preprocessing $
2282 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2284 return (dflags', src_fn, buf)
2287 -----------------------------------------------------------------------------
2289 -----------------------------------------------------------------------------
2291 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2292 -- ToDo: we don't have a proper line number for this error
2293 noModError dflags loc wanted_mod err
2294 = throwOneError $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2296 noHsFileErr :: GhcMonad m => SrcSpan -> String -> m a
2297 noHsFileErr loc path
2298 = throwOneError $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2300 packageModErr :: GhcMonad m => ModuleName -> m a
2302 = throwOneError $ mkPlainErrMsg noSrcSpan $
2303 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2305 multiRootsErr :: [ModSummary] -> IO ()
2306 multiRootsErr [] = panic "multiRootsErr"
2307 multiRootsErr summs@(summ1:_)
2308 = throwOneError $ mkPlainErrMsg noSrcSpan $
2309 text "module" <+> quotes (ppr mod) <+>
2310 text "is defined in multiple files:" <+>
2311 sep (map text files)
2314 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2316 cyclicModuleErr :: [ModSummary] -> SDoc
2318 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2319 2 (vcat (map show_one ms))
2321 mods_in_cycle = map ms_mod_name ms
2322 imp_modname = unLoc . ideclName . unLoc
2323 just_in_cycle = filter ((`elem` mods_in_cycle) . imp_modname)
2326 vcat [ show_mod (ms_hsc_src ms) (ms_mod_name ms) <+>
2327 maybe empty (parens . text) (ml_hs_file (ms_location ms)),
2328 nest 2 $ ptext (sLit "imports:") <+> vcat [
2329 pp_imps HsBootFile (just_in_cycle $ ms_srcimps ms),
2330 pp_imps HsSrcFile (just_in_cycle $ ms_imps ms) ]
2332 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2333 pp_imps src imps = fsep (map (show_mod src . unLoc . ideclName . unLoc) imps)
2336 -- | Inform GHC that the working directory has changed. GHC will flush
2337 -- its cache of module locations, since it may no longer be valid.
2339 -- Note: Before changing the working directory make sure all threads running
2340 -- in the same session have stopped. If you change the working directory,
2341 -- you should also unload the current program (set targets to empty,
2342 -- followed by load).
2343 workingDirectoryChanged :: GhcMonad m => m ()
2344 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2346 -- -----------------------------------------------------------------------------
2347 -- inspecting the session
2349 -- | Get the module dependency graph.
2350 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2351 getModuleGraph = liftM hsc_mod_graph getSession
2353 -- | Determines whether a set of modules requires Template Haskell.
2355 -- Note that if the session's 'DynFlags' enabled Template Haskell when
2356 -- 'depanal' was called, then each module in the returned module graph will
2357 -- have Template Haskell enabled whether it is actually needed or not.
2358 needsTemplateHaskell :: ModuleGraph -> Bool
2359 needsTemplateHaskell ms =
2360 any (dopt Opt_TemplateHaskell . ms_hspp_opts) ms
2362 -- | Return @True@ <==> module is loaded.
2363 isLoaded :: GhcMonad m => ModuleName -> m Bool
2364 isLoaded m = withSession $ \hsc_env ->
2365 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2367 -- | Return the bindings for the current interactive session.
2368 getBindings :: GhcMonad m => m [TyThing]
2369 getBindings = withSession $ \hsc_env ->
2370 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2371 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2373 occ_env = mkOccEnv [ (nameOccName (idName id), AnId id)
2374 | id <- ic_tmp_ids (hsc_IC hsc_env) ]
2376 return (occEnvElts occ_env)
2378 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2379 getPrintUnqual = withSession $ \hsc_env ->
2380 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2382 -- | Container for information about a 'Module'.
2383 data ModuleInfo = ModuleInfo {
2384 minf_type_env :: TypeEnv,
2385 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2386 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2387 minf_instances :: [Instance]
2389 ,minf_modBreaks :: ModBreaks
2391 -- ToDo: this should really contain the ModIface too
2393 -- We don't want HomeModInfo here, because a ModuleInfo applies
2394 -- to package modules too.
2396 -- | Request information about a loaded 'Module'
2397 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2398 getModuleInfo mdl = withSession $ \hsc_env -> do
2399 let mg = hsc_mod_graph hsc_env
2400 if mdl `elem` map ms_mod mg
2401 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2403 {- if isHomeModule (hsc_dflags hsc_env) mdl
2405 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2406 -- getPackageModuleInfo will attempt to find the interface, so
2407 -- we don't want to call it for a home module, just in case there
2408 -- was a problem loading the module and the interface doesn't
2409 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2411 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2413 getPackageModuleInfo hsc_env mdl = do
2414 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2416 Nothing -> return Nothing
2418 eps <- readIORef (hsc_EPS hsc_env)
2420 names = availsToNameSet avails
2422 tys = [ ty | name <- concatMap availNames avails,
2423 Just ty <- [lookupTypeEnv pte name] ]
2425 return (Just (ModuleInfo {
2426 minf_type_env = mkTypeEnv tys,
2427 minf_exports = names,
2428 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2429 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2430 minf_modBreaks = emptyModBreaks
2433 getPackageModuleInfo _hsc_env _mdl = do
2434 -- bogusly different for non-GHCI (ToDo)
2438 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2439 getHomeModuleInfo hsc_env mdl =
2440 case lookupUFM (hsc_HPT hsc_env) mdl of
2441 Nothing -> return Nothing
2443 let details = hm_details hmi
2444 return (Just (ModuleInfo {
2445 minf_type_env = md_types details,
2446 minf_exports = availsToNameSet (md_exports details),
2447 minf_rdr_env = mi_globals $! hm_iface hmi,
2448 minf_instances = md_insts details
2450 ,minf_modBreaks = getModBreaks hmi
2454 -- | The list of top-level entities defined in a module
2455 modInfoTyThings :: ModuleInfo -> [TyThing]
2456 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2458 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2459 modInfoTopLevelScope minf
2460 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2462 modInfoExports :: ModuleInfo -> [Name]
2463 modInfoExports minf = nameSetToList $! minf_exports minf
2465 -- | Returns the instances defined by the specified module.
2466 -- Warning: currently unimplemented for package modules.
2467 modInfoInstances :: ModuleInfo -> [Instance]
2468 modInfoInstances = minf_instances
2470 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2471 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2473 mkPrintUnqualifiedForModule :: GhcMonad m =>
2475 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2476 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2477 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2479 modInfoLookupName :: GhcMonad m =>
2481 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2482 modInfoLookupName minf name = withSession $ \hsc_env -> do
2483 case lookupTypeEnv (minf_type_env minf) name of
2484 Just tyThing -> return (Just tyThing)
2486 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2487 return $! lookupType (hsc_dflags hsc_env)
2488 (hsc_HPT hsc_env) (eps_PTE eps) name
2491 modInfoModBreaks :: ModuleInfo -> ModBreaks
2492 modInfoModBreaks = minf_modBreaks
2495 isDictonaryId :: Id -> Bool
2497 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2499 -- | Looks up a global name: that is, any top-level name in any
2500 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2501 -- the interactive context, and therefore does not require a preceding
2503 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2504 lookupGlobalName name = withSession $ \hsc_env -> do
2505 liftIO $ lookupTypeHscEnv hsc_env name
2507 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
2508 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
2509 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
2510 return (findAnns deserialize ann_env target)
2513 -- | get the GlobalRdrEnv for a session
2514 getGRE :: GhcMonad m => m GlobalRdrEnv
2515 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2518 -- -----------------------------------------------------------------------------
2520 -- | Return all /external/ modules available in the package database.
2521 -- Modules from the current session (i.e., from the 'HomePackageTable') are
2523 packageDbModules :: GhcMonad m =>
2524 Bool -- ^ Only consider exposed packages.
2526 packageDbModules only_exposed = do
2527 dflags <- getSessionDynFlags
2528 let pkgs = UFM.eltsUFM (pkgIdMap (pkgState dflags))
2530 [ mkModule pid modname | p <- pkgs
2531 , not only_exposed || exposed p
2532 , let pid = packageConfigId p
2533 , modname <- exposedModules p ]
2535 -- -----------------------------------------------------------------------------
2536 -- Misc exported utils
2538 dataConType :: DataCon -> Type
2539 dataConType dc = idType (dataConWrapId dc)
2541 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2542 pprParenSymName :: NamedThing a => a -> SDoc
2543 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2545 -- ----------------------------------------------------------------------------
2550 -- - Data and Typeable instances for HsSyn.
2552 -- ToDo: check for small transformations that happen to the syntax in
2553 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2555 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2556 -- to get from TyCons, Ids etc. to TH syntax (reify).
2558 -- :browse will use either lm_toplev or inspect lm_interface, depending
2559 -- on whether the module is interpreted or not.
2563 -- Extract the filename, stringbuffer content and dynflags associed to a module
2565 -- XXX: Explain pre-conditions
2566 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
2567 getModuleSourceAndFlags mod = do
2568 m <- getModSummary (moduleName mod)
2569 case ml_hs_file $ ms_location m of
2570 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
2571 Just sourceFile -> do
2572 source <- liftIO $ hGetStringBuffer sourceFile
2573 return (sourceFile, source, ms_hspp_opts m)
2576 -- | Return module source as token stream, including comments.
2578 -- The module must be in the module graph and its source must be available.
2579 -- Throws a 'HscTypes.SourceError' on parse error.
2580 getTokenStream :: GhcMonad m => Module -> m [Located Token]
2581 getTokenStream mod = do
2582 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2583 let startLoc = mkSrcLoc (mkFastString sourceFile) 1 1
2584 case lexTokenStream source startLoc flags of
2585 POk _ ts -> return ts
2586 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2588 -- | Give even more information on the source than 'getTokenStream'
2589 -- This function allows reconstructing the source completely with
2590 -- 'showRichTokenStream'.
2591 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
2592 getRichTokenStream mod = do
2593 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2594 let startLoc = mkSrcLoc (mkFastString sourceFile) 1 1
2595 case lexTokenStream source startLoc flags of
2596 POk _ ts -> return $ addSourceToTokens startLoc source ts
2597 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2599 -- | Given a source location and a StringBuffer corresponding to this
2600 -- location, return a rich token stream with the source associated to the
2602 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
2603 -> [(Located Token, String)]
2604 addSourceToTokens _ _ [] = []
2605 addSourceToTokens loc buf (t@(L span _) : ts)
2606 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
2607 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
2609 (newLoc, newBuf, str) = go "" loc buf
2610 start = srcSpanStart span
2611 end = srcSpanEnd span
2612 go acc loc buf | loc < start = go acc nLoc nBuf
2613 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
2614 | otherwise = (loc, buf, reverse acc)
2615 where (ch, nBuf) = nextChar buf
2616 nLoc = advanceSrcLoc loc ch
2619 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
2620 -- return source code almost identical to the original code (except for
2621 -- insignificant whitespace.)
2622 showRichTokenStream :: [(Located Token, String)] -> String
2623 showRichTokenStream ts = go startLoc ts ""
2624 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
2625 startLoc = mkSrcLoc sourceFile 1 1
2627 go loc ((L span _, str):ts)
2628 | not (isGoodSrcSpan span) = go loc ts
2629 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
2632 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
2633 . ((replicate tokCol ' ') ++)
2636 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
2637 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
2638 tokEnd = srcSpanEnd span
2640 -- -----------------------------------------------------------------------------
2641 -- Interactive evaluation
2643 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2644 -- filesystem and package database to find the corresponding 'Module',
2645 -- using the algorithm that is used for an @import@ declaration.
2646 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2647 findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
2649 dflags = hsc_dflags hsc_env
2650 this_pkg = thisPackage dflags
2653 Just pkg | fsToPackageId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
2654 res <- findImportedModule hsc_env mod_name maybe_pkg
2656 Found _ m -> return m
2657 err -> noModError dflags noSrcSpan mod_name err
2659 home <- lookupLoadedHomeModule mod_name
2662 Nothing -> liftIO $ do
2663 res <- findImportedModule hsc_env mod_name maybe_pkg
2665 Found loc m | modulePackageId m /= this_pkg -> return m
2666 | otherwise -> modNotLoadedError m loc
2667 err -> noModError dflags noSrcSpan mod_name err
2669 modNotLoadedError :: Module -> ModLocation -> IO a
2670 modNotLoadedError m loc = ghcError $ CmdLineError $ showSDoc $
2671 text "module is not loaded:" <+>
2672 quotes (ppr (moduleName m)) <+>
2673 parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
2675 -- | Like 'findModule', but differs slightly when the module refers to
2676 -- a source file, and the file has not been loaded via 'load'. In
2677 -- this case, 'findModule' will throw an error (module not loaded),
2678 -- but 'lookupModule' will check to see whether the module can also be
2679 -- found in a package, and if so, that package 'Module' will be
2680 -- returned. If not, the usual module-not-found error will be thrown.
2682 lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2683 lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
2684 lookupModule mod_name Nothing = withSession $ \hsc_env -> do
2685 home <- lookupLoadedHomeModule mod_name
2688 Nothing -> liftIO $ do
2689 res <- findExposedPackageModule hsc_env mod_name Nothing
2691 Found _ m -> return m
2692 err -> noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
2694 lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
2695 lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
2696 case lookupUFM (hsc_HPT hsc_env) mod_name of
2697 Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
2698 _not_a_home_module -> return Nothing
2701 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2702 getHistorySpan h = withSession $ \hsc_env ->
2703 return$ InteractiveEval.getHistorySpan hsc_env h
2705 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
2706 obtainTermFromVal bound force ty a =
2707 withSession $ \hsc_env ->
2708 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
2710 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
2711 obtainTermFromId bound force id =
2712 withSession $ \hsc_env ->
2713 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id