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,
58 -- * Parsing Haddock comments
61 -- * Inspecting the module structure of the program
62 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
67 -- * Inspecting modules
74 modInfoIsExportedName,
77 mkPrintUnqualifiedForModule,
80 PrintUnqualified, alwaysQualify,
82 -- * Interactive evaluation
83 getBindings, getPrintUnqual,
86 setContext, getContext,
96 runStmt, SingleStep(..),
98 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
99 resumeHistory, resumeHistoryIx),
100 History(historyBreakInfo, historyEnclosingDecl),
101 GHC.getHistorySpan, getHistoryModule,
104 InteractiveEval.back,
105 InteractiveEval.forward,
108 InteractiveEval.compileExpr, HValue, dynCompileExpr,
110 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
112 ModBreaks(..), BreakIndex,
113 BreakInfo(breakInfo_number, breakInfo_module),
114 BreakArray, setBreakOn, setBreakOff, getBreak,
117 -- * Abstract syntax elements
123 Module, mkModule, pprModule, moduleName, modulePackageId,
124 ModuleName, mkModuleName, moduleNameString,
128 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
130 RdrName(Qual,Unqual),
134 isImplicitId, isDeadBinder,
135 isExportedId, isLocalId, isGlobalId,
137 isPrimOpId, isFCallId, isClassOpId_maybe,
138 isDataConWorkId, idDataCon,
139 isBottomingId, isDictonaryId,
140 recordSelectorFieldLabel,
142 -- ** Type constructors
144 tyConTyVars, tyConDataCons, tyConArity,
145 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
147 synTyConDefn, synTyConType, synTyConResKind,
153 -- ** Data constructors
155 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
156 dataConIsInfix, isVanillaDataCon,
158 StrictnessMark(..), isMarkedStrict,
162 classMethods, classSCTheta, classTvsFds,
167 instanceDFunId, pprInstance, pprInstanceHdr,
169 -- ** Types and Kinds
170 Type, splitForAllTys, funResultTy,
171 pprParendType, pprTypeApp,
174 ThetaType, pprThetaArrow,
180 module HsSyn, -- ToDo: remove extraneous bits
184 defaultFixity, maxPrecedence,
188 -- ** Source locations
190 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
191 srcLocFile, srcLocLine, srcLocCol,
193 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
194 srcSpanStart, srcSpanEnd,
196 srcSpanStartLine, srcSpanEndLine,
197 srcSpanStartCol, srcSpanEndCol,
200 GhcException(..), showGhcException,
202 -- * Token stream manipulations
204 getTokenStream, getRichTokenStream,
205 showRichTokenStream, addSourceToTokens,
215 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
216 * what StaticFlags should we expose, if any?
219 #include "HsVersions.h"
222 import qualified Linker
223 import Linker ( HValue )
227 import InteractiveEval
232 import TcRnTypes hiding (LIE)
233 import TcRnMonad ( initIfaceCheck )
237 import qualified HsSyn -- hack as we want to reexport the whole module
238 import HsSyn hiding ((<.>))
239 import Type hiding (typeKind)
240 import TcType hiding (typeKind)
243 import TysPrim ( alphaTyVars )
248 import Name hiding ( varName )
249 import OccName ( parenSymOcc )
250 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
252 import FamInstEnv ( emptyFamInstEnv )
256 import DriverPipeline
257 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
263 import StaticFlagParser
264 import qualified StaticFlags
265 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
274 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
278 import StringBuffer ( StringBuffer, hGetStringBuffer, nextChar )
281 import Maybes ( expectJust, mapCatMaybes )
283 import HaddockLex ( tokenise )
287 import Control.Concurrent
288 import System.Directory ( getModificationTime, doesFileExist,
289 getCurrentDirectory )
292 import qualified Data.List as List
294 import System.Exit ( exitWith, ExitCode(..) )
295 import System.Time ( ClockTime, getClockTime )
298 import System.FilePath
300 import System.IO.Error ( try, isDoesNotExistError )
301 import Prelude hiding (init)
304 -- -----------------------------------------------------------------------------
305 -- Exception handlers
307 -- | Install some default exception handlers and run the inner computation.
308 -- Unless you want to handle exceptions yourself, you should wrap this around
309 -- the top level of your program. The default handlers output the error
310 -- message(s) to stderr and exit cleanly.
311 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
312 defaultErrorHandler dflags inner =
313 -- top-level exception handler: any unrecognised exception is a compiler bug.
314 ghandle (\exception -> liftIO $ do
316 case fromException exception of
317 -- an IO exception probably isn't our fault, so don't panic
318 Just (ioe :: IOException) ->
319 fatalErrorMsg dflags (text (show ioe))
320 _ -> case fromException exception of
321 Just StackOverflow ->
322 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
323 _ -> case fromException exception of
324 Just (ex :: ExitCode) -> throw ex
327 (text (show (Panic (show exception))))
328 exitWith (ExitFailure 1)
331 -- program errors: messages with locations attached. Sometimes it is
332 -- convenient to just throw these as exceptions.
335 printBagOfErrors dflags (unitBag em)
336 exitWith (ExitFailure 1)) $
338 -- error messages propagated as exceptions
343 PhaseFailed _ code -> exitWith code
344 Interrupted -> exitWith (ExitFailure 1)
345 _ -> do fatalErrorMsg dflags (text (show ge))
346 exitWith (ExitFailure 1)
350 -- | Install a default cleanup handler to remove temporary files deposited by
351 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
352 -- want to override the error handling, but still get the ordinary cleanup
354 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
355 DynFlags -> m a -> m a
356 defaultCleanupHandler dflags inner =
357 -- make sure we clean up after ourselves
360 cleanTempFiles dflags
363 -- exceptions will be blocked while we clean the temporary files,
364 -- so there shouldn't be any difficulty if we receive further
367 -- | Print the error message and all warnings. Useful inside exception
368 -- handlers. Clears warnings after printing.
369 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
370 printExceptionAndWarnings err = do
371 let errs = srcErrorMessages err
373 dflags <- getSessionDynFlags
375 -- Empty errors means we failed due to -Werror. (Since this function
376 -- takes a source error as argument, we know for sure _some_ error
377 -- did indeed happen.)
379 printBagOfWarnings dflags warns
380 printBagOfErrors dflags (unitBag warnIsErrorMsg)
381 else liftIO $ printBagOfErrors dflags errs
384 -- | Print all accumulated warnings using 'log_action'.
385 printWarnings :: GhcMonad m => m ()
387 dflags <- getSessionDynFlags
389 liftIO $ printBagOfWarnings dflags warns
392 -- | Run function for the 'Ghc' monad.
394 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
395 -- to this function will create a new session which should not be shared among
398 -- Any errors not handled inside the 'Ghc' action are propagated as IO
401 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
402 -> Ghc a -- ^ The action to perform.
404 runGhc mb_top_dir ghc = do
405 wref <- newIORef emptyBag
406 ref <- newIORef undefined
407 let session = Session ref wref
408 flip unGhc session $ do
409 initGhcMonad mb_top_dir
411 -- XXX: unregister interrupt handlers here?
413 -- | Run function for 'GhcT' monad transformer.
415 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
416 -- to this function will create a new session which should not be shared among
419 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
420 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
421 -> GhcT m a -- ^ The action to perform.
423 runGhcT mb_top_dir ghct = do
424 wref <- liftIO $ newIORef emptyBag
425 ref <- liftIO $ newIORef undefined
426 let session = Session ref wref
427 flip unGhcT session $ do
428 initGhcMonad mb_top_dir
431 -- | Initialise a GHC session.
433 -- If you implement a custom 'GhcMonad' you must call this function in the
434 -- monad run function. It will initialise the session variable and clear all
437 -- The first argument should point to the directory where GHC's library files
438 -- reside. More precisely, this should be the output of @ghc --print-libdir@
439 -- of the version of GHC the module using this API is compiled with. For
440 -- portability, you should use the @ghc-paths@ package, available at
441 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
443 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
444 initGhcMonad mb_top_dir = do
446 main_thread <- liftIO $ myThreadId
447 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
448 liftIO $ installSignalHandlers
450 liftIO $ StaticFlags.initStaticOpts
452 dflags0 <- liftIO $ initDynFlags defaultDynFlags
453 dflags <- liftIO $ initSysTools mb_top_dir dflags0
454 env <- liftIO $ newHscEnv dflags
458 -- -----------------------------------------------------------------------------
461 -- | Grabs the DynFlags from the Session
462 getSessionDynFlags :: GhcMonad m => m DynFlags
463 getSessionDynFlags = withSession (return . hsc_dflags)
465 -- | Updates the DynFlags in a Session. This also reads
466 -- the package database (unless it has already been read),
467 -- and prepares the compilers knowledge about packages. It
468 -- can be called again to load new packages: just add new
469 -- package flags to (packageFlags dflags).
471 -- Returns a list of new packages that may need to be linked in using
472 -- the dynamic linker (see 'linkPackages') as a result of new package
473 -- flags. If you are not doing linking or doing static linking, you
474 -- can ignore the list of packages returned.
476 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
477 setSessionDynFlags dflags = do
478 (dflags', preload) <- liftIO $ initPackages dflags
479 modifySession (\h -> h{ hsc_dflags = dflags' })
482 -- | If there is no -o option, guess the name of target executable
483 -- by using top-level source file name as a base.
484 guessOutputFile :: GhcMonad m => m ()
485 guessOutputFile = modifySession $ \env ->
486 let dflags = hsc_dflags env
487 mod_graph = hsc_mod_graph env
488 mainModuleSrcPath :: Maybe String
489 mainModuleSrcPath = do
490 let isMain = (== mainModIs dflags) . ms_mod
491 [ms] <- return (filter isMain mod_graph)
492 ml_hs_file (ms_location ms)
493 name = fmap dropExtension mainModuleSrcPath
495 #if defined(mingw32_HOST_OS)
496 -- we must add the .exe extention unconditionally here, otherwise
497 -- when name has an extension of its own, the .exe extension will
498 -- not be added by DriverPipeline.exeFileName. See #2248
499 name_exe = fmap (<.> "exe") name
504 case outputFile dflags of
506 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
508 -- -----------------------------------------------------------------------------
511 -- ToDo: think about relative vs. absolute file paths. And what
512 -- happens when the current directory changes.
514 -- | Sets the targets for this session. Each target may be a module name
515 -- or a filename. The targets correspond to the set of root modules for
516 -- the program\/library. Unloading the current program is achieved by
517 -- setting the current set of targets to be empty, followed by 'load'.
518 setTargets :: GhcMonad m => [Target] -> m ()
519 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
521 -- | Returns the current set of targets
522 getTargets :: GhcMonad m => m [Target]
523 getTargets = withSession (return . hsc_targets)
525 -- | Add another target.
526 addTarget :: GhcMonad m => Target -> m ()
528 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
531 removeTarget :: GhcMonad m => TargetId -> m ()
532 removeTarget target_id
533 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
535 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
537 -- | Attempts to guess what Target a string refers to. This function
538 -- implements the @--make@/GHCi command-line syntax for filenames:
540 -- - if the string looks like a Haskell source filename, then interpret it
543 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
546 -- - otherwise interpret the string as a module name
548 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
549 guessTarget str (Just phase)
550 = return (Target (TargetFile str (Just phase)) True Nothing)
551 guessTarget str Nothing
552 | isHaskellSrcFilename file
553 = return (target (TargetFile file Nothing))
555 = do exists <- liftIO $ doesFileExist hs_file
557 then return (target (TargetFile hs_file Nothing))
559 exists <- liftIO $ doesFileExist lhs_file
561 then return (target (TargetFile lhs_file Nothing))
563 if looksLikeModuleName file
564 then return (target (TargetModule (mkModuleName file)))
567 (ProgramError (showSDoc $
568 text "target" <+> quotes (text file) <+>
569 text "is not a module name or a source file"))
572 | '*':rest <- str = (rest, False)
573 | otherwise = (str, True)
575 hs_file = file <.> "hs"
576 lhs_file = file <.> "lhs"
578 target tid = Target tid obj_allowed Nothing
580 -- -----------------------------------------------------------------------------
581 -- Extending the program scope
583 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
584 extendGlobalRdrScope rdrElts
585 = modifySession $ \hscEnv ->
586 let global_rdr = hsc_global_rdr_env hscEnv
587 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
589 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
590 setGlobalRdrScope rdrElts
591 = modifySession $ \hscEnv ->
592 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
594 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
595 extendGlobalTypeScope ids
596 = modifySession $ \hscEnv ->
597 let global_type = hsc_global_type_env hscEnv
598 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
600 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
601 setGlobalTypeScope ids
602 = modifySession $ \hscEnv ->
603 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
605 -- -----------------------------------------------------------------------------
606 -- Parsing Haddock comments
608 parseHaddockComment :: String -> Either String (HsDoc RdrName)
609 parseHaddockComment string =
610 case parseHaddockParagraphs (tokenise string) of
614 -- -----------------------------------------------------------------------------
615 -- Loading the program
617 -- | Perform a dependency analysis starting from the current targets
618 -- and update the session with the new module graph.
619 depanal :: GhcMonad m =>
620 [ModuleName] -- ^ excluded modules
621 -> Bool -- ^ allow duplicate roots
623 depanal excluded_mods allow_dup_roots = do
624 hsc_env <- getSession
626 dflags = hsc_dflags hsc_env
627 targets = hsc_targets hsc_env
628 old_graph = hsc_mod_graph hsc_env
630 liftIO $ showPass dflags "Chasing dependencies"
631 liftIO $ debugTraceMsg dflags 2 (hcat [
632 text "Chasing modules from: ",
633 hcat (punctuate comma (map pprTarget targets))])
635 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
636 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
641 | LoadUpTo ModuleName
642 | LoadDependenciesOf ModuleName
644 -- | Try to load the program. Calls 'loadWithLogger' with the default
645 -- compiler that just immediately logs all warnings and errors.
646 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
648 loadWithLogger defaultWarnErrLogger how_much
650 -- | A function called to log warnings and errors.
651 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
653 defaultWarnErrLogger :: WarnErrLogger
654 defaultWarnErrLogger Nothing = printWarnings
655 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
657 -- | Try to load the program. If a Module is supplied, then just
658 -- attempt to load up to this target. If no Module is supplied,
659 -- then try to load all targets.
661 -- The first argument is a function that is called after compiling each
662 -- module to print wanrings and errors.
664 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
665 loadWithLogger logger how_much = do
666 -- Dependency analysis first. Note that this fixes the module graph:
667 -- even if we don't get a fully successful upsweep, the full module
668 -- graph is still retained in the Session. We can tell which modules
669 -- were successfully loaded by inspecting the Session's HPT.
670 mod_graph <- depanal [] False
671 load2 how_much mod_graph logger
673 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary] -> WarnErrLogger
675 load2 how_much mod_graph logger = do
677 hsc_env <- getSession
679 let hpt1 = hsc_HPT hsc_env
680 let dflags = hsc_dflags hsc_env
682 -- The "bad" boot modules are the ones for which we have
683 -- B.hs-boot in the module graph, but no B.hs
684 -- The downsweep should have ensured this does not happen
686 let all_home_mods = [ms_mod_name s
687 | s <- mod_graph, not (isBootSummary s)]
688 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
689 not (ms_mod_name s `elem` all_home_mods)]
690 ASSERT( null bad_boot_mods ) return ()
692 -- check that the module given in HowMuch actually exists, otherwise
693 -- topSortModuleGraph will bomb later.
694 let checkHowMuch (LoadUpTo m) = checkMod m
695 checkHowMuch (LoadDependenciesOf m) = checkMod m
699 | m `elem` all_home_mods = and_then
701 liftIO $ errorMsg dflags (text "no such module:" <+>
705 checkHowMuch how_much $ do
707 -- mg2_with_srcimps drops the hi-boot nodes, returning a
708 -- graph with cycles. Among other things, it is used for
709 -- backing out partially complete cycles following a failed
710 -- upsweep, and for removing from hpt all the modules
711 -- not in strict downwards closure, during calls to compile.
712 let mg2_with_srcimps :: [SCC ModSummary]
713 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
715 -- If we can determine that any of the {-# SOURCE #-} imports
716 -- are definitely unnecessary, then emit a warning.
717 warnUnnecessarySourceImports dflags mg2_with_srcimps
720 -- check the stability property for each module.
721 stable_mods@(stable_obj,stable_bco)
722 = checkStability hpt1 mg2_with_srcimps all_home_mods
724 -- prune bits of the HPT which are definitely redundant now,
726 pruned_hpt = pruneHomePackageTable hpt1
727 (flattenSCCs mg2_with_srcimps)
730 liftIO $ evaluate pruned_hpt
732 -- before we unload anything, make sure we don't leave an old
733 -- interactive context around pointing to dead bindings. Also,
734 -- write the pruned HPT to allow the old HPT to be GC'd.
735 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
736 hsc_HPT = pruned_hpt }
738 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
739 text "Stable BCO:" <+> ppr stable_bco)
741 -- Unload any modules which are going to be re-linked this time around.
742 let stable_linkables = [ linkable
743 | m <- stable_obj++stable_bco,
744 Just hmi <- [lookupUFM pruned_hpt m],
745 Just linkable <- [hm_linkable hmi] ]
746 liftIO $ unload hsc_env stable_linkables
748 -- We could at this point detect cycles which aren't broken by
749 -- a source-import, and complain immediately, but it seems better
750 -- to let upsweep_mods do this, so at least some useful work gets
751 -- done before the upsweep is abandoned.
752 --hPutStrLn stderr "after tsort:\n"
753 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
755 -- Now do the upsweep, calling compile for each module in
756 -- turn. Final result is version 3 of everything.
758 -- Topologically sort the module graph, this time including hi-boot
759 -- nodes, and possibly just including the portion of the graph
760 -- reachable from the module specified in the 2nd argument to load.
761 -- This graph should be cycle-free.
762 -- If we're restricting the upsweep to a portion of the graph, we
763 -- also want to retain everything that is still stable.
764 let full_mg :: [SCC ModSummary]
765 full_mg = topSortModuleGraph False mod_graph Nothing
767 maybe_top_mod = case how_much of
769 LoadDependenciesOf m -> Just m
772 partial_mg0 :: [SCC ModSummary]
773 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
775 -- LoadDependenciesOf m: we want the upsweep to stop just
776 -- short of the specified module (unless the specified module
779 | LoadDependenciesOf _mod <- how_much
780 = ASSERT( case last partial_mg0 of
781 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
782 List.init partial_mg0
788 | AcyclicSCC ms <- full_mg,
789 ms_mod_name ms `elem` stable_obj++stable_bco,
790 ms_mod_name ms `notElem` [ ms_mod_name ms' |
791 AcyclicSCC ms' <- partial_mg ] ]
793 mg = stable_mg ++ partial_mg
795 -- clean up between compilations
796 let cleanup = cleanTempFilesExcept dflags
797 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
799 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
801 (upsweep_ok, hsc_env1, modsUpswept)
803 (hsc_env { hsc_HPT = emptyHomePackageTable })
804 pruned_hpt stable_mods cleanup mg
806 -- Make modsDone be the summaries for each home module now
807 -- available; this should equal the domain of hpt3.
808 -- Get in in a roughly top .. bottom order (hence reverse).
810 let modsDone = reverse modsUpswept
812 -- Try and do linking in some form, depending on whether the
813 -- upsweep was completely or only partially successful.
815 if succeeded upsweep_ok
818 -- Easy; just relink it all.
819 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
821 -- Clean up after ourselves
822 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
824 -- Issue a warning for the confusing case where the user
825 -- said '-o foo' but we're not going to do any linking.
826 -- We attempt linking if either (a) one of the modules is
827 -- called Main, or (b) the user said -no-hs-main, indicating
828 -- that main() is going to come from somewhere else.
830 let ofile = outputFile dflags
831 let no_hs_main = dopt Opt_NoHsMain dflags
833 main_mod = mainModIs dflags
834 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
835 do_linking = a_root_is_Main || no_hs_main
837 when (ghcLink dflags == LinkBinary
838 && isJust ofile && not do_linking) $
839 liftIO $ debugTraceMsg dflags 1 $
840 text ("Warning: output was redirected with -o, " ++
841 "but no output will be generated\n" ++
842 "because there is no " ++
843 moduleNameString (moduleName main_mod) ++ " module.")
845 -- link everything together
846 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
848 loadFinish Succeeded linkresult hsc_env1
851 -- Tricky. We need to back out the effects of compiling any
852 -- half-done cycles, both so as to clean up the top level envs
853 -- and to avoid telling the interactive linker to link them.
854 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
857 = map ms_mod modsDone
858 let mods_to_zap_names
859 = findPartiallyCompletedCycles modsDone_names
862 = filter ((`notElem` mods_to_zap_names).ms_mod)
865 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
868 -- Clean up after ourselves
869 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
871 -- there should be no Nothings where linkables should be, now
872 ASSERT(all (isJust.hm_linkable)
873 (eltsUFM (hsc_HPT hsc_env))) do
875 -- Link everything together
876 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
878 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
879 loadFinish Failed linkresult hsc_env4
881 -- Finish up after a load.
883 -- If the link failed, unload everything and return.
884 loadFinish :: GhcMonad m =>
885 SuccessFlag -> SuccessFlag -> HscEnv
887 loadFinish _all_ok Failed hsc_env
888 = do liftIO $ unload hsc_env []
889 modifySession $ \_ -> discardProg hsc_env
892 -- Empty the interactive context and set the module context to the topmost
893 -- newly loaded module, or the Prelude if none were loaded.
894 loadFinish all_ok Succeeded hsc_env
895 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
899 -- Forget the current program, but retain the persistent info in HscEnv
900 discardProg :: HscEnv -> HscEnv
902 = hsc_env { hsc_mod_graph = emptyMG,
903 hsc_IC = emptyInteractiveContext,
904 hsc_HPT = emptyHomePackageTable }
906 -- used to fish out the preprocess output files for the purposes of
907 -- cleaning up. The preprocessed file *might* be the same as the
908 -- source file, but that doesn't do any harm.
909 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
910 ppFilesFromSummaries summaries = map ms_hspp_file summaries
912 -- -----------------------------------------------------------------------------
914 class ParsedMod m where
915 modSummary :: m -> ModSummary
916 parsedSource :: m -> ParsedSource
918 class ParsedMod m => TypecheckedMod m where
919 renamedSource :: m -> Maybe RenamedSource
920 typecheckedSource :: m -> TypecheckedSource
921 moduleInfo :: m -> ModuleInfo
922 tm_internals :: m -> (TcGblEnv, ModDetails)
923 -- ToDo: improvements that could be made here:
924 -- if the module succeeded renaming but not typechecking,
925 -- we can still get back the GlobalRdrEnv and exports, so
926 -- perhaps the ModuleInfo should be split up into separate
929 class TypecheckedMod m => DesugaredMod m where
930 coreModule :: m -> ModGuts
932 -- | The result of successful parsing.
934 ParsedModule { pm_mod_summary :: ModSummary
935 , pm_parsed_source :: ParsedSource }
937 instance ParsedMod ParsedModule where
938 modSummary m = pm_mod_summary m
939 parsedSource m = pm_parsed_source m
941 -- | The result of successful typechecking. It also contains the parser
943 data TypecheckedModule =
944 TypecheckedModule { tm_parsed_module :: ParsedModule
945 , tm_renamed_source :: Maybe RenamedSource
946 , tm_typechecked_source :: TypecheckedSource
947 , tm_checked_module_info :: ModuleInfo
948 , tm_internals_ :: (TcGblEnv, ModDetails)
951 instance ParsedMod TypecheckedModule where
952 modSummary m = modSummary (tm_parsed_module m)
953 parsedSource m = parsedSource (tm_parsed_module m)
955 instance TypecheckedMod TypecheckedModule where
956 renamedSource m = tm_renamed_source m
957 typecheckedSource m = tm_typechecked_source m
958 moduleInfo m = tm_checked_module_info m
959 tm_internals m = tm_internals_ m
961 -- | The result of successful desugaring (i.e., translation to core). Also
962 -- contains all the information of a typechecked module.
963 data DesugaredModule =
964 DesugaredModule { dm_typechecked_module :: TypecheckedModule
965 , dm_core_module :: ModGuts
968 instance ParsedMod DesugaredModule where
969 modSummary m = modSummary (dm_typechecked_module m)
970 parsedSource m = parsedSource (dm_typechecked_module m)
972 instance TypecheckedMod DesugaredModule where
973 renamedSource m = renamedSource (dm_typechecked_module m)
974 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
975 moduleInfo m = moduleInfo (dm_typechecked_module m)
976 tm_internals m = tm_internals_ (dm_typechecked_module m)
978 instance DesugaredMod DesugaredModule where
979 coreModule m = dm_core_module m
981 type ParsedSource = Located (HsModule RdrName)
982 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
983 Maybe (HsDoc Name), HaddockModInfo Name)
984 type TypecheckedSource = LHsBinds Id
987 -- - things that aren't in the output of the typechecker right now:
991 -- - type/data/newtype declarations
992 -- - class declarations
994 -- - extra things in the typechecker's output:
995 -- - default methods are turned into top-level decls.
996 -- - dictionary bindings
998 -- | Return the 'ModSummary' of a module with the given name.
1000 -- The module must be part of the module graph (see 'hsc_mod_graph' and
1001 -- 'ModuleGraph'). If this is not the case, this function will throw an
1004 -- Note that the module graph may contain several 'ModSummary's matching the
1005 -- same name (for example both a @.hs@ and a @.hs-boot@).
1006 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1007 getModSummary mod = do
1008 mg <- liftM hsc_mod_graph getSession
1009 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
1010 [] -> throw $ mkApiErr (text "Module not part of module graph")
1013 -- | Parse a module.
1015 -- Throws a 'SourceError' on parse error.
1016 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
1018 hsc_env0 <- getSession
1019 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1020 rdr_module <- parseFile hsc_env ms
1021 return (ParsedModule ms rdr_module)
1023 -- | Typecheck and rename a parsed module.
1025 -- Throws a 'SourceError' if either fails.
1026 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1027 typecheckModule pmod = do
1028 let ms = modSummary pmod
1029 hsc_env0 <- getSession
1030 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1031 (tc_gbl_env, rn_info)
1032 <- typecheckRenameModule hsc_env ms (parsedSource pmod)
1033 details <- liftIO $ makeSimpleDetails hsc_env tc_gbl_env
1036 tm_internals_ = (tc_gbl_env, details),
1037 tm_parsed_module = pmod,
1038 tm_renamed_source = rn_info,
1039 tm_typechecked_source = tcg_binds tc_gbl_env,
1040 tm_checked_module_info =
1042 minf_type_env = md_types details,
1043 minf_exports = availsToNameSet $ md_exports details,
1044 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1045 minf_instances = md_insts details
1047 ,minf_modBreaks = emptyModBreaks
1051 -- | Desugar a typechecked module.
1052 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1053 desugarModule tcm = do
1054 let ms = modSummary tcm
1055 hsc_env0 <- getSession
1056 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1057 let (tcg, _) = tm_internals tcm
1058 guts <- deSugarModule hsc_env ms tcg
1061 dm_typechecked_module = tcm,
1062 dm_core_module = guts
1065 -- | Load a module. Input doesn't need to be desugared.
1067 -- XXX: Describe usage.
1068 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1070 let ms = modSummary tcm
1071 let mod = ms_mod_name ms
1072 hsc_env0 <- getSession
1073 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1074 let (tcg, details) = tm_internals tcm
1075 (iface,_) <- liftIO $ makeSimpleIface hsc_env Nothing tcg details
1076 let mod_info = HomeModInfo {
1078 hm_details = details,
1079 hm_linkable = Nothing }
1080 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
1081 modifySession $ \_ -> hsc_env0{ hsc_HPT = hpt_new }
1084 -- | This is the way to get access to the Core bindings corresponding
1085 -- to a module. 'compileToCore' parses, typechecks, and
1086 -- desugars the module, then returns the resulting Core module (consisting of
1087 -- the module name, type declarations, and function declarations) if
1089 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1090 compileToCoreModule = compileCore False
1092 -- | Like compileToCoreModule, but invokes the simplifier, so
1093 -- as to return simplified and tidied Core.
1094 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1095 compileToCoreSimplified = compileCore True
1097 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1098 -- bindings, but for most purposes, you probably want to call
1099 -- compileToCoreModule.
1100 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1101 compileToCore fn = do
1102 mod <- compileToCoreModule session fn
1103 return $ cm_binds mod
1105 -- | Takes a CoreModule and compiles the bindings therein
1106 -- to object code. The first argument is a bool flag indicating
1107 -- whether to run the simplifier.
1108 -- The resulting .o, .hi, and executable files, if any, are stored in the
1109 -- current directory, and named according to the module name.
1110 -- Returns True iff compilation succeeded.
1111 -- This has only so far been tested with a single self-contained module.
1112 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1113 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1114 hscEnv <- getSession
1115 dflags <- getSessionDynFlags
1116 currentTime <- liftIO $ getClockTime
1117 cwd <- liftIO $ getCurrentDirectory
1118 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1119 ((moduleNameSlashes . moduleName) mName)
1121 let modSummary = ModSummary { ms_mod = mName,
1122 ms_hsc_src = ExtCoreFile,
1123 ms_location = modLocation,
1124 -- By setting the object file timestamp to Nothing,
1125 -- we always force recompilation, which is what we
1126 -- want. (Thus it doesn't matter what the timestamp
1127 -- for the (nonexistent) source file is.)
1128 ms_hs_date = currentTime,
1129 ms_obj_date = Nothing,
1130 -- Only handling the single-module case for now, so no imports.
1135 ms_hspp_opts = dflags,
1136 ms_hspp_buf = Nothing
1139 ioMsgMaybe $ flip evalComp (CompState{ compHscEnv=hscEnv,
1140 compModSummary=modSummary,
1141 compOldIface=Nothing}) $
1142 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1143 | otherwise = return mod_guts
1144 in maybe_simplify (mkModGuts cm)
1150 -- Makes a "vanilla" ModGuts.
1151 mkModGuts :: CoreModule -> ModGuts
1152 mkModGuts coreModule = ModGuts {
1153 mg_module = cm_module coreModule,
1156 mg_deps = noDependencies,
1157 mg_dir_imps = emptyModuleEnv,
1158 mg_used_names = emptyNameSet,
1159 mg_rdr_env = emptyGlobalRdrEnv,
1160 mg_fix_env = emptyFixityEnv,
1161 mg_types = emptyTypeEnv,
1165 mg_binds = cm_binds coreModule,
1166 mg_foreign = NoStubs,
1167 mg_warns = NoWarnings,
1168 mg_hpc_info = emptyHpcInfo False,
1169 mg_modBreaks = emptyModBreaks,
1170 mg_vect_info = noVectInfo,
1171 mg_inst_env = emptyInstEnv,
1172 mg_fam_inst_env = emptyFamInstEnv
1175 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1176 compileCore simplify fn = do
1177 -- First, set the target to the desired filename
1178 target <- guessTarget fn Nothing
1181 -- Then find dependencies
1182 modGraph <- depanal [] True
1183 case find ((== fn) . msHsFilePath) modGraph of
1184 Just modSummary -> do
1185 -- Now we have the module name;
1186 -- parse, typecheck and desugar the module
1187 mod_guts <- coreModule `fmap`
1188 (desugarModule =<< typecheckModule =<< parseModule modSummary)
1189 liftM gutsToCoreModule $
1192 -- If simplify is true: simplify (hscSimplify), then tidy
1194 hsc_env <- getSession
1195 simpl_guts <- ioMsg $ evalComp (hscSimplify mod_guts)
1197 compHscEnv = hsc_env,
1198 compModSummary = modSummary,
1199 compOldIface = Nothing})
1200 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1201 return $ Left tidy_guts
1203 return $ Right mod_guts
1205 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1206 module dependency graph"
1207 where -- two versions, based on whether we simplify (thus run tidyProgram,
1208 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1209 -- we just have a ModGuts.
1210 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1211 gutsToCoreModule (Left (cg, md)) = CoreModule {
1212 cm_module = cg_module cg, cm_types = md_types md,
1213 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1215 gutsToCoreModule (Right mg) = CoreModule {
1216 cm_module = mg_module mg, cm_types = mg_types mg,
1217 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1220 -- ---------------------------------------------------------------------------
1223 unload :: HscEnv -> [Linkable] -> IO ()
1224 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1225 = case ghcLink (hsc_dflags hsc_env) of
1227 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1229 LinkInMemory -> panic "unload: no interpreter"
1230 -- urgh. avoid warnings:
1231 hsc_env stable_linkables
1235 -- -----------------------------------------------------------------------------
1239 Stability tells us which modules definitely do not need to be recompiled.
1240 There are two main reasons for having stability:
1242 - avoid doing a complete upsweep of the module graph in GHCi when
1243 modules near the bottom of the tree have not changed.
1245 - to tell GHCi when it can load object code: we can only load object code
1246 for a module when we also load object code fo all of the imports of the
1247 module. So we need to know that we will definitely not be recompiling
1248 any of these modules, and we can use the object code.
1250 The stability check is as follows. Both stableObject and
1251 stableBCO are used during the upsweep phase later.
1254 stable m = stableObject m || stableBCO m
1257 all stableObject (imports m)
1258 && old linkable does not exist, or is == on-disk .o
1259 && date(on-disk .o) > date(.hs)
1262 all stable (imports m)
1263 && date(BCO) > date(.hs)
1266 These properties embody the following ideas:
1268 - if a module is stable, then:
1270 - if it has been compiled in a previous pass (present in HPT)
1271 then it does not need to be compiled or re-linked.
1273 - if it has not been compiled in a previous pass,
1274 then we only need to read its .hi file from disk and
1275 link it to produce a 'ModDetails'.
1277 - if a modules is not stable, we will definitely be at least
1278 re-linking, and possibly re-compiling it during the 'upsweep'.
1279 All non-stable modules can (and should) therefore be unlinked
1280 before the 'upsweep'.
1282 - Note that objects are only considered stable if they only depend
1283 on other objects. We can't link object code against byte code.
1287 :: HomePackageTable -- HPT from last compilation
1288 -> [SCC ModSummary] -- current module graph (cyclic)
1289 -> [ModuleName] -- all home modules
1290 -> ([ModuleName], -- stableObject
1291 [ModuleName]) -- stableBCO
1293 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1295 checkSCC (stable_obj, stable_bco) scc0
1296 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1297 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1298 | otherwise = (stable_obj, stable_bco)
1300 scc = flattenSCC scc0
1301 scc_mods = map ms_mod_name scc
1302 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1304 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1305 -- all imports outside the current SCC, but in the home pkg
1307 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1308 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1312 && all object_ok scc
1315 and (zipWith (||) stable_obj_imps stable_bco_imps)
1319 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1323 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1324 Just hmi | Just l <- hm_linkable hmi
1325 -> isObjectLinkable l && t == linkableTime l
1327 -- why '>=' rather than '>' above? If the filesystem stores
1328 -- times to the nearset second, we may occasionally find that
1329 -- the object & source have the same modification time,
1330 -- especially if the source was automatically generated
1331 -- and compiled. Using >= is slightly unsafe, but it matches
1332 -- make's behaviour.
1335 = case lookupUFM hpt (ms_mod_name ms) of
1336 Just hmi | Just l <- hm_linkable hmi ->
1337 not (isObjectLinkable l) &&
1338 linkableTime l >= ms_hs_date ms
1341 ms_allimps :: ModSummary -> [ModuleName]
1342 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1344 -- -----------------------------------------------------------------------------
1346 -- | Prune the HomePackageTable
1348 -- Before doing an upsweep, we can throw away:
1350 -- - For non-stable modules:
1351 -- - all ModDetails, all linked code
1352 -- - all unlinked code that is out of date with respect to
1355 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1356 -- space at the end of the upsweep, because the topmost ModDetails of the
1357 -- old HPT holds on to the entire type environment from the previous
1360 pruneHomePackageTable
1363 -> ([ModuleName],[ModuleName])
1366 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1369 | is_stable modl = hmi'
1370 | otherwise = hmi'{ hm_details = emptyModDetails }
1372 modl = moduleName (mi_module (hm_iface hmi))
1373 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1374 = hmi{ hm_linkable = Nothing }
1377 where ms = expectJust "prune" (lookupUFM ms_map modl)
1379 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1381 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1383 -- -----------------------------------------------------------------------------
1385 -- Return (names of) all those in modsDone who are part of a cycle
1386 -- as defined by theGraph.
1387 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1388 findPartiallyCompletedCycles modsDone theGraph
1392 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1393 chew ((CyclicSCC vs):rest)
1394 = let names_in_this_cycle = nub (map ms_mod vs)
1396 = nub ([done | done <- modsDone,
1397 done `elem` names_in_this_cycle])
1398 chewed_rest = chew rest
1400 if notNull mods_in_this_cycle
1401 && length mods_in_this_cycle < length names_in_this_cycle
1402 then mods_in_this_cycle ++ chewed_rest
1405 -- -----------------------------------------------------------------------------
1409 -- This is where we compile each module in the module graph, in a pass
1410 -- from the bottom to the top of the graph.
1412 -- There better had not be any cyclic groups here -- we check for them.
1416 WarnErrLogger -- ^ Called to print warnings and errors.
1417 -> HscEnv -- ^ Includes initially-empty HPT
1418 -> HomePackageTable -- ^ HPT from last time round (pruned)
1419 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1420 -> IO () -- ^ How to clean up unwanted tmp files
1421 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1423 HscEnv, -- With an updated HPT
1424 [ModSummary]) -- Mods which succeeded
1426 upsweep logger hsc_env old_hpt stable_mods cleanup sccs = do
1427 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1428 return (res, hsc_env, reverse done)
1431 upsweep' hsc_env _old_hpt done
1433 = return (Succeeded, hsc_env, done)
1435 upsweep' hsc_env _old_hpt done
1436 (CyclicSCC ms:_) _ _
1437 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1438 return (Failed, hsc_env, done)
1440 upsweep' hsc_env old_hpt done
1441 (AcyclicSCC mod:mods) mod_index nmods
1442 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1443 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1444 -- (moduleEnvElts (hsc_HPT hsc_env)))
1447 <- handleSourceError
1448 (\err -> do logger (Just err); return Nothing) $ do
1449 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1451 logger Nothing -- log warnings
1452 return (Just mod_info)
1454 liftIO cleanup -- Remove unwanted tmp files between compilations
1457 Nothing -> return (Failed, hsc_env, done)
1459 let this_mod = ms_mod_name mod
1461 -- Add new info to hsc_env
1462 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1463 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1465 -- Space-saving: delete the old HPT entry
1466 -- for mod BUT if mod is a hs-boot
1467 -- node, don't delete it. For the
1468 -- interface, the HPT entry is probaby for the
1469 -- main Haskell source file. Deleting it
1470 -- would force the real module to be recompiled
1472 old_hpt1 | isBootSummary mod = old_hpt
1473 | otherwise = delFromUFM old_hpt this_mod
1477 -- fixup our HomePackageTable after we've finished compiling
1478 -- a mutually-recursive loop. See reTypecheckLoop, below.
1479 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1481 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1483 -- | Compile a single module. Always produce a Linkable for it if
1484 -- successful. If no compilation happened, return the old Linkable.
1485 upsweep_mod :: GhcMonad m =>
1488 -> ([ModuleName],[ModuleName])
1490 -> Int -- index of module
1491 -> Int -- total number of modules
1494 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1496 this_mod_name = ms_mod_name summary
1497 this_mod = ms_mod summary
1498 mb_obj_date = ms_obj_date summary
1499 obj_fn = ml_obj_file (ms_location summary)
1500 hs_date = ms_hs_date summary
1502 is_stable_obj = this_mod_name `elem` stable_obj
1503 is_stable_bco = this_mod_name `elem` stable_bco
1505 old_hmi = lookupUFM old_hpt this_mod_name
1507 -- We're using the dflags for this module now, obtained by
1508 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1509 dflags = ms_hspp_opts summary
1510 prevailing_target = hscTarget (hsc_dflags hsc_env)
1511 local_target = hscTarget dflags
1513 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1514 -- we don't do anything dodgy: these should only work to change
1515 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1516 -- end up trying to link object code to byte code.
1517 target = if prevailing_target /= local_target
1518 && (not (isObjectTarget prevailing_target)
1519 || not (isObjectTarget local_target))
1520 then prevailing_target
1523 -- store the corrected hscTarget into the summary
1524 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1526 -- The old interface is ok if
1527 -- a) we're compiling a source file, and the old HPT
1528 -- entry is for a source file
1529 -- b) we're compiling a hs-boot file
1530 -- Case (b) allows an hs-boot file to get the interface of its
1531 -- real source file on the second iteration of the compilation
1532 -- manager, but that does no harm. Otherwise the hs-boot file
1533 -- will always be recompiled
1538 Just hm_info | isBootSummary summary -> Just iface
1539 | not (mi_boot iface) -> Just iface
1540 | otherwise -> Nothing
1542 iface = hm_iface hm_info
1544 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1545 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1547 compile_it_discard_iface :: GhcMonad m =>
1548 Maybe Linkable -> m HomeModInfo
1549 compile_it_discard_iface
1550 = compile hsc_env summary' mod_index nmods Nothing
1556 -- Regardless of whether we're generating object code or
1557 -- byte code, we can always use an existing object file
1558 -- if it is *stable* (see checkStability).
1559 | is_stable_obj, isJust old_hmi ->
1560 let Just hmi = old_hmi in
1562 -- object is stable, and we have an entry in the
1563 -- old HPT: nothing to do
1565 | is_stable_obj, isNothing old_hmi -> do
1566 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1567 (expectJust "upsweep1" mb_obj_date)
1568 compile_it (Just linkable)
1569 -- object is stable, but we need to load the interface
1570 -- off disk to make a HMI.
1574 ASSERT(isJust old_hmi) -- must be in the old_hpt
1575 let Just hmi = old_hmi in
1577 -- BCO is stable: nothing to do
1579 | Just hmi <- old_hmi,
1580 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1581 linkableTime l >= ms_hs_date summary ->
1583 -- we have an old BCO that is up to date with respect
1584 -- to the source: do a recompilation check as normal.
1588 -- no existing code at all: we must recompile.
1590 -- When generating object code, if there's an up-to-date
1591 -- object file on the disk, then we can use it.
1592 -- However, if the object file is new (compared to any
1593 -- linkable we had from a previous compilation), then we
1594 -- must discard any in-memory interface, because this
1595 -- means the user has compiled the source file
1596 -- separately and generated a new interface, that we must
1597 -- read from the disk.
1599 obj | isObjectTarget obj,
1600 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1603 | Just l <- hm_linkable hmi,
1604 isObjectLinkable l && linkableTime l == obj_date
1605 -> compile_it (Just l)
1607 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1608 compile_it_discard_iface (Just linkable)
1615 -- Filter modules in the HPT
1616 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1617 retainInTopLevelEnvs keep_these hpt
1618 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1620 , let mb_mod_info = lookupUFM hpt mod
1621 , isJust mb_mod_info ]
1623 -- ---------------------------------------------------------------------------
1624 -- Typecheck module loops
1627 See bug #930. This code fixes a long-standing bug in --make. The
1628 problem is that when compiling the modules *inside* a loop, a data
1629 type that is only defined at the top of the loop looks opaque; but
1630 after the loop is done, the structure of the data type becomes
1633 The difficulty is then that two different bits of code have
1634 different notions of what the data type looks like.
1636 The idea is that after we compile a module which also has an .hs-boot
1637 file, we re-generate the ModDetails for each of the modules that
1638 depends on the .hs-boot file, so that everyone points to the proper
1639 TyCons, Ids etc. defined by the real module, not the boot module.
1640 Fortunately re-generating a ModDetails from a ModIface is easy: the
1641 function TcIface.typecheckIface does exactly that.
1643 Picking the modules to re-typecheck is slightly tricky. Starting from
1644 the module graph consisting of the modules that have already been
1645 compiled, we reverse the edges (so they point from the imported module
1646 to the importing module), and depth-first-search from the .hs-boot
1647 node. This gives us all the modules that depend transitively on the
1648 .hs-boot module, and those are exactly the modules that we need to
1651 Following this fix, GHC can compile itself with --make -O2.
1654 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1655 reTypecheckLoop hsc_env ms graph
1656 | not (isBootSummary ms) &&
1657 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1659 let mss = reachableBackwards (ms_mod_name ms) graph
1660 non_boot = filter (not.isBootSummary) mss
1661 debugTraceMsg (hsc_dflags hsc_env) 2 $
1662 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1663 typecheckLoop hsc_env (map ms_mod_name non_boot)
1667 this_mod = ms_mod ms
1669 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1670 typecheckLoop hsc_env mods = do
1672 fixIO $ \new_hpt -> do
1673 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1674 mds <- initIfaceCheck new_hsc_env $
1675 mapM (typecheckIface . hm_iface) hmis
1676 let new_hpt = addListToUFM old_hpt
1677 (zip mods [ hmi{ hm_details = details }
1678 | (hmi,details) <- zip hmis mds ])
1680 return hsc_env{ hsc_HPT = new_hpt }
1682 old_hpt = hsc_HPT hsc_env
1683 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1685 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1686 reachableBackwards mod summaries
1687 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1688 where -- the rest just sets up the graph:
1689 (graph, lookup_node) = moduleGraphNodes False summaries
1690 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1692 -- ---------------------------------------------------------------------------
1693 -- Topological sort of the module graph
1695 type SummaryNode = (ModSummary, Int, [Int])
1698 :: Bool -- Drop hi-boot nodes? (see below)
1702 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1703 -- The resulting list of strongly-connected-components is in topologically
1704 -- sorted order, starting with the module(s) at the bottom of the
1705 -- dependency graph (ie compile them first) and ending with the ones at
1708 -- Drop hi-boot nodes (first boolean arg)?
1710 -- False: treat the hi-boot summaries as nodes of the graph,
1711 -- so the graph must be acyclic
1713 -- True: eliminate the hi-boot nodes, and instead pretend
1714 -- the a source-import of Foo is an import of Foo
1715 -- The resulting graph has no hi-boot nodes, but can be cyclic
1717 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1718 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1720 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1722 initial_graph = case mb_root_mod of
1725 -- restrict the graph to just those modules reachable from
1726 -- the specified module. We do this by building a graph with
1727 -- the full set of nodes, and determining the reachable set from
1728 -- the specified node.
1729 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1730 | otherwise = ghcError (ProgramError "module does not exist")
1731 in graphFromEdgedVertices (seq root (reachableG graph root))
1733 summaryNodeKey :: SummaryNode -> Int
1734 summaryNodeKey (_, k, _) = k
1736 summaryNodeSummary :: SummaryNode -> ModSummary
1737 summaryNodeSummary (s, _, _) = s
1739 moduleGraphNodes :: Bool -> [ModSummary]
1740 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1741 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1743 numbered_summaries = zip summaries [1..]
1745 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1746 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1748 lookup_key :: HscSource -> ModuleName -> Maybe Int
1749 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1751 node_map :: NodeMap SummaryNode
1752 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1753 | node@(s, _, _) <- nodes ]
1755 -- We use integers as the keys for the SCC algorithm
1756 nodes :: [SummaryNode]
1757 nodes = [ (s, key, out_keys)
1758 | (s, key) <- numbered_summaries
1759 -- Drop the hi-boot ones if told to do so
1760 , not (isBootSummary s && drop_hs_boot_nodes)
1761 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1762 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1763 (-- see [boot-edges] below
1764 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1766 else case lookup_key HsBootFile (ms_mod_name s) of
1770 -- [boot-edges] if this is a .hs and there is an equivalent
1771 -- .hs-boot, add a link from the former to the latter. This
1772 -- has the effect of detecting bogus cases where the .hs-boot
1773 -- depends on the .hs, by introducing a cycle. Additionally,
1774 -- it ensures that we will always process the .hs-boot before
1775 -- the .hs, and so the HomePackageTable will always have the
1776 -- most up to date information.
1778 -- Drop hs-boot nodes by using HsSrcFile as the key
1779 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1780 | otherwise = HsBootFile
1782 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1783 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1784 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1785 -- the IsBootInterface parameter True; else False
1788 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1789 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1791 msKey :: ModSummary -> NodeKey
1792 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1794 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1795 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1797 nodeMapElts :: NodeMap a -> [a]
1798 nodeMapElts = eltsFM
1800 -- | If there are {-# SOURCE #-} imports between strongly connected
1801 -- components in the topological sort, then those imports can
1802 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1803 -- were necessary, then the edge would be part of a cycle.
1804 warnUnnecessarySourceImports :: GhcMonad m => DynFlags -> [SCC ModSummary] -> m ()
1805 warnUnnecessarySourceImports dflags sccs =
1806 liftIO $ printBagOfWarnings dflags (listToBag (concatMap (check.flattenSCC) sccs))
1808 let mods_in_this_cycle = map ms_mod_name ms in
1809 [ warn i | m <- ms, i <- ms_srcimps m,
1810 unLoc i `notElem` mods_in_this_cycle ]
1812 warn :: Located ModuleName -> WarnMsg
1815 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1816 <+> quotes (ppr mod))
1818 -----------------------------------------------------------------------------
1819 -- Downsweep (dependency analysis)
1821 -- Chase downwards from the specified root set, returning summaries
1822 -- for all home modules encountered. Only follow source-import
1825 -- We pass in the previous collection of summaries, which is used as a
1826 -- cache to avoid recalculating a module summary if the source is
1829 -- The returned list of [ModSummary] nodes has one node for each home-package
1830 -- module, plus one for any hs-boot files. The imports of these nodes
1831 -- are all there, including the imports of non-home-package modules.
1833 downsweep :: GhcMonad m =>
1835 -> [ModSummary] -- Old summaries
1836 -> [ModuleName] -- Ignore dependencies on these; treat
1837 -- them as if they were package modules
1838 -> Bool -- True <=> allow multiple targets to have
1839 -- the same module name; this is
1840 -- very useful for ghc -M
1842 -- The elts of [ModSummary] all have distinct
1843 -- (Modules, IsBoot) identifiers, unless the Bool is true
1844 -- in which case there can be repeats
1845 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1846 = do -- catch error messages and return them
1847 --handleErrMsg -- should be covered by GhcMonad now
1848 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1849 rootSummaries <- mapM getRootSummary roots
1850 let root_map = mkRootMap rootSummaries
1851 checkDuplicates root_map
1852 summs <- loop (concatMap msDeps rootSummaries) root_map
1855 roots = hsc_targets hsc_env
1857 old_summary_map :: NodeMap ModSummary
1858 old_summary_map = mkNodeMap old_summaries
1860 getRootSummary :: GhcMonad m => Target -> m ModSummary
1861 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1862 = do exists <- liftIO $ doesFileExist file
1864 then summariseFile hsc_env old_summaries file mb_phase
1865 obj_allowed maybe_buf
1866 else throwErrMsg $ mkPlainErrMsg noSrcSpan $
1867 text "can't find file:" <+> text file
1868 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1869 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1870 (L rootLoc modl) obj_allowed
1872 case maybe_summary of
1873 Nothing -> packageModErr modl
1876 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1878 -- In a root module, the filename is allowed to diverge from the module
1879 -- name, so we have to check that there aren't multiple root files
1880 -- defining the same module (otherwise the duplicates will be silently
1881 -- ignored, leading to confusing behaviour).
1882 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1883 checkDuplicates root_map
1884 | allow_dup_roots = return ()
1885 | null dup_roots = return ()
1886 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1888 dup_roots :: [[ModSummary]] -- Each at least of length 2
1889 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1891 loop :: GhcMonad m =>
1892 [(Located ModuleName,IsBootInterface)]
1893 -- Work list: process these modules
1894 -> NodeMap [ModSummary]
1895 -- Visited set; the range is a list because
1896 -- the roots can have the same module names
1897 -- if allow_dup_roots is True
1899 -- The result includes the worklist, except
1900 -- for those mentioned in the visited set
1901 loop [] done = return (concat (nodeMapElts done))
1902 loop ((wanted_mod, is_boot) : ss) done
1903 | Just summs <- lookupFM done key
1904 = if isSingleton summs then
1907 do { liftIO $ multiRootsErr summs; return [] }
1909 = do mb_s <- summariseModule hsc_env old_summary_map
1910 is_boot wanted_mod True
1913 Nothing -> loop ss done
1914 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1916 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1918 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1919 mkRootMap summaries = addListToFM_C (++) emptyFM
1920 [ (msKey s, [s]) | s <- summaries ]
1922 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1923 -- (msDeps s) returns the dependencies of the ModSummary s.
1924 -- A wrinkle is that for a {-# SOURCE #-} import we return
1925 -- *both* the hs-boot file
1926 -- *and* the source file
1927 -- as "dependencies". That ensures that the list of all relevant
1928 -- modules always contains B.hs if it contains B.hs-boot.
1929 -- Remember, this pass isn't doing the topological sort. It's
1930 -- just gathering the list of all relevant ModSummaries
1932 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1933 ++ [ (m,False) | m <- ms_imps s ]
1935 -----------------------------------------------------------------------------
1936 -- Summarising modules
1938 -- We have two types of summarisation:
1940 -- * Summarise a file. This is used for the root module(s) passed to
1941 -- cmLoadModules. The file is read, and used to determine the root
1942 -- module name. The module name may differ from the filename.
1944 -- * Summarise a module. We are given a module name, and must provide
1945 -- a summary. The finder is used to locate the file in which the module
1951 -> [ModSummary] -- old summaries
1952 -> FilePath -- source file name
1953 -> Maybe Phase -- start phase
1954 -> Bool -- object code allowed?
1955 -> Maybe (StringBuffer,ClockTime)
1958 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1959 -- we can use a cached summary if one is available and the
1960 -- source file hasn't changed, But we have to look up the summary
1961 -- by source file, rather than module name as we do in summarise.
1962 | Just old_summary <- findSummaryBySourceFile old_summaries file
1964 let location = ms_location old_summary
1966 -- return the cached summary if the source didn't change
1967 src_timestamp <- case maybe_buf of
1968 Just (_,t) -> return t
1969 Nothing -> liftIO $ getModificationTime file
1970 -- The file exists; we checked in getRootSummary above.
1971 -- If it gets removed subsequently, then this
1972 -- getModificationTime may fail, but that's the right
1975 if ms_hs_date old_summary == src_timestamp
1976 then do -- update the object-file timestamp
1978 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1979 || obj_allowed -- bug #1205
1980 then liftIO $ getObjTimestamp location False
1982 return old_summary{ ms_obj_date = obj_timestamp }
1990 let dflags = hsc_dflags hsc_env
1992 (dflags', hspp_fn, buf)
1993 <- preprocessFile hsc_env file mb_phase maybe_buf
1995 (srcimps,the_imps, L _ mod_name) <- liftIO $ getImports dflags' buf hspp_fn file
1997 -- Make a ModLocation for this file
1998 location <- liftIO $ mkHomeModLocation dflags mod_name file
2000 -- Tell the Finder cache where it is, so that subsequent calls
2001 -- to findModule will find it, even if it's not on any search path
2002 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2004 src_timestamp <- case maybe_buf of
2005 Just (_,t) -> return t
2006 Nothing -> liftIO $ getModificationTime file
2007 -- getMofificationTime may fail
2009 -- when the user asks to load a source file by name, we only
2010 -- use an object file if -fobject-code is on. See #1205.
2012 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2013 || obj_allowed -- bug #1205
2014 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2017 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2018 ms_location = location,
2019 ms_hspp_file = hspp_fn,
2020 ms_hspp_opts = dflags',
2021 ms_hspp_buf = Just buf,
2022 ms_srcimps = srcimps, ms_imps = the_imps,
2023 ms_hs_date = src_timestamp,
2024 ms_obj_date = obj_timestamp })
2026 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2027 findSummaryBySourceFile summaries file
2028 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2029 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2033 -- Summarise a module, and pick up source and timestamp.
2037 -> NodeMap ModSummary -- Map of old summaries
2038 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2039 -> Located ModuleName -- Imported module to be summarised
2040 -> Bool -- object code allowed?
2041 -> Maybe (StringBuffer, ClockTime)
2042 -> [ModuleName] -- Modules to exclude
2043 -> m (Maybe ModSummary) -- Its new summary
2045 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2046 obj_allowed maybe_buf excl_mods
2047 | wanted_mod `elem` excl_mods
2050 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2051 = do -- Find its new timestamp; all the
2052 -- ModSummaries in the old map have valid ml_hs_files
2053 let location = ms_location old_summary
2054 src_fn = expectJust "summariseModule" (ml_hs_file location)
2056 -- check the modification time on the source file, and
2057 -- return the cached summary if it hasn't changed. If the
2058 -- file has disappeared, we need to call the Finder again.
2060 Just (_,t) -> check_timestamp old_summary location src_fn t
2062 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2064 Right t -> check_timestamp old_summary location src_fn t
2065 Left e | isDoesNotExistError e -> find_it
2066 | otherwise -> liftIO $ ioError e
2068 | otherwise = find_it
2070 dflags = hsc_dflags hsc_env
2072 hsc_src = if is_boot then HsBootFile else HsSrcFile
2074 check_timestamp old_summary location src_fn src_timestamp
2075 | ms_hs_date old_summary == src_timestamp = do
2076 -- update the object-file timestamp
2077 obj_timestamp <- liftIO $
2078 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2079 || obj_allowed -- bug #1205
2080 then getObjTimestamp location is_boot
2082 return (Just old_summary{ ms_obj_date = obj_timestamp })
2084 -- source changed: re-summarise.
2085 new_summary location (ms_mod old_summary) src_fn src_timestamp
2088 -- Don't use the Finder's cache this time. If the module was
2089 -- previously a package module, it may have now appeared on the
2090 -- search path, so we want to consider it to be a home module. If
2091 -- the module was previously a home module, it may have moved.
2092 liftIO $ uncacheModule hsc_env wanted_mod
2093 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2096 | isJust (ml_hs_file location) ->
2098 just_found location mod
2100 -- Drop external-pkg
2101 ASSERT(modulePackageId mod /= thisPackage dflags)
2104 err -> liftIO $ noModError dflags loc wanted_mod err
2107 just_found location mod = do
2108 -- Adjust location to point to the hs-boot source file,
2109 -- hi file, object file, when is_boot says so
2110 let location' | is_boot = addBootSuffixLocn location
2111 | otherwise = location
2112 src_fn = expectJust "summarise2" (ml_hs_file location')
2114 -- Check that it exists
2115 -- It might have been deleted since the Finder last found it
2116 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2118 Nothing -> noHsFileErr loc src_fn
2119 Just t -> new_summary location' mod src_fn t
2122 new_summary location mod src_fn src_timestamp
2124 -- Preprocess the source file and get its imports
2125 -- The dflags' contains the OPTIONS pragmas
2126 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2127 (srcimps, the_imps, L mod_loc mod_name) <- liftIO $ getImports dflags' buf hspp_fn src_fn
2129 when (mod_name /= wanted_mod) $
2130 throwErrMsg $ mkPlainErrMsg mod_loc $
2131 text "File name does not match module name:"
2132 $$ text "Saw:" <+> quotes (ppr mod_name)
2133 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2135 -- Find the object timestamp, and return the summary
2136 obj_timestamp <- liftIO $
2137 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2138 || obj_allowed -- bug #1205
2139 then getObjTimestamp location is_boot
2142 return (Just (ModSummary { ms_mod = mod,
2143 ms_hsc_src = hsc_src,
2144 ms_location = location,
2145 ms_hspp_file = hspp_fn,
2146 ms_hspp_opts = dflags',
2147 ms_hspp_buf = Just buf,
2148 ms_srcimps = srcimps,
2150 ms_hs_date = src_timestamp,
2151 ms_obj_date = obj_timestamp }))
2154 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2155 getObjTimestamp location is_boot
2156 = if is_boot then return Nothing
2157 else modificationTimeIfExists (ml_obj_file location)
2160 preprocessFile :: GhcMonad m =>
2163 -> Maybe Phase -- ^ Starting phase
2164 -> Maybe (StringBuffer,ClockTime)
2165 -> m (DynFlags, FilePath, StringBuffer)
2166 preprocessFile hsc_env src_fn mb_phase Nothing
2168 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2169 buf <- liftIO $ hGetStringBuffer hspp_fn
2170 return (dflags', hspp_fn, buf)
2172 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2174 let dflags = hsc_dflags hsc_env
2175 -- case we bypass the preprocessing stage?
2177 local_opts = getOptions dflags buf src_fn
2179 (dflags', leftovers, warns)
2180 <- parseDynamicNoPackageFlags dflags local_opts
2181 liftIO $ checkProcessArgsResult leftovers -- XXX: throws exceptions
2182 liftIO $ handleFlagWarnings dflags' warns -- XXX: throws exceptions
2186 | Just (Unlit _) <- mb_phase = True
2187 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2188 -- note: local_opts is only required if there's no Unlit phase
2189 | dopt Opt_Cpp dflags' = True
2190 | dopt Opt_Pp dflags' = True
2193 when needs_preprocessing $
2194 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2196 return (dflags', src_fn, buf)
2199 -----------------------------------------------------------------------------
2201 -----------------------------------------------------------------------------
2203 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2204 -- ToDo: we don't have a proper line number for this error
2205 noModError dflags loc wanted_mod err
2206 = throwErrMsg $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2208 noHsFileErr :: SrcSpan -> String -> a
2209 noHsFileErr loc path
2210 = throwErrMsg $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2212 packageModErr :: ModuleName -> a
2214 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2215 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2217 multiRootsErr :: [ModSummary] -> IO ()
2218 multiRootsErr [] = panic "multiRootsErr"
2219 multiRootsErr summs@(summ1:_)
2220 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2221 text "module" <+> quotes (ppr mod) <+>
2222 text "is defined in multiple files:" <+>
2223 sep (map text files)
2226 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2228 cyclicModuleErr :: [ModSummary] -> SDoc
2230 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2231 2 (vcat (map show_one ms))
2233 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2234 nest 2 $ ptext (sLit "imports:") <+>
2235 (pp_imps HsBootFile (ms_srcimps ms)
2236 $$ pp_imps HsSrcFile (ms_imps ms))]
2237 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2238 pp_imps src mods = fsep (map (show_mod src) mods)
2241 -- | Inform GHC that the working directory has changed. GHC will flush
2242 -- its cache of module locations, since it may no longer be valid.
2243 -- Note: if you change the working directory, you should also unload
2244 -- the current program (set targets to empty, followed by load).
2245 workingDirectoryChanged :: GhcMonad m => m ()
2246 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2248 -- -----------------------------------------------------------------------------
2249 -- inspecting the session
2251 -- | Get the module dependency graph.
2252 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2253 getModuleGraph = liftM hsc_mod_graph getSession
2255 -- | Return @True@ <==> module is loaded.
2256 isLoaded :: GhcMonad m => ModuleName -> m Bool
2257 isLoaded m = withSession $ \hsc_env ->
2258 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2260 -- | Return the bindings for the current interactive session.
2261 getBindings :: GhcMonad m => m [TyThing]
2262 getBindings = withSession $ \hsc_env ->
2263 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2264 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2266 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2267 filtered = foldr f (const []) tmp_ids emptyUniqSet
2269 | uniq `elementOfUniqSet` set = rest set
2270 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2271 where uniq = getUnique (nameOccName (idName id))
2275 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2276 getPrintUnqual = withSession $ \hsc_env ->
2277 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2279 -- | Container for information about a 'Module'.
2280 data ModuleInfo = ModuleInfo {
2281 minf_type_env :: TypeEnv,
2282 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2283 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2284 minf_instances :: [Instance]
2286 ,minf_modBreaks :: ModBreaks
2288 -- ToDo: this should really contain the ModIface too
2290 -- We don't want HomeModInfo here, because a ModuleInfo applies
2291 -- to package modules too.
2293 -- | Request information about a loaded 'Module'
2294 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2295 getModuleInfo mdl = withSession $ \hsc_env -> do
2296 let mg = hsc_mod_graph hsc_env
2297 if mdl `elem` map ms_mod mg
2298 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2300 {- if isHomeModule (hsc_dflags hsc_env) mdl
2302 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2303 -- getPackageModuleInfo will attempt to find the interface, so
2304 -- we don't want to call it for a home module, just in case there
2305 -- was a problem loading the module and the interface doesn't
2306 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2308 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2310 getPackageModuleInfo hsc_env mdl = do
2311 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2313 Nothing -> return Nothing
2315 eps <- readIORef (hsc_EPS hsc_env)
2317 names = availsToNameSet avails
2319 tys = [ ty | name <- concatMap availNames avails,
2320 Just ty <- [lookupTypeEnv pte name] ]
2322 return (Just (ModuleInfo {
2323 minf_type_env = mkTypeEnv tys,
2324 minf_exports = names,
2325 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2326 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2327 minf_modBreaks = emptyModBreaks
2330 getPackageModuleInfo _hsc_env _mdl = do
2331 -- bogusly different for non-GHCI (ToDo)
2335 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2336 getHomeModuleInfo hsc_env mdl =
2337 case lookupUFM (hsc_HPT hsc_env) mdl of
2338 Nothing -> return Nothing
2340 let details = hm_details hmi
2341 return (Just (ModuleInfo {
2342 minf_type_env = md_types details,
2343 minf_exports = availsToNameSet (md_exports details),
2344 minf_rdr_env = mi_globals $! hm_iface hmi,
2345 minf_instances = md_insts details
2347 ,minf_modBreaks = getModBreaks hmi
2351 -- | The list of top-level entities defined in a module
2352 modInfoTyThings :: ModuleInfo -> [TyThing]
2353 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2355 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2356 modInfoTopLevelScope minf
2357 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2359 modInfoExports :: ModuleInfo -> [Name]
2360 modInfoExports minf = nameSetToList $! minf_exports minf
2362 -- | Returns the instances defined by the specified module.
2363 -- Warning: currently unimplemented for package modules.
2364 modInfoInstances :: ModuleInfo -> [Instance]
2365 modInfoInstances = minf_instances
2367 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2368 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2370 mkPrintUnqualifiedForModule :: GhcMonad m =>
2372 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2373 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2374 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2376 modInfoLookupName :: GhcMonad m =>
2378 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2379 modInfoLookupName minf name = withSession $ \hsc_env -> do
2380 case lookupTypeEnv (minf_type_env minf) name of
2381 Just tyThing -> return (Just tyThing)
2383 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2384 return $! lookupType (hsc_dflags hsc_env)
2385 (hsc_HPT hsc_env) (eps_PTE eps) name
2388 modInfoModBreaks :: ModuleInfo -> ModBreaks
2389 modInfoModBreaks = minf_modBreaks
2392 isDictonaryId :: Id -> Bool
2394 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2396 -- | Looks up a global name: that is, any top-level name in any
2397 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2398 -- the interactive context, and therefore does not require a preceding
2400 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2401 lookupGlobalName name = withSession $ \hsc_env -> do
2402 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2403 return $! lookupType (hsc_dflags hsc_env)
2404 (hsc_HPT hsc_env) (eps_PTE eps) name
2407 -- | get the GlobalRdrEnv for a session
2408 getGRE :: GhcMonad m => m GlobalRdrEnv
2409 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2412 -- -----------------------------------------------------------------------------
2413 -- Misc exported utils
2415 dataConType :: DataCon -> Type
2416 dataConType dc = idType (dataConWrapId dc)
2418 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2419 pprParenSymName :: NamedThing a => a -> SDoc
2420 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2422 -- ----------------------------------------------------------------------------
2427 -- - Data and Typeable instances for HsSyn.
2429 -- ToDo: check for small transformations that happen to the syntax in
2430 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2432 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2433 -- to get from TyCons, Ids etc. to TH syntax (reify).
2435 -- :browse will use either lm_toplev or inspect lm_interface, depending
2436 -- on whether the module is interpreted or not.
2440 -- Extract the filename, stringbuffer content and dynflags associed to a module
2442 -- XXX: Explain pre-conditions
2443 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
2444 getModuleSourceAndFlags mod = do
2445 m <- getModSummary (moduleName mod)
2446 case ml_hs_file $ ms_location m of
2447 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
2448 Just sourceFile -> do
2449 source <- liftIO $ hGetStringBuffer sourceFile
2450 return (sourceFile, source, ms_hspp_opts m)
2453 -- | Return module source as token stream, including comments.
2455 -- The module must be in the module graph and its source must be available.
2456 -- Throws a 'HscTypes.SourceError' on parse error.
2457 getTokenStream :: GhcMonad m => Module -> m [Located Token]
2458 getTokenStream mod = do
2459 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2460 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2461 case lexTokenStream source startLoc flags of
2462 POk _ ts -> return ts
2463 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2465 -- | Give even more information on the source than 'getTokenStream'
2466 -- This function allows reconstructing the source completely with
2467 -- 'showRichTokenStream'.
2468 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
2469 getRichTokenStream mod = do
2470 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2471 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2472 case lexTokenStream source startLoc flags of
2473 POk _ ts -> return $ addSourceToTokens startLoc source ts
2474 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2476 -- | Given a source location and a StringBuffer corresponding to this
2477 -- location, return a rich token stream with the source associated to the
2479 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
2480 -> [(Located Token, String)]
2481 addSourceToTokens _ _ [] = []
2482 addSourceToTokens loc buf (t@(L span _) : ts)
2483 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
2484 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
2486 (newLoc, newBuf, str) = go "" loc buf
2487 start = srcSpanStart span
2488 end = srcSpanEnd span
2489 go acc loc buf | loc < start = go acc nLoc nBuf
2490 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
2491 | otherwise = (loc, buf, reverse acc)
2492 where (ch, nBuf) = nextChar buf
2493 nLoc = advanceSrcLoc loc ch
2496 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
2497 -- return source code almost identical to the original code (except for
2498 -- insignificant whitespace.)
2499 showRichTokenStream :: [(Located Token, String)] -> String
2500 showRichTokenStream ts = go startLoc ts ""
2501 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
2502 startLoc = mkSrcLoc sourceFile 0 0
2504 go loc ((L span _, str):ts)
2505 | not (isGoodSrcSpan span) = go loc ts
2506 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
2509 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
2510 . ((replicate tokCol ' ') ++)
2513 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
2514 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
2515 tokEnd = srcSpanEnd span
2517 -- -----------------------------------------------------------------------------
2518 -- Interactive evaluation
2520 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2521 -- filesystem and package database to find the corresponding 'Module',
2522 -- using the algorithm that is used for an @import@ declaration.
2523 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2524 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2526 dflags = hsc_dflags hsc_env
2527 hpt = hsc_HPT hsc_env
2528 this_pkg = thisPackage dflags
2530 case lookupUFM hpt mod_name of
2531 Just mod_info -> return (mi_module (hm_iface mod_info))
2532 _not_a_home_module -> do
2533 res <- findImportedModule hsc_env mod_name maybe_pkg
2535 Found _ m | modulePackageId m /= this_pkg -> return m
2536 | otherwise -> ghcError (CmdLineError (showSDoc $
2537 text "module" <+> quotes (ppr (moduleName m)) <+>
2538 text "is not loaded"))
2539 err -> let msg = cannotFindModule dflags mod_name err in
2540 ghcError (CmdLineError (showSDoc msg))
2543 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2544 getHistorySpan h = withSession $ \hsc_env ->
2545 return$ InteractiveEval.getHistorySpan hsc_env h
2547 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
2548 obtainTermFromVal bound force ty a =
2549 withSession $ \hsc_env ->
2550 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
2552 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
2553 obtainTermFromId bound force id =
2554 withSession $ \hsc_env ->
2555 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id