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.obtainTermFromId, GHC.obtainTermFromVal, 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,
201 -- * Token stream manipulations
203 getTokenStream, getRichTokenStream,
204 showRichTokenStream, addSourceToTokens,
214 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
215 * what StaticFlags should we expose, if any?
218 #include "HsVersions.h"
221 import qualified Linker
222 import Linker ( HValue )
226 import InteractiveEval
231 import TcRnTypes hiding (LIE)
232 import TcRnMonad ( initIfaceCheck )
236 import qualified HsSyn -- hack as we want to reexport the whole module
237 import HsSyn hiding ((<.>))
238 import Type hiding (typeKind)
239 import TcType hiding (typeKind)
242 import TysPrim ( alphaTyVars )
247 import Name hiding ( varName )
248 import OccName ( parenSymOcc )
249 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
251 import FamInstEnv ( emptyFamInstEnv )
255 import DriverPipeline
256 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
262 import StaticFlagParser
263 import qualified StaticFlags
264 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
273 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
277 import StringBuffer ( StringBuffer, hGetStringBuffer, nextChar )
280 import Maybes ( expectJust, mapCatMaybes )
282 import HaddockLex ( tokenise )
286 import Control.Concurrent
287 import System.Directory ( getModificationTime, doesFileExist,
288 getCurrentDirectory )
291 import qualified Data.List as List
293 import System.Exit ( exitWith, ExitCode(..) )
294 import System.Time ( ClockTime, getClockTime )
297 import System.FilePath
299 import System.IO.Error ( try, isDoesNotExistError )
300 #if __GLASGOW_HASKELL__ >= 609
301 import Data.Typeable (cast)
303 import Prelude hiding (init)
306 -- -----------------------------------------------------------------------------
307 -- Exception handlers
309 -- | Install some default exception handlers and run the inner computation.
310 -- Unless you want to handle exceptions yourself, you should wrap this around
311 -- the top level of your program. The default handlers output the error
312 -- message(s) to stderr and exit cleanly.
313 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
314 defaultErrorHandler dflags inner =
315 -- top-level exception handler: any unrecognised exception is a compiler bug.
316 #if __GLASGOW_HASKELL__ < 609
317 ghandle (\exception -> liftIO $ do
320 -- an IO exception probably isn't our fault, so don't panic
322 fatalErrorMsg dflags (text (show exception))
323 AsyncException StackOverflow ->
324 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
325 ExitException _ -> throw exception
327 fatalErrorMsg dflags (text (show (Panic (show exception))))
328 exitWith (ExitFailure 1)
331 ghandle (\(SomeException exception) -> liftIO $ do
333 case cast exception of
334 -- an IO exception probably isn't our fault, so don't panic
335 Just (ioe :: IOException) ->
336 fatalErrorMsg dflags (text (show ioe))
337 _ -> case cast exception of
338 Just StackOverflow ->
339 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
340 _ -> case cast exception of
341 Just (ex :: ExitCode) -> throw ex
344 (text (show (Panic (show exception))))
345 exitWith (ExitFailure 1)
349 -- program errors: messages with locations attached. Sometimes it is
350 -- convenient to just throw these as exceptions.
353 printBagOfErrors dflags (unitBag em)
354 exitWith (ExitFailure 1)) $
356 -- error messages propagated as exceptions
361 PhaseFailed _ code -> exitWith code
362 Interrupted -> exitWith (ExitFailure 1)
363 _ -> do fatalErrorMsg dflags (text (show ge))
364 exitWith (ExitFailure 1)
368 -- | Install a default cleanup handler to remove temporary files deposited by
369 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
370 -- want to override the error handling, but still get the ordinary cleanup
372 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
373 DynFlags -> m a -> m a
374 defaultCleanupHandler dflags inner =
375 -- make sure we clean up after ourselves
378 cleanTempFiles dflags
381 -- exceptions will be blocked while we clean the temporary files,
382 -- so there shouldn't be any difficulty if we receive further
385 -- | Print the error message and all warnings. Useful inside exception
386 -- handlers. Clears warnings after printing.
387 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
388 printExceptionAndWarnings err = do
389 let errs = srcErrorMessages err
391 dflags <- getSessionDynFlags
393 -- Empty errors means we failed due to -Werror. (Since this function
394 -- takes a source error as argument, we know for sure _some_ error
395 -- did indeed happen.)
397 printBagOfWarnings dflags warns
398 printBagOfErrors dflags (unitBag warnIsErrorMsg)
399 else liftIO $ printBagOfErrors dflags errs
402 -- | Print all accumulated warnings using 'log_action'.
403 printWarnings :: GhcMonad m => m ()
405 dflags <- getSessionDynFlags
407 liftIO $ printBagOfWarnings dflags warns
410 -- | Run function for the 'Ghc' monad.
412 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
413 -- to this function will create a new session which should not be shared among
416 -- Any errors not handled inside the 'Ghc' action are propagated as IO
419 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
420 -> Ghc a -- ^ The action to perform.
422 runGhc mb_top_dir ghc = do
423 wref <- newIORef emptyBag
424 ref <- newIORef undefined
425 let session = Session ref wref
426 flip unGhc session $ do
427 initGhcMonad mb_top_dir
429 -- XXX: unregister interrupt handlers here?
431 -- | Run function for 'GhcT' monad transformer.
433 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
434 -- to this function will create a new session which should not be shared among
437 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
438 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
439 -> GhcT m a -- ^ The action to perform.
441 runGhcT mb_top_dir ghct = do
442 wref <- liftIO $ newIORef emptyBag
443 ref <- liftIO $ newIORef undefined
444 let session = Session ref wref
445 flip unGhcT session $ do
446 initGhcMonad mb_top_dir
449 -- | Initialise a GHC session.
451 -- If you implement a custom 'GhcMonad' you must call this function in the
452 -- monad run function. It will initialise the session variable and clear all
455 -- The first argument should point to the directory where GHC's library files
456 -- reside. More precisely, this should be the output of @ghc --print-libdir@
457 -- of the version of GHC the module using this API is compiled with. For
458 -- portability, you should use the @ghc-paths@ package, available at
459 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
461 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
462 initGhcMonad mb_top_dir = do
464 main_thread <- liftIO $ myThreadId
465 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
466 liftIO $ installSignalHandlers
468 liftIO $ StaticFlags.initStaticOpts
470 dflags0 <- liftIO $ initDynFlags defaultDynFlags
471 dflags <- liftIO $ initSysTools mb_top_dir dflags0
472 env <- liftIO $ newHscEnv dflags
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 -- Parsing Haddock comments
626 parseHaddockComment :: String -> Either String (HsDoc RdrName)
627 parseHaddockComment string =
628 case parseHaddockParagraphs (tokenise string) of
632 -- -----------------------------------------------------------------------------
633 -- Loading the program
635 -- | Perform a dependency analysis starting from the current targets
636 -- and update the session with the new module graph.
637 depanal :: GhcMonad m =>
638 [ModuleName] -- ^ excluded modules
639 -> Bool -- ^ allow duplicate roots
641 depanal excluded_mods allow_dup_roots = do
642 hsc_env <- getSession
644 dflags = hsc_dflags hsc_env
645 targets = hsc_targets hsc_env
646 old_graph = hsc_mod_graph hsc_env
648 liftIO $ showPass dflags "Chasing dependencies"
649 liftIO $ debugTraceMsg dflags 2 (hcat [
650 text "Chasing modules from: ",
651 hcat (punctuate comma (map pprTarget targets))])
653 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
654 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
659 | LoadUpTo ModuleName
660 | LoadDependenciesOf ModuleName
662 -- | Try to load the program. Calls 'loadWithLogger' with the default
663 -- compiler that just immediately logs all warnings and errors.
664 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
666 loadWithLogger defaultWarnErrLogger how_much
668 -- | A function called to log warnings and errors.
669 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
671 defaultWarnErrLogger :: WarnErrLogger
672 defaultWarnErrLogger Nothing = printWarnings
673 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
675 -- | Try to load the program. If a Module is supplied, then just
676 -- attempt to load up to this target. If no Module is supplied,
677 -- then try to load all targets.
679 -- The first argument is a function that is called after compiling each
680 -- module to print wanrings and errors.
682 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
683 loadWithLogger logger how_much = do
684 -- Dependency analysis first. Note that this fixes the module graph:
685 -- even if we don't get a fully successful upsweep, the full module
686 -- graph is still retained in the Session. We can tell which modules
687 -- were successfully loaded by inspecting the Session's HPT.
688 mod_graph <- depanal [] False
689 load2 how_much mod_graph logger
691 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary] -> WarnErrLogger
693 load2 how_much mod_graph logger = do
695 hsc_env <- getSession
697 let hpt1 = hsc_HPT hsc_env
698 let dflags = hsc_dflags hsc_env
700 -- The "bad" boot modules are the ones for which we have
701 -- B.hs-boot in the module graph, but no B.hs
702 -- The downsweep should have ensured this does not happen
704 let all_home_mods = [ms_mod_name s
705 | s <- mod_graph, not (isBootSummary s)]
706 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
707 not (ms_mod_name s `elem` all_home_mods)]
708 ASSERT( null bad_boot_mods ) return ()
710 -- check that the module given in HowMuch actually exists, otherwise
711 -- topSortModuleGraph will bomb later.
712 let checkHowMuch (LoadUpTo m) = checkMod m
713 checkHowMuch (LoadDependenciesOf m) = checkMod m
717 | m `elem` all_home_mods = and_then
719 liftIO $ errorMsg dflags (text "no such module:" <+>
723 checkHowMuch how_much $ do
725 -- mg2_with_srcimps drops the hi-boot nodes, returning a
726 -- graph with cycles. Among other things, it is used for
727 -- backing out partially complete cycles following a failed
728 -- upsweep, and for removing from hpt all the modules
729 -- not in strict downwards closure, during calls to compile.
730 let mg2_with_srcimps :: [SCC ModSummary]
731 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
733 -- If we can determine that any of the {-# SOURCE #-} imports
734 -- are definitely unnecessary, then emit a warning.
735 warnUnnecessarySourceImports dflags mg2_with_srcimps
738 -- check the stability property for each module.
739 stable_mods@(stable_obj,stable_bco)
740 = checkStability hpt1 mg2_with_srcimps all_home_mods
742 -- prune bits of the HPT which are definitely redundant now,
744 pruned_hpt = pruneHomePackageTable hpt1
745 (flattenSCCs mg2_with_srcimps)
748 liftIO $ evaluate pruned_hpt
750 -- before we unload anything, make sure we don't leave an old
751 -- interactive context around pointing to dead bindings. Also,
752 -- write the pruned HPT to allow the old HPT to be GC'd.
753 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
754 hsc_HPT = pruned_hpt }
756 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
757 text "Stable BCO:" <+> ppr stable_bco)
759 -- Unload any modules which are going to be re-linked this time around.
760 let stable_linkables = [ linkable
761 | m <- stable_obj++stable_bco,
762 Just hmi <- [lookupUFM pruned_hpt m],
763 Just linkable <- [hm_linkable hmi] ]
764 liftIO $ unload hsc_env stable_linkables
766 -- We could at this point detect cycles which aren't broken by
767 -- a source-import, and complain immediately, but it seems better
768 -- to let upsweep_mods do this, so at least some useful work gets
769 -- done before the upsweep is abandoned.
770 --hPutStrLn stderr "after tsort:\n"
771 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
773 -- Now do the upsweep, calling compile for each module in
774 -- turn. Final result is version 3 of everything.
776 -- Topologically sort the module graph, this time including hi-boot
777 -- nodes, and possibly just including the portion of the graph
778 -- reachable from the module specified in the 2nd argument to load.
779 -- This graph should be cycle-free.
780 -- If we're restricting the upsweep to a portion of the graph, we
781 -- also want to retain everything that is still stable.
782 let full_mg :: [SCC ModSummary]
783 full_mg = topSortModuleGraph False mod_graph Nothing
785 maybe_top_mod = case how_much of
787 LoadDependenciesOf m -> Just m
790 partial_mg0 :: [SCC ModSummary]
791 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
793 -- LoadDependenciesOf m: we want the upsweep to stop just
794 -- short of the specified module (unless the specified module
797 | LoadDependenciesOf _mod <- how_much
798 = ASSERT( case last partial_mg0 of
799 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
800 List.init partial_mg0
806 | AcyclicSCC ms <- full_mg,
807 ms_mod_name ms `elem` stable_obj++stable_bco,
808 ms_mod_name ms `notElem` [ ms_mod_name ms' |
809 AcyclicSCC ms' <- partial_mg ] ]
811 mg = stable_mg ++ partial_mg
813 -- clean up between compilations
814 let cleanup = cleanTempFilesExcept dflags
815 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
817 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
819 (upsweep_ok, hsc_env1, modsUpswept)
821 (hsc_env { hsc_HPT = emptyHomePackageTable })
822 pruned_hpt stable_mods cleanup mg
824 -- Make modsDone be the summaries for each home module now
825 -- available; this should equal the domain of hpt3.
826 -- Get in in a roughly top .. bottom order (hence reverse).
828 let modsDone = reverse modsUpswept
830 -- Try and do linking in some form, depending on whether the
831 -- upsweep was completely or only partially successful.
833 if succeeded upsweep_ok
836 -- Easy; just relink it all.
837 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
839 -- Clean up after ourselves
840 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
842 -- Issue a warning for the confusing case where the user
843 -- said '-o foo' but we're not going to do any linking.
844 -- We attempt linking if either (a) one of the modules is
845 -- called Main, or (b) the user said -no-hs-main, indicating
846 -- that main() is going to come from somewhere else.
848 let ofile = outputFile dflags
849 let no_hs_main = dopt Opt_NoHsMain dflags
851 main_mod = mainModIs dflags
852 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
853 do_linking = a_root_is_Main || no_hs_main
855 when (ghcLink dflags == LinkBinary
856 && isJust ofile && not do_linking) $
857 liftIO $ debugTraceMsg dflags 1 $
858 text ("Warning: output was redirected with -o, " ++
859 "but no output will be generated\n" ++
860 "because there is no " ++
861 moduleNameString (moduleName main_mod) ++ " module.")
863 -- link everything together
864 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
866 loadFinish Succeeded linkresult hsc_env1
869 -- Tricky. We need to back out the effects of compiling any
870 -- half-done cycles, both so as to clean up the top level envs
871 -- and to avoid telling the interactive linker to link them.
872 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
875 = map ms_mod modsDone
876 let mods_to_zap_names
877 = findPartiallyCompletedCycles modsDone_names
880 = filter ((`notElem` mods_to_zap_names).ms_mod)
883 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
886 -- Clean up after ourselves
887 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
889 -- there should be no Nothings where linkables should be, now
890 ASSERT(all (isJust.hm_linkable)
891 (eltsUFM (hsc_HPT hsc_env))) do
893 -- Link everything together
894 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
896 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
897 loadFinish Failed linkresult hsc_env4
899 -- Finish up after a load.
901 -- If the link failed, unload everything and return.
902 loadFinish :: GhcMonad m =>
903 SuccessFlag -> SuccessFlag -> HscEnv
905 loadFinish _all_ok Failed hsc_env
906 = do liftIO $ unload hsc_env []
907 modifySession $ \_ -> discardProg hsc_env
910 -- Empty the interactive context and set the module context to the topmost
911 -- newly loaded module, or the Prelude if none were loaded.
912 loadFinish all_ok Succeeded hsc_env
913 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
917 -- Forget the current program, but retain the persistent info in HscEnv
918 discardProg :: HscEnv -> HscEnv
920 = hsc_env { hsc_mod_graph = emptyMG,
921 hsc_IC = emptyInteractiveContext,
922 hsc_HPT = emptyHomePackageTable }
924 -- used to fish out the preprocess output files for the purposes of
925 -- cleaning up. The preprocessed file *might* be the same as the
926 -- source file, but that doesn't do any harm.
927 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
928 ppFilesFromSummaries summaries = map ms_hspp_file summaries
930 -- -----------------------------------------------------------------------------
932 class ParsedMod m where
933 modSummary :: m -> ModSummary
934 parsedSource :: m -> ParsedSource
936 class ParsedMod m => TypecheckedMod m where
937 renamedSource :: m -> Maybe RenamedSource
938 typecheckedSource :: m -> TypecheckedSource
939 moduleInfo :: m -> ModuleInfo
940 tm_internals :: m -> (TcGblEnv, ModDetails)
941 -- ToDo: improvements that could be made here:
942 -- if the module succeeded renaming but not typechecking,
943 -- we can still get back the GlobalRdrEnv and exports, so
944 -- perhaps the ModuleInfo should be split up into separate
947 class TypecheckedMod m => DesugaredMod m where
948 coreModule :: m -> ModGuts
950 -- | The result of successful parsing.
952 ParsedModule { pm_mod_summary :: ModSummary
953 , pm_parsed_source :: ParsedSource }
955 instance ParsedMod ParsedModule where
956 modSummary m = pm_mod_summary m
957 parsedSource m = pm_parsed_source m
959 -- | The result of successful typechecking. It also contains the parser
961 data TypecheckedModule =
962 TypecheckedModule { tm_parsed_module :: ParsedModule
963 , tm_renamed_source :: Maybe RenamedSource
964 , tm_typechecked_source :: TypecheckedSource
965 , tm_checked_module_info :: ModuleInfo
966 , tm_internals_ :: (TcGblEnv, ModDetails)
969 instance ParsedMod TypecheckedModule where
970 modSummary m = modSummary (tm_parsed_module m)
971 parsedSource m = parsedSource (tm_parsed_module m)
973 instance TypecheckedMod TypecheckedModule where
974 renamedSource m = tm_renamed_source m
975 typecheckedSource m = tm_typechecked_source m
976 moduleInfo m = tm_checked_module_info m
977 tm_internals m = tm_internals_ m
979 -- | The result of successful desugaring (i.e., translation to core). Also
980 -- contains all the information of a typechecked module.
981 data DesugaredModule =
982 DesugaredModule { dm_typechecked_module :: TypecheckedModule
983 , dm_core_module :: ModGuts
986 instance ParsedMod DesugaredModule where
987 modSummary m = modSummary (dm_typechecked_module m)
988 parsedSource m = parsedSource (dm_typechecked_module m)
990 instance TypecheckedMod DesugaredModule where
991 renamedSource m = renamedSource (dm_typechecked_module m)
992 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
993 moduleInfo m = moduleInfo (dm_typechecked_module m)
994 tm_internals m = tm_internals_ (dm_typechecked_module m)
996 instance DesugaredMod DesugaredModule where
997 coreModule m = dm_core_module m
999 type ParsedSource = Located (HsModule RdrName)
1000 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
1001 Maybe (HsDoc Name), HaddockModInfo Name)
1002 type TypecheckedSource = LHsBinds Id
1005 -- - things that aren't in the output of the typechecker right now:
1006 -- - the export list
1008 -- - type signatures
1009 -- - type/data/newtype declarations
1010 -- - class declarations
1012 -- - extra things in the typechecker's output:
1013 -- - default methods are turned into top-level decls.
1014 -- - dictionary bindings
1016 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1017 getModSummary mod = do
1018 mg <- liftM hsc_mod_graph getSession
1019 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
1020 [] -> throw $ mkApiErr (text "Module not part of module graph")
1023 -- | Parse a module.
1025 -- Throws a 'SourceError' on parse error.
1026 parseModule :: GhcMonad m => ModuleName -> m ParsedModule
1027 parseModule mod = do
1028 ms <- getModSummary mod
1029 hsc_env0 <- getSession
1030 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1031 rdr_module <- parseFile hsc_env ms
1032 return (ParsedModule ms rdr_module)
1034 -- | Typecheck and rename a parsed module.
1036 -- Throws a 'SourceError' if either fails.
1037 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1038 typecheckModule pmod = do
1039 let ms = modSummary pmod
1040 hsc_env0 <- getSession
1041 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1042 (tc_gbl_env, rn_info)
1043 <- typecheckRenameModule hsc_env ms (parsedSource pmod)
1044 details <- liftIO $ makeSimpleDetails hsc_env tc_gbl_env
1047 tm_internals_ = (tc_gbl_env, details),
1048 tm_parsed_module = pmod,
1049 tm_renamed_source = rn_info,
1050 tm_typechecked_source = tcg_binds tc_gbl_env,
1051 tm_checked_module_info =
1053 minf_type_env = md_types details,
1054 minf_exports = availsToNameSet $ md_exports details,
1055 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1056 minf_instances = md_insts details
1058 ,minf_modBreaks = emptyModBreaks
1062 -- | Desugar a typechecked module.
1063 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1064 desugarModule tcm = do
1065 let ms = modSummary tcm
1066 hsc_env0 <- getSession
1067 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1068 let (tcg, _) = tm_internals tcm
1069 guts <- deSugarModule hsc_env ms tcg
1072 dm_typechecked_module = tcm,
1073 dm_core_module = guts
1076 -- | Load a module. Input doesn't need to be desugared.
1078 -- XXX: Describe usage.
1079 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1081 let ms = modSummary tcm
1082 let mod = ms_mod_name ms
1083 hsc_env0 <- getSession
1084 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1085 let (tcg, details) = tm_internals tcm
1086 (iface,_) <- liftIO $ makeSimpleIface hsc_env Nothing tcg details
1087 let mod_info = HomeModInfo {
1089 hm_details = details,
1090 hm_linkable = Nothing }
1091 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
1092 modifySession $ \_ -> hsc_env0{ hsc_HPT = hpt_new }
1095 -- | This is the way to get access to the Core bindings corresponding
1096 -- to a module. 'compileToCore' parses, typechecks, and
1097 -- desugars the module, then returns the resulting Core module (consisting of
1098 -- the module name, type declarations, and function declarations) if
1100 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1101 compileToCoreModule = compileCore False
1103 -- | Like compileToCoreModule, but invokes the simplifier, so
1104 -- as to return simplified and tidied Core.
1105 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1106 compileToCoreSimplified = compileCore True
1108 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1109 -- bindings, but for most purposes, you probably want to call
1110 -- compileToCoreModule.
1111 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1112 compileToCore fn = do
1113 mod <- compileToCoreModule session fn
1114 return $ cm_binds mod
1116 -- | Takes a CoreModule and compiles the bindings therein
1117 -- to object code. The first argument is a bool flag indicating
1118 -- whether to run the simplifier.
1119 -- The resulting .o, .hi, and executable files, if any, are stored in the
1120 -- current directory, and named according to the module name.
1121 -- Returns True iff compilation succeeded.
1122 -- This has only so far been tested with a single self-contained module.
1123 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1124 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1125 hscEnv <- getSession
1126 dflags <- getSessionDynFlags
1127 currentTime <- liftIO $ getClockTime
1128 cwd <- liftIO $ getCurrentDirectory
1129 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1130 ((moduleNameSlashes . moduleName) mName)
1132 let modSummary = ModSummary { ms_mod = mName,
1133 ms_hsc_src = ExtCoreFile,
1134 ms_location = modLocation,
1135 -- By setting the object file timestamp to Nothing,
1136 -- we always force recompilation, which is what we
1137 -- want. (Thus it doesn't matter what the timestamp
1138 -- for the (nonexistent) source file is.)
1139 ms_hs_date = currentTime,
1140 ms_obj_date = Nothing,
1141 -- Only handling the single-module case for now, so no imports.
1146 ms_hspp_opts = dflags,
1147 ms_hspp_buf = Nothing
1150 ioMsgMaybe $ flip evalComp (CompState{ compHscEnv=hscEnv,
1151 compModSummary=modSummary,
1152 compOldIface=Nothing}) $
1153 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1154 | otherwise = return mod_guts
1155 in maybe_simplify (mkModGuts cm)
1161 -- Makes a "vanilla" ModGuts.
1162 mkModGuts :: CoreModule -> ModGuts
1163 mkModGuts coreModule = ModGuts {
1164 mg_module = cm_module coreModule,
1167 mg_deps = noDependencies,
1168 mg_dir_imps = emptyModuleEnv,
1169 mg_used_names = emptyNameSet,
1170 mg_rdr_env = emptyGlobalRdrEnv,
1171 mg_fix_env = emptyFixityEnv,
1172 mg_types = emptyTypeEnv,
1176 mg_binds = cm_binds coreModule,
1177 mg_foreign = NoStubs,
1178 mg_warns = NoWarnings,
1179 mg_hpc_info = emptyHpcInfo False,
1180 mg_modBreaks = emptyModBreaks,
1181 mg_vect_info = noVectInfo,
1182 mg_inst_env = emptyInstEnv,
1183 mg_fam_inst_env = emptyFamInstEnv
1186 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1187 compileCore simplify fn = do
1188 -- First, set the target to the desired filename
1189 target <- guessTarget fn Nothing
1192 -- Then find dependencies
1193 modGraph <- depanal [] True
1194 case find ((== fn) . msHsFilePath) modGraph of
1195 Just modSummary -> do
1196 -- Now we have the module name;
1197 -- parse, typecheck and desugar the module
1198 let mod = ms_mod_name modSummary
1199 mod_guts <- coreModule `fmap`
1200 (desugarModule =<< typecheckModule =<< parseModule mod)
1201 liftM gutsToCoreModule $
1204 -- If simplify is true: simplify (hscSimplify), then tidy
1206 hsc_env <- getSession
1207 simpl_guts <- ioMsg $ evalComp (hscSimplify mod_guts)
1209 compHscEnv = hsc_env,
1210 compModSummary = modSummary,
1211 compOldIface = Nothing})
1212 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1213 return $ Left tidy_guts
1215 return $ Right mod_guts
1217 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1218 module dependency graph"
1219 where -- two versions, based on whether we simplify (thus run tidyProgram,
1220 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1221 -- we just have a ModGuts.
1222 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1223 gutsToCoreModule (Left (cg, md)) = CoreModule {
1224 cm_module = cg_module cg, cm_types = md_types md,
1225 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1227 gutsToCoreModule (Right mg) = CoreModule {
1228 cm_module = mg_module mg, cm_types = mg_types mg,
1229 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1232 -- ---------------------------------------------------------------------------
1235 unload :: HscEnv -> [Linkable] -> IO ()
1236 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1237 = case ghcLink (hsc_dflags hsc_env) of
1239 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1241 LinkInMemory -> panic "unload: no interpreter"
1242 -- urgh. avoid warnings:
1243 hsc_env stable_linkables
1247 -- -----------------------------------------------------------------------------
1251 Stability tells us which modules definitely do not need to be recompiled.
1252 There are two main reasons for having stability:
1254 - avoid doing a complete upsweep of the module graph in GHCi when
1255 modules near the bottom of the tree have not changed.
1257 - to tell GHCi when it can load object code: we can only load object code
1258 for a module when we also load object code fo all of the imports of the
1259 module. So we need to know that we will definitely not be recompiling
1260 any of these modules, and we can use the object code.
1262 The stability check is as follows. Both stableObject and
1263 stableBCO are used during the upsweep phase later.
1266 stable m = stableObject m || stableBCO m
1269 all stableObject (imports m)
1270 && old linkable does not exist, or is == on-disk .o
1271 && date(on-disk .o) > date(.hs)
1274 all stable (imports m)
1275 && date(BCO) > date(.hs)
1278 These properties embody the following ideas:
1280 - if a module is stable, then:
1282 - if it has been compiled in a previous pass (present in HPT)
1283 then it does not need to be compiled or re-linked.
1285 - if it has not been compiled in a previous pass,
1286 then we only need to read its .hi file from disk and
1287 link it to produce a 'ModDetails'.
1289 - if a modules is not stable, we will definitely be at least
1290 re-linking, and possibly re-compiling it during the 'upsweep'.
1291 All non-stable modules can (and should) therefore be unlinked
1292 before the 'upsweep'.
1294 - Note that objects are only considered stable if they only depend
1295 on other objects. We can't link object code against byte code.
1299 :: HomePackageTable -- HPT from last compilation
1300 -> [SCC ModSummary] -- current module graph (cyclic)
1301 -> [ModuleName] -- all home modules
1302 -> ([ModuleName], -- stableObject
1303 [ModuleName]) -- stableBCO
1305 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1307 checkSCC (stable_obj, stable_bco) scc0
1308 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1309 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1310 | otherwise = (stable_obj, stable_bco)
1312 scc = flattenSCC scc0
1313 scc_mods = map ms_mod_name scc
1314 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1316 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1317 -- all imports outside the current SCC, but in the home pkg
1319 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1320 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1324 && all object_ok scc
1327 and (zipWith (||) stable_obj_imps stable_bco_imps)
1331 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1335 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1336 Just hmi | Just l <- hm_linkable hmi
1337 -> isObjectLinkable l && t == linkableTime l
1339 -- why '>=' rather than '>' above? If the filesystem stores
1340 -- times to the nearset second, we may occasionally find that
1341 -- the object & source have the same modification time,
1342 -- especially if the source was automatically generated
1343 -- and compiled. Using >= is slightly unsafe, but it matches
1344 -- make's behaviour.
1347 = case lookupUFM hpt (ms_mod_name ms) of
1348 Just hmi | Just l <- hm_linkable hmi ->
1349 not (isObjectLinkable l) &&
1350 linkableTime l >= ms_hs_date ms
1353 ms_allimps :: ModSummary -> [ModuleName]
1354 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1356 -- -----------------------------------------------------------------------------
1358 -- | Prune the HomePackageTable
1360 -- Before doing an upsweep, we can throw away:
1362 -- - For non-stable modules:
1363 -- - all ModDetails, all linked code
1364 -- - all unlinked code that is out of date with respect to
1367 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1368 -- space at the end of the upsweep, because the topmost ModDetails of the
1369 -- old HPT holds on to the entire type environment from the previous
1372 pruneHomePackageTable
1375 -> ([ModuleName],[ModuleName])
1378 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1381 | is_stable modl = hmi'
1382 | otherwise = hmi'{ hm_details = emptyModDetails }
1384 modl = moduleName (mi_module (hm_iface hmi))
1385 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1386 = hmi{ hm_linkable = Nothing }
1389 where ms = expectJust "prune" (lookupUFM ms_map modl)
1391 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1393 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1395 -- -----------------------------------------------------------------------------
1397 -- Return (names of) all those in modsDone who are part of a cycle
1398 -- as defined by theGraph.
1399 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1400 findPartiallyCompletedCycles modsDone theGraph
1404 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1405 chew ((CyclicSCC vs):rest)
1406 = let names_in_this_cycle = nub (map ms_mod vs)
1408 = nub ([done | done <- modsDone,
1409 done `elem` names_in_this_cycle])
1410 chewed_rest = chew rest
1412 if notNull mods_in_this_cycle
1413 && length mods_in_this_cycle < length names_in_this_cycle
1414 then mods_in_this_cycle ++ chewed_rest
1417 -- -----------------------------------------------------------------------------
1421 -- This is where we compile each module in the module graph, in a pass
1422 -- from the bottom to the top of the graph.
1424 -- There better had not be any cyclic groups here -- we check for them.
1428 WarnErrLogger -- ^ Called to print warnings and errors.
1429 -> HscEnv -- ^ Includes initially-empty HPT
1430 -> HomePackageTable -- ^ HPT from last time round (pruned)
1431 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1432 -> IO () -- ^ How to clean up unwanted tmp files
1433 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1435 HscEnv, -- With an updated HPT
1436 [ModSummary]) -- Mods which succeeded
1438 upsweep logger hsc_env old_hpt stable_mods cleanup sccs = do
1439 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1440 return (res, hsc_env, reverse done)
1443 upsweep' hsc_env _old_hpt done
1445 = return (Succeeded, hsc_env, done)
1447 upsweep' hsc_env _old_hpt done
1448 (CyclicSCC ms:_) _ _
1449 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1450 return (Failed, hsc_env, done)
1452 upsweep' hsc_env old_hpt done
1453 (AcyclicSCC mod:mods) mod_index nmods
1454 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1455 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1456 -- (moduleEnvElts (hsc_HPT hsc_env)))
1459 <- handleSourceError
1460 (\err -> do logger (Just err); return Nothing) $ do
1461 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1463 logger Nothing -- log warnings
1464 return (Just mod_info)
1466 liftIO cleanup -- Remove unwanted tmp files between compilations
1469 Nothing -> return (Failed, hsc_env, done)
1471 let this_mod = ms_mod_name mod
1473 -- Add new info to hsc_env
1474 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1475 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1477 -- Space-saving: delete the old HPT entry
1478 -- for mod BUT if mod is a hs-boot
1479 -- node, don't delete it. For the
1480 -- interface, the HPT entry is probaby for the
1481 -- main Haskell source file. Deleting it
1482 -- would force the real module to be recompiled
1484 old_hpt1 | isBootSummary mod = old_hpt
1485 | otherwise = delFromUFM old_hpt this_mod
1489 -- fixup our HomePackageTable after we've finished compiling
1490 -- a mutually-recursive loop. See reTypecheckLoop, below.
1491 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1493 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1495 -- | Compile a single module. Always produce a Linkable for it if
1496 -- successful. If no compilation happened, return the old Linkable.
1497 upsweep_mod :: GhcMonad m =>
1500 -> ([ModuleName],[ModuleName])
1502 -> Int -- index of module
1503 -> Int -- total number of modules
1506 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1508 this_mod_name = ms_mod_name summary
1509 this_mod = ms_mod summary
1510 mb_obj_date = ms_obj_date summary
1511 obj_fn = ml_obj_file (ms_location summary)
1512 hs_date = ms_hs_date summary
1514 is_stable_obj = this_mod_name `elem` stable_obj
1515 is_stable_bco = this_mod_name `elem` stable_bco
1517 old_hmi = lookupUFM old_hpt this_mod_name
1519 -- We're using the dflags for this module now, obtained by
1520 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1521 dflags = ms_hspp_opts summary
1522 prevailing_target = hscTarget (hsc_dflags hsc_env)
1523 local_target = hscTarget dflags
1525 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1526 -- we don't do anything dodgy: these should only work to change
1527 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1528 -- end up trying to link object code to byte code.
1529 target = if prevailing_target /= local_target
1530 && (not (isObjectTarget prevailing_target)
1531 || not (isObjectTarget local_target))
1532 then prevailing_target
1535 -- store the corrected hscTarget into the summary
1536 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1538 -- The old interface is ok if
1539 -- a) we're compiling a source file, and the old HPT
1540 -- entry is for a source file
1541 -- b) we're compiling a hs-boot file
1542 -- Case (b) allows an hs-boot file to get the interface of its
1543 -- real source file on the second iteration of the compilation
1544 -- manager, but that does no harm. Otherwise the hs-boot file
1545 -- will always be recompiled
1550 Just hm_info | isBootSummary summary -> Just iface
1551 | not (mi_boot iface) -> Just iface
1552 | otherwise -> Nothing
1554 iface = hm_iface hm_info
1556 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1557 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1559 compile_it_discard_iface :: GhcMonad m =>
1560 Maybe Linkable -> m HomeModInfo
1561 compile_it_discard_iface
1562 = compile hsc_env summary' mod_index nmods Nothing
1568 -- Regardless of whether we're generating object code or
1569 -- byte code, we can always use an existing object file
1570 -- if it is *stable* (see checkStability).
1571 | is_stable_obj, isJust old_hmi ->
1572 let Just hmi = old_hmi in
1574 -- object is stable, and we have an entry in the
1575 -- old HPT: nothing to do
1577 | is_stable_obj, isNothing old_hmi -> do
1578 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1579 (expectJust "upsweep1" mb_obj_date)
1580 compile_it (Just linkable)
1581 -- object is stable, but we need to load the interface
1582 -- off disk to make a HMI.
1586 ASSERT(isJust old_hmi) -- must be in the old_hpt
1587 let Just hmi = old_hmi in
1589 -- BCO is stable: nothing to do
1591 | Just hmi <- old_hmi,
1592 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1593 linkableTime l >= ms_hs_date summary ->
1595 -- we have an old BCO that is up to date with respect
1596 -- to the source: do a recompilation check as normal.
1600 -- no existing code at all: we must recompile.
1602 -- When generating object code, if there's an up-to-date
1603 -- object file on the disk, then we can use it.
1604 -- However, if the object file is new (compared to any
1605 -- linkable we had from a previous compilation), then we
1606 -- must discard any in-memory interface, because this
1607 -- means the user has compiled the source file
1608 -- separately and generated a new interface, that we must
1609 -- read from the disk.
1611 obj | isObjectTarget obj,
1612 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1615 | Just l <- hm_linkable hmi,
1616 isObjectLinkable l && linkableTime l == obj_date
1617 -> compile_it (Just l)
1619 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1620 compile_it_discard_iface (Just linkable)
1627 -- Filter modules in the HPT
1628 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1629 retainInTopLevelEnvs keep_these hpt
1630 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1632 , let mb_mod_info = lookupUFM hpt mod
1633 , isJust mb_mod_info ]
1635 -- ---------------------------------------------------------------------------
1636 -- Typecheck module loops
1639 See bug #930. This code fixes a long-standing bug in --make. The
1640 problem is that when compiling the modules *inside* a loop, a data
1641 type that is only defined at the top of the loop looks opaque; but
1642 after the loop is done, the structure of the data type becomes
1645 The difficulty is then that two different bits of code have
1646 different notions of what the data type looks like.
1648 The idea is that after we compile a module which also has an .hs-boot
1649 file, we re-generate the ModDetails for each of the modules that
1650 depends on the .hs-boot file, so that everyone points to the proper
1651 TyCons, Ids etc. defined by the real module, not the boot module.
1652 Fortunately re-generating a ModDetails from a ModIface is easy: the
1653 function TcIface.typecheckIface does exactly that.
1655 Picking the modules to re-typecheck is slightly tricky. Starting from
1656 the module graph consisting of the modules that have already been
1657 compiled, we reverse the edges (so they point from the imported module
1658 to the importing module), and depth-first-search from the .hs-boot
1659 node. This gives us all the modules that depend transitively on the
1660 .hs-boot module, and those are exactly the modules that we need to
1663 Following this fix, GHC can compile itself with --make -O2.
1666 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1667 reTypecheckLoop hsc_env ms graph
1668 | not (isBootSummary ms) &&
1669 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1671 let mss = reachableBackwards (ms_mod_name ms) graph
1672 non_boot = filter (not.isBootSummary) mss
1673 debugTraceMsg (hsc_dflags hsc_env) 2 $
1674 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1675 typecheckLoop hsc_env (map ms_mod_name non_boot)
1679 this_mod = ms_mod ms
1681 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1682 typecheckLoop hsc_env mods = do
1684 fixIO $ \new_hpt -> do
1685 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1686 mds <- initIfaceCheck new_hsc_env $
1687 mapM (typecheckIface . hm_iface) hmis
1688 let new_hpt = addListToUFM old_hpt
1689 (zip mods [ hmi{ hm_details = details }
1690 | (hmi,details) <- zip hmis mds ])
1692 return hsc_env{ hsc_HPT = new_hpt }
1694 old_hpt = hsc_HPT hsc_env
1695 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1697 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1698 reachableBackwards mod summaries
1699 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1700 where -- the rest just sets up the graph:
1701 (graph, lookup_node) = moduleGraphNodes False summaries
1702 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1704 -- ---------------------------------------------------------------------------
1705 -- Topological sort of the module graph
1707 type SummaryNode = (ModSummary, Int, [Int])
1710 :: Bool -- Drop hi-boot nodes? (see below)
1714 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1715 -- The resulting list of strongly-connected-components is in topologically
1716 -- sorted order, starting with the module(s) at the bottom of the
1717 -- dependency graph (ie compile them first) and ending with the ones at
1720 -- Drop hi-boot nodes (first boolean arg)?
1722 -- False: treat the hi-boot summaries as nodes of the graph,
1723 -- so the graph must be acyclic
1725 -- True: eliminate the hi-boot nodes, and instead pretend
1726 -- the a source-import of Foo is an import of Foo
1727 -- The resulting graph has no hi-boot nodes, but can be cyclic
1729 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1730 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1732 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1734 initial_graph = case mb_root_mod of
1737 -- restrict the graph to just those modules reachable from
1738 -- the specified module. We do this by building a graph with
1739 -- the full set of nodes, and determining the reachable set from
1740 -- the specified node.
1741 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1742 | otherwise = ghcError (ProgramError "module does not exist")
1743 in graphFromEdgedVertices (seq root (reachableG graph root))
1745 summaryNodeKey :: SummaryNode -> Int
1746 summaryNodeKey (_, k, _) = k
1748 summaryNodeSummary :: SummaryNode -> ModSummary
1749 summaryNodeSummary (s, _, _) = s
1751 moduleGraphNodes :: Bool -> [ModSummary]
1752 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1753 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1755 numbered_summaries = zip summaries [1..]
1757 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1758 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1760 lookup_key :: HscSource -> ModuleName -> Maybe Int
1761 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1763 node_map :: NodeMap SummaryNode
1764 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1765 | node@(s, _, _) <- nodes ]
1767 -- We use integers as the keys for the SCC algorithm
1768 nodes :: [SummaryNode]
1769 nodes = [ (s, key, out_keys)
1770 | (s, key) <- numbered_summaries
1771 -- Drop the hi-boot ones if told to do so
1772 , not (isBootSummary s && drop_hs_boot_nodes)
1773 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1774 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1775 (-- see [boot-edges] below
1776 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1778 else case lookup_key HsBootFile (ms_mod_name s) of
1782 -- [boot-edges] if this is a .hs and there is an equivalent
1783 -- .hs-boot, add a link from the former to the latter. This
1784 -- has the effect of detecting bogus cases where the .hs-boot
1785 -- depends on the .hs, by introducing a cycle. Additionally,
1786 -- it ensures that we will always process the .hs-boot before
1787 -- the .hs, and so the HomePackageTable will always have the
1788 -- most up to date information.
1790 -- Drop hs-boot nodes by using HsSrcFile as the key
1791 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1792 | otherwise = HsBootFile
1794 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1795 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1796 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1797 -- the IsBootInterface parameter True; else False
1800 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1801 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1803 msKey :: ModSummary -> NodeKey
1804 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1806 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1807 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1809 nodeMapElts :: NodeMap a -> [a]
1810 nodeMapElts = eltsFM
1812 -- | If there are {-# SOURCE #-} imports between strongly connected
1813 -- components in the topological sort, then those imports can
1814 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1815 -- were necessary, then the edge would be part of a cycle.
1816 warnUnnecessarySourceImports :: GhcMonad m => DynFlags -> [SCC ModSummary] -> m ()
1817 warnUnnecessarySourceImports dflags sccs =
1818 liftIO $ printBagOfWarnings dflags (listToBag (concatMap (check.flattenSCC) sccs))
1820 let mods_in_this_cycle = map ms_mod_name ms in
1821 [ warn i | m <- ms, i <- ms_srcimps m,
1822 unLoc i `notElem` mods_in_this_cycle ]
1824 warn :: Located ModuleName -> WarnMsg
1827 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1828 <+> quotes (ppr mod))
1830 -----------------------------------------------------------------------------
1831 -- Downsweep (dependency analysis)
1833 -- Chase downwards from the specified root set, returning summaries
1834 -- for all home modules encountered. Only follow source-import
1837 -- We pass in the previous collection of summaries, which is used as a
1838 -- cache to avoid recalculating a module summary if the source is
1841 -- The returned list of [ModSummary] nodes has one node for each home-package
1842 -- module, plus one for any hs-boot files. The imports of these nodes
1843 -- are all there, including the imports of non-home-package modules.
1845 downsweep :: GhcMonad m =>
1847 -> [ModSummary] -- Old summaries
1848 -> [ModuleName] -- Ignore dependencies on these; treat
1849 -- them as if they were package modules
1850 -> Bool -- True <=> allow multiple targets to have
1851 -- the same module name; this is
1852 -- very useful for ghc -M
1854 -- The elts of [ModSummary] all have distinct
1855 -- (Modules, IsBoot) identifiers, unless the Bool is true
1856 -- in which case there can be repeats
1857 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1858 = do -- catch error messages and return them
1859 --handleErrMsg -- should be covered by GhcMonad now
1860 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1861 rootSummaries <- mapM getRootSummary roots
1862 let root_map = mkRootMap rootSummaries
1863 checkDuplicates root_map
1864 summs <- loop (concatMap msDeps rootSummaries) root_map
1867 roots = hsc_targets hsc_env
1869 old_summary_map :: NodeMap ModSummary
1870 old_summary_map = mkNodeMap old_summaries
1872 getRootSummary :: GhcMonad m => Target -> m ModSummary
1873 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1874 = do exists <- liftIO $ doesFileExist file
1876 then summariseFile hsc_env old_summaries file mb_phase
1877 obj_allowed maybe_buf
1878 else throwErrMsg $ mkPlainErrMsg noSrcSpan $
1879 text "can't find file:" <+> text file
1880 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1881 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1882 (L rootLoc modl) obj_allowed
1884 case maybe_summary of
1885 Nothing -> packageModErr modl
1888 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1890 -- In a root module, the filename is allowed to diverge from the module
1891 -- name, so we have to check that there aren't multiple root files
1892 -- defining the same module (otherwise the duplicates will be silently
1893 -- ignored, leading to confusing behaviour).
1894 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1895 checkDuplicates root_map
1896 | allow_dup_roots = return ()
1897 | null dup_roots = return ()
1898 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1900 dup_roots :: [[ModSummary]] -- Each at least of length 2
1901 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1903 loop :: GhcMonad m =>
1904 [(Located ModuleName,IsBootInterface)]
1905 -- Work list: process these modules
1906 -> NodeMap [ModSummary]
1907 -- Visited set; the range is a list because
1908 -- the roots can have the same module names
1909 -- if allow_dup_roots is True
1911 -- The result includes the worklist, except
1912 -- for those mentioned in the visited set
1913 loop [] done = return (concat (nodeMapElts done))
1914 loop ((wanted_mod, is_boot) : ss) done
1915 | Just summs <- lookupFM done key
1916 = if isSingleton summs then
1919 do { liftIO $ multiRootsErr summs; return [] }
1921 = do mb_s <- summariseModule hsc_env old_summary_map
1922 is_boot wanted_mod True
1925 Nothing -> loop ss done
1926 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1928 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1930 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1931 mkRootMap summaries = addListToFM_C (++) emptyFM
1932 [ (msKey s, [s]) | s <- summaries ]
1934 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1935 -- (msDeps s) returns the dependencies of the ModSummary s.
1936 -- A wrinkle is that for a {-# SOURCE #-} import we return
1937 -- *both* the hs-boot file
1938 -- *and* the source file
1939 -- as "dependencies". That ensures that the list of all relevant
1940 -- modules always contains B.hs if it contains B.hs-boot.
1941 -- Remember, this pass isn't doing the topological sort. It's
1942 -- just gathering the list of all relevant ModSummaries
1944 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1945 ++ [ (m,False) | m <- ms_imps s ]
1947 -----------------------------------------------------------------------------
1948 -- Summarising modules
1950 -- We have two types of summarisation:
1952 -- * Summarise a file. This is used for the root module(s) passed to
1953 -- cmLoadModules. The file is read, and used to determine the root
1954 -- module name. The module name may differ from the filename.
1956 -- * Summarise a module. We are given a module name, and must provide
1957 -- a summary. The finder is used to locate the file in which the module
1963 -> [ModSummary] -- old summaries
1964 -> FilePath -- source file name
1965 -> Maybe Phase -- start phase
1966 -> Bool -- object code allowed?
1967 -> Maybe (StringBuffer,ClockTime)
1970 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1971 -- we can use a cached summary if one is available and the
1972 -- source file hasn't changed, But we have to look up the summary
1973 -- by source file, rather than module name as we do in summarise.
1974 | Just old_summary <- findSummaryBySourceFile old_summaries file
1976 let location = ms_location old_summary
1978 -- return the cached summary if the source didn't change
1979 src_timestamp <- case maybe_buf of
1980 Just (_,t) -> return t
1981 Nothing -> liftIO $ getModificationTime file
1982 -- The file exists; we checked in getRootSummary above.
1983 -- If it gets removed subsequently, then this
1984 -- getModificationTime may fail, but that's the right
1987 if ms_hs_date old_summary == src_timestamp
1988 then do -- update the object-file timestamp
1990 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1991 || obj_allowed -- bug #1205
1992 then liftIO $ getObjTimestamp location False
1994 return old_summary{ ms_obj_date = obj_timestamp }
2002 let dflags = hsc_dflags hsc_env
2004 (dflags', hspp_fn, buf)
2005 <- preprocessFile hsc_env file mb_phase maybe_buf
2007 (srcimps,the_imps, L _ mod_name) <- liftIO $ getImports dflags' buf hspp_fn file
2009 -- Make a ModLocation for this file
2010 location <- liftIO $ mkHomeModLocation dflags mod_name file
2012 -- Tell the Finder cache where it is, so that subsequent calls
2013 -- to findModule will find it, even if it's not on any search path
2014 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2016 src_timestamp <- case maybe_buf of
2017 Just (_,t) -> return t
2018 Nothing -> liftIO $ getModificationTime file
2019 -- getMofificationTime may fail
2021 -- when the user asks to load a source file by name, we only
2022 -- use an object file if -fobject-code is on. See #1205.
2024 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2025 || obj_allowed -- bug #1205
2026 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2029 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2030 ms_location = location,
2031 ms_hspp_file = hspp_fn,
2032 ms_hspp_opts = dflags',
2033 ms_hspp_buf = Just buf,
2034 ms_srcimps = srcimps, ms_imps = the_imps,
2035 ms_hs_date = src_timestamp,
2036 ms_obj_date = obj_timestamp })
2038 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2039 findSummaryBySourceFile summaries file
2040 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2041 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2045 -- Summarise a module, and pick up source and timestamp.
2049 -> NodeMap ModSummary -- Map of old summaries
2050 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2051 -> Located ModuleName -- Imported module to be summarised
2052 -> Bool -- object code allowed?
2053 -> Maybe (StringBuffer, ClockTime)
2054 -> [ModuleName] -- Modules to exclude
2055 -> m (Maybe ModSummary) -- Its new summary
2057 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2058 obj_allowed maybe_buf excl_mods
2059 | wanted_mod `elem` excl_mods
2062 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2063 = do -- Find its new timestamp; all the
2064 -- ModSummaries in the old map have valid ml_hs_files
2065 let location = ms_location old_summary
2066 src_fn = expectJust "summariseModule" (ml_hs_file location)
2068 -- check the modification time on the source file, and
2069 -- return the cached summary if it hasn't changed. If the
2070 -- file has disappeared, we need to call the Finder again.
2072 Just (_,t) -> check_timestamp old_summary location src_fn t
2074 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2076 Right t -> check_timestamp old_summary location src_fn t
2077 Left e | isDoesNotExistError e -> find_it
2078 | otherwise -> liftIO $ ioError e
2080 | otherwise = find_it
2082 dflags = hsc_dflags hsc_env
2084 hsc_src = if is_boot then HsBootFile else HsSrcFile
2086 check_timestamp old_summary location src_fn src_timestamp
2087 | ms_hs_date old_summary == src_timestamp = do
2088 -- update the object-file timestamp
2089 obj_timestamp <- liftIO $
2090 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2091 || obj_allowed -- bug #1205
2092 then getObjTimestamp location is_boot
2094 return (Just old_summary{ ms_obj_date = obj_timestamp })
2096 -- source changed: re-summarise.
2097 new_summary location (ms_mod old_summary) src_fn src_timestamp
2100 -- Don't use the Finder's cache this time. If the module was
2101 -- previously a package module, it may have now appeared on the
2102 -- search path, so we want to consider it to be a home module. If
2103 -- the module was previously a home module, it may have moved.
2104 liftIO $ uncacheModule hsc_env wanted_mod
2105 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2108 | isJust (ml_hs_file location) ->
2110 just_found location mod
2112 -- Drop external-pkg
2113 ASSERT(modulePackageId mod /= thisPackage dflags)
2116 err -> liftIO $ noModError dflags loc wanted_mod err
2119 just_found location mod = do
2120 -- Adjust location to point to the hs-boot source file,
2121 -- hi file, object file, when is_boot says so
2122 let location' | is_boot = addBootSuffixLocn location
2123 | otherwise = location
2124 src_fn = expectJust "summarise2" (ml_hs_file location')
2126 -- Check that it exists
2127 -- It might have been deleted since the Finder last found it
2128 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2130 Nothing -> noHsFileErr loc src_fn
2131 Just t -> new_summary location' mod src_fn t
2134 new_summary location mod src_fn src_timestamp
2136 -- Preprocess the source file and get its imports
2137 -- The dflags' contains the OPTIONS pragmas
2138 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2139 (srcimps, the_imps, L mod_loc mod_name) <- liftIO $ getImports dflags' buf hspp_fn src_fn
2141 when (mod_name /= wanted_mod) $
2142 throwErrMsg $ mkPlainErrMsg mod_loc $
2143 text "File name does not match module name:"
2144 $$ text "Saw:" <+> quotes (ppr mod_name)
2145 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2147 -- Find the object timestamp, and return the summary
2148 obj_timestamp <- liftIO $
2149 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2150 || obj_allowed -- bug #1205
2151 then getObjTimestamp location is_boot
2154 return (Just (ModSummary { ms_mod = mod,
2155 ms_hsc_src = hsc_src,
2156 ms_location = location,
2157 ms_hspp_file = hspp_fn,
2158 ms_hspp_opts = dflags',
2159 ms_hspp_buf = Just buf,
2160 ms_srcimps = srcimps,
2162 ms_hs_date = src_timestamp,
2163 ms_obj_date = obj_timestamp }))
2166 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2167 getObjTimestamp location is_boot
2168 = if is_boot then return Nothing
2169 else modificationTimeIfExists (ml_obj_file location)
2172 preprocessFile :: GhcMonad m =>
2175 -> Maybe Phase -- ^ Starting phase
2176 -> Maybe (StringBuffer,ClockTime)
2177 -> m (DynFlags, FilePath, StringBuffer)
2178 preprocessFile hsc_env src_fn mb_phase Nothing
2180 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2181 buf <- liftIO $ hGetStringBuffer hspp_fn
2182 return (dflags', hspp_fn, buf)
2184 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2186 let dflags = hsc_dflags hsc_env
2187 -- case we bypass the preprocessing stage?
2189 local_opts = getOptions dflags buf src_fn
2191 (dflags', leftovers, warns)
2192 <- parseDynamicNoPackageFlags dflags local_opts
2193 liftIO $ checkProcessArgsResult leftovers -- XXX: throws exceptions
2194 liftIO $ handleFlagWarnings dflags' warns -- XXX: throws exceptions
2198 | Just (Unlit _) <- mb_phase = True
2199 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2200 -- note: local_opts is only required if there's no Unlit phase
2201 | dopt Opt_Cpp dflags' = True
2202 | dopt Opt_Pp dflags' = True
2205 when needs_preprocessing $
2206 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2208 return (dflags', src_fn, buf)
2211 -----------------------------------------------------------------------------
2213 -----------------------------------------------------------------------------
2215 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2216 -- ToDo: we don't have a proper line number for this error
2217 noModError dflags loc wanted_mod err
2218 = throwErrMsg $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2220 noHsFileErr :: SrcSpan -> String -> a
2221 noHsFileErr loc path
2222 = throwErrMsg $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2224 packageModErr :: ModuleName -> a
2226 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2227 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2229 multiRootsErr :: [ModSummary] -> IO ()
2230 multiRootsErr [] = panic "multiRootsErr"
2231 multiRootsErr summs@(summ1:_)
2232 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2233 text "module" <+> quotes (ppr mod) <+>
2234 text "is defined in multiple files:" <+>
2235 sep (map text files)
2238 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2240 cyclicModuleErr :: [ModSummary] -> SDoc
2242 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2243 2 (vcat (map show_one ms))
2245 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2246 nest 2 $ ptext (sLit "imports:") <+>
2247 (pp_imps HsBootFile (ms_srcimps ms)
2248 $$ pp_imps HsSrcFile (ms_imps ms))]
2249 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2250 pp_imps src mods = fsep (map (show_mod src) mods)
2253 -- | Inform GHC that the working directory has changed. GHC will flush
2254 -- its cache of module locations, since it may no longer be valid.
2255 -- Note: if you change the working directory, you should also unload
2256 -- the current program (set targets to empty, followed by load).
2257 workingDirectoryChanged :: GhcMonad m => m ()
2258 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2260 -- -----------------------------------------------------------------------------
2261 -- inspecting the session
2263 -- | Get the module dependency graph.
2264 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2265 getModuleGraph = liftM hsc_mod_graph getSession
2267 -- | Return @True@ <==> module is loaded.
2268 isLoaded :: GhcMonad m => ModuleName -> m Bool
2269 isLoaded m = withSession $ \hsc_env ->
2270 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2272 -- | Return the bindings for the current interactive session.
2273 getBindings :: GhcMonad m => m [TyThing]
2274 getBindings = withSession $ \hsc_env ->
2275 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2276 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2278 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2279 filtered = foldr f (const []) tmp_ids emptyUniqSet
2281 | uniq `elementOfUniqSet` set = rest set
2282 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2283 where uniq = getUnique (nameOccName (idName id))
2287 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2288 getPrintUnqual = withSession $ \hsc_env ->
2289 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2291 -- | Container for information about a 'Module'.
2292 data ModuleInfo = ModuleInfo {
2293 minf_type_env :: TypeEnv,
2294 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2295 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2296 minf_instances :: [Instance]
2298 ,minf_modBreaks :: ModBreaks
2300 -- ToDo: this should really contain the ModIface too
2302 -- We don't want HomeModInfo here, because a ModuleInfo applies
2303 -- to package modules too.
2305 -- | Request information about a loaded 'Module'
2306 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2307 getModuleInfo mdl = withSession $ \hsc_env -> do
2308 let mg = hsc_mod_graph hsc_env
2309 if mdl `elem` map ms_mod mg
2310 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2312 {- if isHomeModule (hsc_dflags hsc_env) mdl
2314 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2315 -- getPackageModuleInfo will attempt to find the interface, so
2316 -- we don't want to call it for a home module, just in case there
2317 -- was a problem loading the module and the interface doesn't
2318 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2320 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2322 getPackageModuleInfo hsc_env mdl = do
2323 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2325 Nothing -> return Nothing
2327 eps <- readIORef (hsc_EPS hsc_env)
2329 names = availsToNameSet avails
2331 tys = [ ty | name <- concatMap availNames avails,
2332 Just ty <- [lookupTypeEnv pte name] ]
2334 return (Just (ModuleInfo {
2335 minf_type_env = mkTypeEnv tys,
2336 minf_exports = names,
2337 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2338 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2339 minf_modBreaks = emptyModBreaks
2342 getPackageModuleInfo _hsc_env _mdl = do
2343 -- bogusly different for non-GHCI (ToDo)
2347 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2348 getHomeModuleInfo hsc_env mdl =
2349 case lookupUFM (hsc_HPT hsc_env) mdl of
2350 Nothing -> return Nothing
2352 let details = hm_details hmi
2353 return (Just (ModuleInfo {
2354 minf_type_env = md_types details,
2355 minf_exports = availsToNameSet (md_exports details),
2356 minf_rdr_env = mi_globals $! hm_iface hmi,
2357 minf_instances = md_insts details
2359 ,minf_modBreaks = getModBreaks hmi
2363 -- | The list of top-level entities defined in a module
2364 modInfoTyThings :: ModuleInfo -> [TyThing]
2365 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2367 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2368 modInfoTopLevelScope minf
2369 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2371 modInfoExports :: ModuleInfo -> [Name]
2372 modInfoExports minf = nameSetToList $! minf_exports minf
2374 -- | Returns the instances defined by the specified module.
2375 -- Warning: currently unimplemented for package modules.
2376 modInfoInstances :: ModuleInfo -> [Instance]
2377 modInfoInstances = minf_instances
2379 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2380 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2382 mkPrintUnqualifiedForModule :: GhcMonad m =>
2384 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2385 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2386 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2388 modInfoLookupName :: GhcMonad m =>
2390 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2391 modInfoLookupName minf name = withSession $ \hsc_env -> do
2392 case lookupTypeEnv (minf_type_env minf) name of
2393 Just tyThing -> return (Just tyThing)
2395 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2396 return $! lookupType (hsc_dflags hsc_env)
2397 (hsc_HPT hsc_env) (eps_PTE eps) name
2400 modInfoModBreaks :: ModuleInfo -> ModBreaks
2401 modInfoModBreaks = minf_modBreaks
2404 isDictonaryId :: Id -> Bool
2406 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2408 -- | Looks up a global name: that is, any top-level name in any
2409 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2410 -- the interactive context, and therefore does not require a preceding
2412 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2413 lookupGlobalName name = withSession $ \hsc_env -> do
2414 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2415 return $! lookupType (hsc_dflags hsc_env)
2416 (hsc_HPT hsc_env) (eps_PTE eps) name
2419 -- | get the GlobalRdrEnv for a session
2420 getGRE :: GhcMonad m => m GlobalRdrEnv
2421 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2424 -- -----------------------------------------------------------------------------
2425 -- Misc exported utils
2427 dataConType :: DataCon -> Type
2428 dataConType dc = idType (dataConWrapId dc)
2430 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2431 pprParenSymName :: NamedThing a => a -> SDoc
2432 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2434 -- ----------------------------------------------------------------------------
2439 -- - Data and Typeable instances for HsSyn.
2441 -- ToDo: check for small transformations that happen to the syntax in
2442 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2444 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2445 -- to get from TyCons, Ids etc. to TH syntax (reify).
2447 -- :browse will use either lm_toplev or inspect lm_interface, depending
2448 -- on whether the module is interpreted or not.
2452 -- Extract the filename, stringbuffer content and dynflags associed to a module
2454 -- XXX: Explain pre-conditions
2455 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
2456 getModuleSourceAndFlags mod = do
2457 m <- getModSummary (moduleName mod)
2458 case ml_hs_file $ ms_location m of
2459 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
2460 Just sourceFile -> do
2461 source <- liftIO $ hGetStringBuffer sourceFile
2462 return (sourceFile, source, ms_hspp_opts m)
2465 -- | Return module source as token stream, including comments.
2467 -- The module must be in the module graph and its source must be available.
2468 -- Throws a 'HscTypes.SourceError' on parse error.
2469 getTokenStream :: GhcMonad m => Module -> m [Located Token]
2470 getTokenStream mod = do
2471 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2472 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2473 case lexTokenStream source startLoc flags of
2474 POk _ ts -> return ts
2475 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2477 -- | Give even more information on the source than 'getTokenStream'
2478 -- This function allows reconstructing the source completely with
2479 -- 'showRichTokenStream'.
2480 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
2481 getRichTokenStream mod = do
2482 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2483 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2484 case lexTokenStream source startLoc flags of
2485 POk _ ts -> return $ addSourceToTokens startLoc source ts
2486 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2488 -- | Given a source location and a StringBuffer corresponding to this
2489 -- location, return a rich token stream with the source associated to the
2491 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
2492 -> [(Located Token, String)]
2493 addSourceToTokens _ _ [] = []
2494 addSourceToTokens loc buf (t@(L span _) : ts)
2495 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
2496 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
2498 (newLoc, newBuf, str) = go "" loc buf
2499 start = srcSpanStart span
2500 end = srcSpanEnd span
2501 go acc loc buf | loc < start = go acc nLoc nBuf
2502 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
2503 | otherwise = (loc, buf, reverse acc)
2504 where (ch, nBuf) = nextChar buf
2505 nLoc = advanceSrcLoc loc ch
2508 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
2509 -- return source code almost identical to the original code (except for
2510 -- insignificant whitespace.)
2511 showRichTokenStream :: [(Located Token, String)] -> String
2512 showRichTokenStream ts = go startLoc ts ""
2513 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
2514 startLoc = mkSrcLoc sourceFile 0 0
2516 go loc ((L span _, str):ts)
2517 | not (isGoodSrcSpan span) = go loc ts
2518 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
2521 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
2522 . ((replicate tokCol ' ') ++)
2525 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
2526 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
2527 tokEnd = srcSpanEnd span
2529 -- -----------------------------------------------------------------------------
2530 -- Interactive evaluation
2532 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2533 -- filesystem and package database to find the corresponding 'Module',
2534 -- using the algorithm that is used for an @import@ declaration.
2535 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2536 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2538 dflags = hsc_dflags hsc_env
2539 hpt = hsc_HPT hsc_env
2540 this_pkg = thisPackage dflags
2542 case lookupUFM hpt mod_name of
2543 Just mod_info -> return (mi_module (hm_iface mod_info))
2544 _not_a_home_module -> do
2545 res <- findImportedModule hsc_env mod_name maybe_pkg
2547 Found _ m | modulePackageId m /= this_pkg -> return m
2548 | otherwise -> ghcError (CmdLineError (showSDoc $
2549 text "module" <+> quotes (ppr (moduleName m)) <+>
2550 text "is not loaded"))
2551 err -> let msg = cannotFindModule dflags mod_name err in
2552 ghcError (CmdLineError (showSDoc msg))
2555 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2556 getHistorySpan h = withSession $ \hsc_env ->
2557 return$ InteractiveEval.getHistorySpan hsc_env h
2559 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
2560 obtainTermFromVal bound force ty a =
2561 withSession $ \hsc_env ->
2562 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
2564 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
2565 obtainTermFromId bound force id =
2566 withSession $ \hsc_env ->
2567 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id