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 TypecheckedMod, ParsedMod,
53 moduleInfo, renamedSource, typecheckedSource,
54 parsedSource, coreModule,
55 compileToCoreModule, compileToCoreSimplified,
59 -- * Parsing Haddock comments
62 -- * Inspecting the module structure of the program
63 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
68 -- * Inspecting modules
75 modInfoIsExportedName,
79 mkPrintUnqualifiedForModule,
82 PrintUnqualified, alwaysQualify,
84 -- * Interactive evaluation
85 getBindings, getPrintUnqual,
88 setContext, getContext,
98 runStmt, SingleStep(..),
100 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
101 resumeHistory, resumeHistoryIx),
102 History(historyBreakInfo, historyEnclosingDecl),
103 GHC.getHistorySpan, getHistoryModule,
106 InteractiveEval.back,
107 InteractiveEval.forward,
110 InteractiveEval.compileExpr, HValue, dynCompileExpr,
112 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
114 ModBreaks(..), BreakIndex,
115 BreakInfo(breakInfo_number, breakInfo_module),
116 BreakArray, setBreakOn, setBreakOff, getBreak,
119 -- * Abstract syntax elements
125 Module, mkModule, pprModule, moduleName, modulePackageId,
126 ModuleName, mkModuleName, moduleNameString,
130 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
132 RdrName(Qual,Unqual),
136 isImplicitId, isDeadBinder,
137 isExportedId, isLocalId, isGlobalId,
139 isPrimOpId, isFCallId, isClassOpId_maybe,
140 isDataConWorkId, idDataCon,
141 isBottomingId, isDictonaryId,
142 recordSelectorFieldLabel,
144 -- ** Type constructors
146 tyConTyVars, tyConDataCons, tyConArity,
147 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
149 synTyConDefn, synTyConType, synTyConResKind,
155 -- ** Data constructors
157 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
158 dataConIsInfix, isVanillaDataCon,
160 StrictnessMark(..), isMarkedStrict,
164 classMethods, classSCTheta, classTvsFds,
169 instanceDFunId, pprInstance, pprInstanceHdr,
171 -- ** Types and Kinds
172 Type, splitForAllTys, funResultTy,
173 pprParendType, pprTypeApp,
176 ThetaType, pprThetaArrow,
182 module HsSyn, -- ToDo: remove extraneous bits
186 defaultFixity, maxPrecedence,
190 -- ** Source locations
192 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
193 srcLocFile, srcLocLine, srcLocCol,
195 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
196 srcSpanStart, srcSpanEnd,
198 srcSpanStartLine, srcSpanEndLine,
199 srcSpanStartCol, srcSpanEndCol,
204 -- *** Constructing Located
205 noLoc, mkGeneralLocated,
207 -- *** Deconstructing Located
210 -- *** Combining and comparing Located values
211 eqLocated, cmpLocated, combineLocs, addCLoc,
212 leftmost_smallest, leftmost_largest, rightmost,
216 GhcException(..), showGhcException,
218 -- * Token stream manipulations
220 getTokenStream, getRichTokenStream,
221 showRichTokenStream, addSourceToTokens,
231 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
232 * what StaticFlags should we expose, if any?
235 #include "HsVersions.h"
238 import qualified Linker
239 import Linker ( HValue )
243 import InteractiveEval
248 import TcRnTypes hiding (LIE)
249 import TcRnMonad ( initIfaceCheck )
253 import qualified HsSyn -- hack as we want to reexport the whole module
254 import HsSyn hiding ((<.>))
255 import Type hiding (typeKind)
256 import TcType hiding (typeKind)
259 import TysPrim ( alphaTyVars )
264 import Name hiding ( varName )
265 import OccName ( parenSymOcc )
266 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
268 import FamInstEnv ( emptyFamInstEnv )
272 import DriverPipeline
273 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
279 import StaticFlagParser
280 import qualified StaticFlags
281 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
291 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
295 import StringBuffer ( StringBuffer, hGetStringBuffer, nextChar )
298 import Maybes ( expectJust, mapCatMaybes )
300 import HaddockLex ( tokenise )
304 import Control.Concurrent
305 import System.Directory ( getModificationTime, doesFileExist,
306 getCurrentDirectory )
309 import qualified Data.List as List
310 import Data.Typeable ( Typeable )
311 import Data.Word ( Word8 )
313 import System.Exit ( exitWith, ExitCode(..) )
314 import System.Time ( ClockTime, getClockTime )
317 import System.FilePath
319 import System.IO.Error ( try, isDoesNotExistError )
320 import Prelude hiding (init)
323 -- -----------------------------------------------------------------------------
324 -- Exception handlers
326 -- | Install some default exception handlers and run the inner computation.
327 -- Unless you want to handle exceptions yourself, you should wrap this around
328 -- the top level of your program. The default handlers output the error
329 -- message(s) to stderr and exit cleanly.
330 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
331 defaultErrorHandler dflags inner =
332 -- top-level exception handler: any unrecognised exception is a compiler bug.
333 ghandle (\exception -> liftIO $ do
335 case fromException exception of
336 -- an IO exception probably isn't our fault, so don't panic
337 Just (ioe :: IOException) ->
338 fatalErrorMsg dflags (text (show ioe))
339 _ -> case fromException exception of
340 Just StackOverflow ->
341 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
342 _ -> case fromException exception of
343 Just (ex :: ExitCode) -> throw ex
346 (text (show (Panic (show exception))))
347 exitWith (ExitFailure 1)
350 -- error messages propagated as exceptions
355 PhaseFailed _ code -> exitWith code
356 Interrupted -> exitWith (ExitFailure 1)
357 _ -> do fatalErrorMsg dflags (text (show ge))
358 exitWith (ExitFailure 1)
362 -- | Install a default cleanup handler to remove temporary files deposited by
363 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
364 -- want to override the error handling, but still get the ordinary cleanup
366 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
367 DynFlags -> m a -> m a
368 defaultCleanupHandler dflags inner =
369 -- make sure we clean up after ourselves
372 cleanTempFiles dflags
375 -- exceptions will be blocked while we clean the temporary files,
376 -- so there shouldn't be any difficulty if we receive further
379 -- | Print the error message and all warnings. Useful inside exception
380 -- handlers. Clears warnings after printing.
381 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
382 printExceptionAndWarnings err = do
383 let errs = srcErrorMessages err
385 dflags <- getSessionDynFlags
387 -- Empty errors means we failed due to -Werror. (Since this function
388 -- takes a source error as argument, we know for sure _some_ error
389 -- did indeed happen.)
391 printBagOfWarnings dflags warns
392 printBagOfErrors dflags (unitBag warnIsErrorMsg)
393 else liftIO $ printBagOfErrors dflags errs
396 -- | Print all accumulated warnings using 'log_action'.
397 printWarnings :: GhcMonad m => m ()
399 dflags <- getSessionDynFlags
401 liftIO $ printBagOfWarnings dflags warns
404 -- | Run function for the 'Ghc' monad.
406 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
407 -- to this function will create a new session which should not be shared among
410 -- Any errors not handled inside the 'Ghc' action are propagated as IO
413 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
414 -> Ghc a -- ^ The action to perform.
416 runGhc mb_top_dir ghc = do
417 wref <- newIORef emptyBag
418 ref <- newIORef undefined
419 let session = Session ref wref
420 flip unGhc session $ do
421 initGhcMonad mb_top_dir
423 -- XXX: unregister interrupt handlers here?
425 -- | Run function for 'GhcT' monad transformer.
427 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
428 -- to this function will create a new session which should not be shared among
431 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
432 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
433 -> GhcT m a -- ^ The action to perform.
435 runGhcT mb_top_dir ghct = do
436 wref <- liftIO $ newIORef emptyBag
437 ref <- liftIO $ newIORef undefined
438 let session = Session ref wref
439 flip unGhcT session $ do
440 initGhcMonad mb_top_dir
443 -- | Initialise a GHC session.
445 -- If you implement a custom 'GhcMonad' you must call this function in the
446 -- monad run function. It will initialise the session variable and clear all
449 -- The first argument should point to the directory where GHC's library files
450 -- reside. More precisely, this should be the output of @ghc --print-libdir@
451 -- of the version of GHC the module using this API is compiled with. For
452 -- portability, you should use the @ghc-paths@ package, available at
453 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
455 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
456 initGhcMonad mb_top_dir = do
458 main_thread <- liftIO $ myThreadId
459 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
460 liftIO $ installSignalHandlers
462 liftIO $ StaticFlags.initStaticOpts
464 dflags0 <- liftIO $ initDynFlags defaultDynFlags
465 dflags <- liftIO $ initSysTools mb_top_dir dflags0
466 env <- liftIO $ newHscEnv dflags
470 -- -----------------------------------------------------------------------------
473 -- | Grabs the DynFlags from the Session
474 getSessionDynFlags :: GhcMonad m => m DynFlags
475 getSessionDynFlags = withSession (return . hsc_dflags)
477 -- | Updates the DynFlags in a Session. This also reads
478 -- the package database (unless it has already been read),
479 -- and prepares the compilers knowledge about packages. It
480 -- can be called again to load new packages: just add new
481 -- package flags to (packageFlags dflags).
483 -- Returns a list of new packages that may need to be linked in using
484 -- the dynamic linker (see 'linkPackages') as a result of new package
485 -- flags. If you are not doing linking or doing static linking, you
486 -- can ignore the list of packages returned.
488 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
489 setSessionDynFlags dflags = do
490 (dflags', preload) <- liftIO $ initPackages dflags
491 modifySession (\h -> h{ hsc_dflags = dflags' })
494 -- | If there is no -o option, guess the name of target executable
495 -- by using top-level source file name as a base.
496 guessOutputFile :: GhcMonad m => m ()
497 guessOutputFile = modifySession $ \env ->
498 let dflags = hsc_dflags env
499 mod_graph = hsc_mod_graph env
500 mainModuleSrcPath :: Maybe String
501 mainModuleSrcPath = do
502 let isMain = (== mainModIs dflags) . ms_mod
503 [ms] <- return (filter isMain mod_graph)
504 ml_hs_file (ms_location ms)
505 name = fmap dropExtension mainModuleSrcPath
507 #if defined(mingw32_HOST_OS)
508 -- we must add the .exe extention unconditionally here, otherwise
509 -- when name has an extension of its own, the .exe extension will
510 -- not be added by DriverPipeline.exeFileName. See #2248
511 name_exe = fmap (<.> "exe") name
516 case outputFile dflags of
518 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
520 -- -----------------------------------------------------------------------------
523 -- ToDo: think about relative vs. absolute file paths. And what
524 -- happens when the current directory changes.
526 -- | Sets the targets for this session. Each target may be a module name
527 -- or a filename. The targets correspond to the set of root modules for
528 -- the program\/library. Unloading the current program is achieved by
529 -- setting the current set of targets to be empty, followed by 'load'.
530 setTargets :: GhcMonad m => [Target] -> m ()
531 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
533 -- | Returns the current set of targets
534 getTargets :: GhcMonad m => m [Target]
535 getTargets = withSession (return . hsc_targets)
537 -- | Add another target.
538 addTarget :: GhcMonad m => Target -> m ()
540 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
543 removeTarget :: GhcMonad m => TargetId -> m ()
544 removeTarget target_id
545 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
547 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
549 -- | Attempts to guess what Target a string refers to. This function
550 -- implements the @--make@/GHCi command-line syntax for filenames:
552 -- - if the string looks like a Haskell source filename, then interpret it
555 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
558 -- - otherwise interpret the string as a module name
560 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
561 guessTarget str (Just phase)
562 = return (Target (TargetFile str (Just phase)) True Nothing)
563 guessTarget str Nothing
564 | isHaskellSrcFilename file
565 = return (target (TargetFile file Nothing))
567 = do exists <- liftIO $ doesFileExist hs_file
569 then return (target (TargetFile hs_file Nothing))
571 exists <- liftIO $ doesFileExist lhs_file
573 then return (target (TargetFile lhs_file Nothing))
575 if looksLikeModuleName file
576 then return (target (TargetModule (mkModuleName file)))
579 (ProgramError (showSDoc $
580 text "target" <+> quotes (text file) <+>
581 text "is not a module name or a source file"))
584 | '*':rest <- str = (rest, False)
585 | otherwise = (str, True)
587 hs_file = file <.> "hs"
588 lhs_file = file <.> "lhs"
590 target tid = Target tid obj_allowed Nothing
592 -- -----------------------------------------------------------------------------
593 -- Extending the program scope
595 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
596 extendGlobalRdrScope rdrElts
597 = modifySession $ \hscEnv ->
598 let global_rdr = hsc_global_rdr_env hscEnv
599 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
601 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
602 setGlobalRdrScope rdrElts
603 = modifySession $ \hscEnv ->
604 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
606 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
607 extendGlobalTypeScope ids
608 = modifySession $ \hscEnv ->
609 let global_type = hsc_global_type_env hscEnv
610 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
612 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
613 setGlobalTypeScope ids
614 = modifySession $ \hscEnv ->
615 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
617 -- -----------------------------------------------------------------------------
618 -- Parsing Haddock comments
620 parseHaddockComment :: String -> Either String (HsDoc RdrName)
621 parseHaddockComment string =
622 case parseHaddockParagraphs (tokenise string) of
626 -- -----------------------------------------------------------------------------
627 -- Loading the program
629 -- | Perform a dependency analysis starting from the current targets
630 -- and update the session with the new module graph.
631 depanal :: GhcMonad m =>
632 [ModuleName] -- ^ excluded modules
633 -> Bool -- ^ allow duplicate roots
635 depanal excluded_mods allow_dup_roots = do
636 hsc_env <- getSession
638 dflags = hsc_dflags hsc_env
639 targets = hsc_targets hsc_env
640 old_graph = hsc_mod_graph hsc_env
642 liftIO $ showPass dflags "Chasing dependencies"
643 liftIO $ debugTraceMsg dflags 2 (hcat [
644 text "Chasing modules from: ",
645 hcat (punctuate comma (map pprTarget targets))])
647 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
648 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
653 | LoadUpTo ModuleName
654 | LoadDependenciesOf ModuleName
656 -- | Try to load the program. Calls 'loadWithLogger' with the default
657 -- compiler that just immediately logs all warnings and errors.
658 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
660 loadWithLogger defaultWarnErrLogger how_much
662 -- | A function called to log warnings and errors.
663 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
665 defaultWarnErrLogger :: WarnErrLogger
666 defaultWarnErrLogger Nothing = printWarnings
667 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
669 -- | Try to load the program. If a Module is supplied, then just
670 -- attempt to load up to this target. If no Module is supplied,
671 -- then try to load all targets.
673 -- The first argument is a function that is called after compiling each
674 -- module to print wanrings and errors.
676 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
677 loadWithLogger logger how_much = do
678 -- Dependency analysis first. Note that this fixes the module graph:
679 -- even if we don't get a fully successful upsweep, the full module
680 -- graph is still retained in the Session. We can tell which modules
681 -- were successfully loaded by inspecting the Session's HPT.
682 mod_graph <- depanal [] False
683 load2 how_much mod_graph logger
685 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary] -> WarnErrLogger
687 load2 how_much mod_graph logger = do
689 hsc_env <- getSession
691 let hpt1 = hsc_HPT hsc_env
692 let dflags = hsc_dflags hsc_env
694 -- The "bad" boot modules are the ones for which we have
695 -- B.hs-boot in the module graph, but no B.hs
696 -- The downsweep should have ensured this does not happen
698 let all_home_mods = [ms_mod_name s
699 | s <- mod_graph, not (isBootSummary s)]
700 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
701 not (ms_mod_name s `elem` all_home_mods)]
702 ASSERT( null bad_boot_mods ) return ()
704 -- check that the module given in HowMuch actually exists, otherwise
705 -- topSortModuleGraph will bomb later.
706 let checkHowMuch (LoadUpTo m) = checkMod m
707 checkHowMuch (LoadDependenciesOf m) = checkMod m
711 | m `elem` all_home_mods = and_then
713 liftIO $ errorMsg dflags (text "no such module:" <+>
717 checkHowMuch how_much $ do
719 -- mg2_with_srcimps drops the hi-boot nodes, returning a
720 -- graph with cycles. Among other things, it is used for
721 -- backing out partially complete cycles following a failed
722 -- upsweep, and for removing from hpt all the modules
723 -- not in strict downwards closure, during calls to compile.
724 let mg2_with_srcimps :: [SCC ModSummary]
725 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
727 -- If we can determine that any of the {-# SOURCE #-} imports
728 -- are definitely unnecessary, then emit a warning.
729 warnUnnecessarySourceImports dflags mg2_with_srcimps
732 -- check the stability property for each module.
733 stable_mods@(stable_obj,stable_bco)
734 = checkStability hpt1 mg2_with_srcimps all_home_mods
736 -- prune bits of the HPT which are definitely redundant now,
738 pruned_hpt = pruneHomePackageTable hpt1
739 (flattenSCCs mg2_with_srcimps)
742 liftIO $ evaluate pruned_hpt
744 -- before we unload anything, make sure we don't leave an old
745 -- interactive context around pointing to dead bindings. Also,
746 -- write the pruned HPT to allow the old HPT to be GC'd.
747 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
748 hsc_HPT = pruned_hpt }
750 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
751 text "Stable BCO:" <+> ppr stable_bco)
753 -- Unload any modules which are going to be re-linked this time around.
754 let stable_linkables = [ linkable
755 | m <- stable_obj++stable_bco,
756 Just hmi <- [lookupUFM pruned_hpt m],
757 Just linkable <- [hm_linkable hmi] ]
758 liftIO $ unload hsc_env stable_linkables
760 -- We could at this point detect cycles which aren't broken by
761 -- a source-import, and complain immediately, but it seems better
762 -- to let upsweep_mods do this, so at least some useful work gets
763 -- done before the upsweep is abandoned.
764 --hPutStrLn stderr "after tsort:\n"
765 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
767 -- Now do the upsweep, calling compile for each module in
768 -- turn. Final result is version 3 of everything.
770 -- Topologically sort the module graph, this time including hi-boot
771 -- nodes, and possibly just including the portion of the graph
772 -- reachable from the module specified in the 2nd argument to load.
773 -- This graph should be cycle-free.
774 -- If we're restricting the upsweep to a portion of the graph, we
775 -- also want to retain everything that is still stable.
776 let full_mg :: [SCC ModSummary]
777 full_mg = topSortModuleGraph False mod_graph Nothing
779 maybe_top_mod = case how_much of
781 LoadDependenciesOf m -> Just m
784 partial_mg0 :: [SCC ModSummary]
785 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
787 -- LoadDependenciesOf m: we want the upsweep to stop just
788 -- short of the specified module (unless the specified module
791 | LoadDependenciesOf _mod <- how_much
792 = ASSERT( case last partial_mg0 of
793 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
794 List.init partial_mg0
800 | AcyclicSCC ms <- full_mg,
801 ms_mod_name ms `elem` stable_obj++stable_bco,
802 ms_mod_name ms `notElem` [ ms_mod_name ms' |
803 AcyclicSCC ms' <- partial_mg ] ]
805 mg = stable_mg ++ partial_mg
807 -- clean up between compilations
808 let cleanup = cleanTempFilesExcept dflags
809 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
811 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
813 (upsweep_ok, hsc_env1, modsUpswept)
815 (hsc_env { hsc_HPT = emptyHomePackageTable })
816 pruned_hpt stable_mods cleanup mg
818 -- Make modsDone be the summaries for each home module now
819 -- available; this should equal the domain of hpt3.
820 -- Get in in a roughly top .. bottom order (hence reverse).
822 let modsDone = reverse modsUpswept
824 -- Try and do linking in some form, depending on whether the
825 -- upsweep was completely or only partially successful.
827 if succeeded upsweep_ok
830 -- Easy; just relink it all.
831 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
833 -- Clean up after ourselves
834 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
836 -- Issue a warning for the confusing case where the user
837 -- said '-o foo' but we're not going to do any linking.
838 -- We attempt linking if either (a) one of the modules is
839 -- called Main, or (b) the user said -no-hs-main, indicating
840 -- that main() is going to come from somewhere else.
842 let ofile = outputFile dflags
843 let no_hs_main = dopt Opt_NoHsMain dflags
845 main_mod = mainModIs dflags
846 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
847 do_linking = a_root_is_Main || no_hs_main
849 when (ghcLink dflags == LinkBinary
850 && isJust ofile && not do_linking) $
851 liftIO $ debugTraceMsg dflags 1 $
852 text ("Warning: output was redirected with -o, " ++
853 "but no output will be generated\n" ++
854 "because there is no " ++
855 moduleNameString (moduleName main_mod) ++ " module.")
857 -- link everything together
858 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
860 loadFinish Succeeded linkresult hsc_env1
863 -- Tricky. We need to back out the effects of compiling any
864 -- half-done cycles, both so as to clean up the top level envs
865 -- and to avoid telling the interactive linker to link them.
866 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
869 = map ms_mod modsDone
870 let mods_to_zap_names
871 = findPartiallyCompletedCycles modsDone_names
874 = filter ((`notElem` mods_to_zap_names).ms_mod)
877 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
880 -- Clean up after ourselves
881 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
883 -- there should be no Nothings where linkables should be, now
884 ASSERT(all (isJust.hm_linkable)
885 (eltsUFM (hsc_HPT hsc_env))) do
887 -- Link everything together
888 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
890 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
891 loadFinish Failed linkresult hsc_env4
893 -- Finish up after a load.
895 -- If the link failed, unload everything and return.
896 loadFinish :: GhcMonad m =>
897 SuccessFlag -> SuccessFlag -> HscEnv
899 loadFinish _all_ok Failed hsc_env
900 = do liftIO $ unload hsc_env []
901 modifySession $ \_ -> discardProg hsc_env
904 -- Empty the interactive context and set the module context to the topmost
905 -- newly loaded module, or the Prelude if none were loaded.
906 loadFinish all_ok Succeeded hsc_env
907 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
911 -- Forget the current program, but retain the persistent info in HscEnv
912 discardProg :: HscEnv -> HscEnv
914 = hsc_env { hsc_mod_graph = emptyMG,
915 hsc_IC = emptyInteractiveContext,
916 hsc_HPT = emptyHomePackageTable }
918 -- used to fish out the preprocess output files for the purposes of
919 -- cleaning up. The preprocessed file *might* be the same as the
920 -- source file, but that doesn't do any harm.
921 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
922 ppFilesFromSummaries summaries = map ms_hspp_file summaries
924 -- -----------------------------------------------------------------------------
926 class ParsedMod m where
927 modSummary :: m -> ModSummary
928 parsedSource :: m -> ParsedSource
930 class ParsedMod m => TypecheckedMod m where
931 renamedSource :: m -> Maybe RenamedSource
932 typecheckedSource :: m -> TypecheckedSource
933 moduleInfo :: m -> ModuleInfo
934 tm_internals :: m -> (TcGblEnv, ModDetails)
935 -- ToDo: improvements that could be made here:
936 -- if the module succeeded renaming but not typechecking,
937 -- we can still get back the GlobalRdrEnv and exports, so
938 -- perhaps the ModuleInfo should be split up into separate
941 class TypecheckedMod m => DesugaredMod m where
942 coreModule :: m -> ModGuts
944 -- | The result of successful parsing.
946 ParsedModule { pm_mod_summary :: ModSummary
947 , pm_parsed_source :: ParsedSource }
949 instance ParsedMod ParsedModule where
950 modSummary m = pm_mod_summary m
951 parsedSource m = pm_parsed_source m
953 -- | The result of successful typechecking. It also contains the parser
955 data TypecheckedModule =
956 TypecheckedModule { tm_parsed_module :: ParsedModule
957 , tm_renamed_source :: Maybe RenamedSource
958 , tm_typechecked_source :: TypecheckedSource
959 , tm_checked_module_info :: ModuleInfo
960 , tm_internals_ :: (TcGblEnv, ModDetails)
963 instance ParsedMod TypecheckedModule where
964 modSummary m = modSummary (tm_parsed_module m)
965 parsedSource m = parsedSource (tm_parsed_module m)
967 instance TypecheckedMod TypecheckedModule where
968 renamedSource m = tm_renamed_source m
969 typecheckedSource m = tm_typechecked_source m
970 moduleInfo m = tm_checked_module_info m
971 tm_internals m = tm_internals_ m
973 -- | The result of successful desugaring (i.e., translation to core). Also
974 -- contains all the information of a typechecked module.
975 data DesugaredModule =
976 DesugaredModule { dm_typechecked_module :: TypecheckedModule
977 , dm_core_module :: ModGuts
980 instance ParsedMod DesugaredModule where
981 modSummary m = modSummary (dm_typechecked_module m)
982 parsedSource m = parsedSource (dm_typechecked_module m)
984 instance TypecheckedMod DesugaredModule where
985 renamedSource m = renamedSource (dm_typechecked_module m)
986 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
987 moduleInfo m = moduleInfo (dm_typechecked_module m)
988 tm_internals m = tm_internals_ (dm_typechecked_module m)
990 instance DesugaredMod DesugaredModule where
991 coreModule m = dm_core_module m
993 type ParsedSource = Located (HsModule RdrName)
994 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
995 Maybe (HsDoc Name), HaddockModInfo Name)
996 type TypecheckedSource = LHsBinds Id
999 -- - things that aren't in the output of the typechecker right now:
1000 -- - the export list
1002 -- - type signatures
1003 -- - type/data/newtype declarations
1004 -- - class declarations
1006 -- - extra things in the typechecker's output:
1007 -- - default methods are turned into top-level decls.
1008 -- - dictionary bindings
1010 -- | Return the 'ModSummary' of a module with the given name.
1012 -- The module must be part of the module graph (see 'hsc_mod_graph' and
1013 -- 'ModuleGraph'). If this is not the case, this function will throw a
1016 -- This function ignores boot modules and requires that there is only one
1017 -- non-boot module with the given name.
1018 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1019 getModSummary mod = do
1020 mg <- liftM hsc_mod_graph getSession
1021 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
1022 [] -> throw $ mkApiErr (text "Module not part of module graph")
1024 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
1026 -- | Parse a module.
1028 -- Throws a 'SourceError' on parse error.
1029 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
1031 hsc_env0 <- getSession
1032 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1033 rdr_module <- parseFile hsc_env ms
1034 return (ParsedModule ms rdr_module)
1036 -- | Typecheck and rename a parsed module.
1038 -- Throws a 'SourceError' if either fails.
1039 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1040 typecheckModule pmod = do
1041 let ms = modSummary pmod
1042 hsc_env0 <- getSession
1043 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1044 (tc_gbl_env, rn_info)
1045 <- typecheckRenameModule hsc_env ms (parsedSource pmod)
1046 details <- liftIO $ makeSimpleDetails hsc_env tc_gbl_env
1049 tm_internals_ = (tc_gbl_env, details),
1050 tm_parsed_module = pmod,
1051 tm_renamed_source = rn_info,
1052 tm_typechecked_source = tcg_binds tc_gbl_env,
1053 tm_checked_module_info =
1055 minf_type_env = md_types details,
1056 minf_exports = availsToNameSet $ md_exports details,
1057 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1058 minf_instances = md_insts details
1060 ,minf_modBreaks = emptyModBreaks
1064 -- | Desugar a typechecked module.
1065 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1066 desugarModule tcm = do
1067 let ms = modSummary tcm
1068 hsc_env0 <- getSession
1069 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1070 let (tcg, _) = tm_internals tcm
1071 guts <- deSugarModule hsc_env ms tcg
1074 dm_typechecked_module = tcm,
1075 dm_core_module = guts
1078 -- | Load a module. Input doesn't need to be desugared.
1080 -- XXX: Describe usage.
1081 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1083 let ms = modSummary tcm
1084 let mod = ms_mod_name ms
1085 hsc_env0 <- getSession
1086 let hsc_env = hsc_env0 { hsc_dflags = ms_hspp_opts ms }
1087 let (tcg, details) = tm_internals tcm
1088 (iface,_) <- liftIO $ makeSimpleIface hsc_env Nothing tcg details
1089 let mod_info = HomeModInfo {
1091 hm_details = details,
1092 hm_linkable = Nothing }
1093 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
1094 modifySession $ \_ -> hsc_env0{ hsc_HPT = hpt_new }
1097 -- | This is the way to get access to the Core bindings corresponding
1098 -- to a module. 'compileToCore' parses, typechecks, and
1099 -- desugars the module, then returns the resulting Core module (consisting of
1100 -- the module name, type declarations, and function declarations) if
1102 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1103 compileToCoreModule = compileCore False
1105 -- | Like compileToCoreModule, but invokes the simplifier, so
1106 -- as to return simplified and tidied Core.
1107 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1108 compileToCoreSimplified = compileCore True
1110 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1111 -- bindings, but for most purposes, you probably want to call
1112 -- compileToCoreModule.
1113 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1114 compileToCore fn = do
1115 mod <- compileToCoreModule session fn
1116 return $ cm_binds mod
1118 -- | Takes a CoreModule and compiles the bindings therein
1119 -- to object code. The first argument is a bool flag indicating
1120 -- whether to run the simplifier.
1121 -- The resulting .o, .hi, and executable files, if any, are stored in the
1122 -- current directory, and named according to the module name.
1123 -- Returns True iff compilation succeeded.
1124 -- This has only so far been tested with a single self-contained module.
1125 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1126 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1127 hscEnv <- getSession
1128 dflags <- getSessionDynFlags
1129 currentTime <- liftIO $ getClockTime
1130 cwd <- liftIO $ getCurrentDirectory
1131 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1132 ((moduleNameSlashes . moduleName) mName)
1134 let modSummary = ModSummary { ms_mod = mName,
1135 ms_hsc_src = ExtCoreFile,
1136 ms_location = modLocation,
1137 -- By setting the object file timestamp to Nothing,
1138 -- we always force recompilation, which is what we
1139 -- want. (Thus it doesn't matter what the timestamp
1140 -- for the (nonexistent) source file is.)
1141 ms_hs_date = currentTime,
1142 ms_obj_date = Nothing,
1143 -- Only handling the single-module case for now, so no imports.
1148 ms_hspp_opts = dflags,
1149 ms_hspp_buf = Nothing
1152 ioMsgMaybe $ flip evalComp (CompState{ compHscEnv=hscEnv,
1153 compModSummary=modSummary,
1154 compOldIface=Nothing}) $
1155 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1156 | otherwise = return mod_guts
1157 in maybe_simplify (mkModGuts cm)
1163 -- Makes a "vanilla" ModGuts.
1164 mkModGuts :: CoreModule -> ModGuts
1165 mkModGuts coreModule = ModGuts {
1166 mg_module = cm_module coreModule,
1169 mg_deps = noDependencies,
1170 mg_dir_imps = emptyModuleEnv,
1171 mg_used_names = emptyNameSet,
1172 mg_rdr_env = emptyGlobalRdrEnv,
1173 mg_fix_env = emptyFixityEnv,
1174 mg_types = emptyTypeEnv,
1178 mg_binds = cm_binds coreModule,
1179 mg_foreign = NoStubs,
1180 mg_warns = NoWarnings,
1182 mg_hpc_info = emptyHpcInfo False,
1183 mg_modBreaks = emptyModBreaks,
1184 mg_vect_info = noVectInfo,
1185 mg_inst_env = emptyInstEnv,
1186 mg_fam_inst_env = emptyFamInstEnv
1189 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1190 compileCore simplify fn = do
1191 -- First, set the target to the desired filename
1192 target <- guessTarget fn Nothing
1195 -- Then find dependencies
1196 modGraph <- depanal [] True
1197 case find ((== fn) . msHsFilePath) modGraph of
1198 Just modSummary -> do
1199 -- Now we have the module name;
1200 -- parse, typecheck and desugar the module
1201 mod_guts <- coreModule `fmap`
1202 (desugarModule =<< typecheckModule =<< parseModule modSummary)
1203 liftM gutsToCoreModule $
1206 -- If simplify is true: simplify (hscSimplify), then tidy
1208 hsc_env <- getSession
1209 simpl_guts <- ioMsg $ evalComp (hscSimplify mod_guts)
1211 compHscEnv = hsc_env,
1212 compModSummary = modSummary,
1213 compOldIface = Nothing})
1214 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1215 return $ Left tidy_guts
1217 return $ Right mod_guts
1219 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1220 module dependency graph"
1221 where -- two versions, based on whether we simplify (thus run tidyProgram,
1222 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1223 -- we just have a ModGuts.
1224 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1225 gutsToCoreModule (Left (cg, md)) = CoreModule {
1226 cm_module = cg_module cg, cm_types = md_types md,
1227 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1229 gutsToCoreModule (Right mg) = CoreModule {
1230 cm_module = mg_module mg, cm_types = mg_types mg,
1231 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1234 -- ---------------------------------------------------------------------------
1237 unload :: HscEnv -> [Linkable] -> IO ()
1238 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1239 = case ghcLink (hsc_dflags hsc_env) of
1241 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1243 LinkInMemory -> panic "unload: no interpreter"
1244 -- urgh. avoid warnings:
1245 hsc_env stable_linkables
1249 -- -----------------------------------------------------------------------------
1253 Stability tells us which modules definitely do not need to be recompiled.
1254 There are two main reasons for having stability:
1256 - avoid doing a complete upsweep of the module graph in GHCi when
1257 modules near the bottom of the tree have not changed.
1259 - to tell GHCi when it can load object code: we can only load object code
1260 for a module when we also load object code fo all of the imports of the
1261 module. So we need to know that we will definitely not be recompiling
1262 any of these modules, and we can use the object code.
1264 The stability check is as follows. Both stableObject and
1265 stableBCO are used during the upsweep phase later.
1268 stable m = stableObject m || stableBCO m
1271 all stableObject (imports m)
1272 && old linkable does not exist, or is == on-disk .o
1273 && date(on-disk .o) > date(.hs)
1276 all stable (imports m)
1277 && date(BCO) > date(.hs)
1280 These properties embody the following ideas:
1282 - if a module is stable, then:
1284 - if it has been compiled in a previous pass (present in HPT)
1285 then it does not need to be compiled or re-linked.
1287 - if it has not been compiled in a previous pass,
1288 then we only need to read its .hi file from disk and
1289 link it to produce a 'ModDetails'.
1291 - if a modules is not stable, we will definitely be at least
1292 re-linking, and possibly re-compiling it during the 'upsweep'.
1293 All non-stable modules can (and should) therefore be unlinked
1294 before the 'upsweep'.
1296 - Note that objects are only considered stable if they only depend
1297 on other objects. We can't link object code against byte code.
1301 :: HomePackageTable -- HPT from last compilation
1302 -> [SCC ModSummary] -- current module graph (cyclic)
1303 -> [ModuleName] -- all home modules
1304 -> ([ModuleName], -- stableObject
1305 [ModuleName]) -- stableBCO
1307 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1309 checkSCC (stable_obj, stable_bco) scc0
1310 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1311 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1312 | otherwise = (stable_obj, stable_bco)
1314 scc = flattenSCC scc0
1315 scc_mods = map ms_mod_name scc
1316 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1318 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1319 -- all imports outside the current SCC, but in the home pkg
1321 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1322 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1326 && all object_ok scc
1329 and (zipWith (||) stable_obj_imps stable_bco_imps)
1333 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1337 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1338 Just hmi | Just l <- hm_linkable hmi
1339 -> isObjectLinkable l && t == linkableTime l
1341 -- why '>=' rather than '>' above? If the filesystem stores
1342 -- times to the nearset second, we may occasionally find that
1343 -- the object & source have the same modification time,
1344 -- especially if the source was automatically generated
1345 -- and compiled. Using >= is slightly unsafe, but it matches
1346 -- make's behaviour.
1349 = case lookupUFM hpt (ms_mod_name ms) of
1350 Just hmi | Just l <- hm_linkable hmi ->
1351 not (isObjectLinkable l) &&
1352 linkableTime l >= ms_hs_date ms
1355 ms_allimps :: ModSummary -> [ModuleName]
1356 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1358 -- -----------------------------------------------------------------------------
1360 -- | Prune the HomePackageTable
1362 -- Before doing an upsweep, we can throw away:
1364 -- - For non-stable modules:
1365 -- - all ModDetails, all linked code
1366 -- - all unlinked code that is out of date with respect to
1369 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1370 -- space at the end of the upsweep, because the topmost ModDetails of the
1371 -- old HPT holds on to the entire type environment from the previous
1374 pruneHomePackageTable
1377 -> ([ModuleName],[ModuleName])
1380 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1383 | is_stable modl = hmi'
1384 | otherwise = hmi'{ hm_details = emptyModDetails }
1386 modl = moduleName (mi_module (hm_iface hmi))
1387 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1388 = hmi{ hm_linkable = Nothing }
1391 where ms = expectJust "prune" (lookupUFM ms_map modl)
1393 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1395 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1397 -- -----------------------------------------------------------------------------
1399 -- Return (names of) all those in modsDone who are part of a cycle
1400 -- as defined by theGraph.
1401 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1402 findPartiallyCompletedCycles modsDone theGraph
1406 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1407 chew ((CyclicSCC vs):rest)
1408 = let names_in_this_cycle = nub (map ms_mod vs)
1410 = nub ([done | done <- modsDone,
1411 done `elem` names_in_this_cycle])
1412 chewed_rest = chew rest
1414 if notNull mods_in_this_cycle
1415 && length mods_in_this_cycle < length names_in_this_cycle
1416 then mods_in_this_cycle ++ chewed_rest
1419 -- -----------------------------------------------------------------------------
1423 -- This is where we compile each module in the module graph, in a pass
1424 -- from the bottom to the top of the graph.
1426 -- There better had not be any cyclic groups here -- we check for them.
1430 WarnErrLogger -- ^ Called to print warnings and errors.
1431 -> HscEnv -- ^ Includes initially-empty HPT
1432 -> HomePackageTable -- ^ HPT from last time round (pruned)
1433 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1434 -> IO () -- ^ How to clean up unwanted tmp files
1435 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1437 HscEnv, -- With an updated HPT
1438 [ModSummary]) -- Mods which succeeded
1440 upsweep logger hsc_env old_hpt stable_mods cleanup sccs = do
1441 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1442 return (res, hsc_env, reverse done)
1445 upsweep' hsc_env _old_hpt done
1447 = return (Succeeded, hsc_env, done)
1449 upsweep' hsc_env _old_hpt done
1450 (CyclicSCC ms:_) _ _
1451 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1452 return (Failed, hsc_env, done)
1454 upsweep' hsc_env old_hpt done
1455 (AcyclicSCC mod:mods) mod_index nmods
1456 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1457 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1458 -- (moduleEnvElts (hsc_HPT hsc_env)))
1461 <- handleSourceError
1462 (\err -> do logger (Just err); return Nothing) $ do
1463 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1465 logger Nothing -- log warnings
1466 return (Just mod_info)
1468 liftIO cleanup -- Remove unwanted tmp files between compilations
1471 Nothing -> return (Failed, hsc_env, done)
1473 let this_mod = ms_mod_name mod
1475 -- Add new info to hsc_env
1476 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1477 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1479 -- Space-saving: delete the old HPT entry
1480 -- for mod BUT if mod is a hs-boot
1481 -- node, don't delete it. For the
1482 -- interface, the HPT entry is probaby for the
1483 -- main Haskell source file. Deleting it
1484 -- would force the real module to be recompiled
1486 old_hpt1 | isBootSummary mod = old_hpt
1487 | otherwise = delFromUFM old_hpt this_mod
1491 -- fixup our HomePackageTable after we've finished compiling
1492 -- a mutually-recursive loop. See reTypecheckLoop, below.
1493 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1495 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1497 -- | Compile a single module. Always produce a Linkable for it if
1498 -- successful. If no compilation happened, return the old Linkable.
1499 upsweep_mod :: GhcMonad m =>
1502 -> ([ModuleName],[ModuleName])
1504 -> Int -- index of module
1505 -> Int -- total number of modules
1508 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1510 this_mod_name = ms_mod_name summary
1511 this_mod = ms_mod summary
1512 mb_obj_date = ms_obj_date summary
1513 obj_fn = ml_obj_file (ms_location summary)
1514 hs_date = ms_hs_date summary
1516 is_stable_obj = this_mod_name `elem` stable_obj
1517 is_stable_bco = this_mod_name `elem` stable_bco
1519 old_hmi = lookupUFM old_hpt this_mod_name
1521 -- We're using the dflags for this module now, obtained by
1522 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1523 dflags = ms_hspp_opts summary
1524 prevailing_target = hscTarget (hsc_dflags hsc_env)
1525 local_target = hscTarget dflags
1527 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1528 -- we don't do anything dodgy: these should only work to change
1529 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1530 -- end up trying to link object code to byte code.
1531 target = if prevailing_target /= local_target
1532 && (not (isObjectTarget prevailing_target)
1533 || not (isObjectTarget local_target))
1534 then prevailing_target
1537 -- store the corrected hscTarget into the summary
1538 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1540 -- The old interface is ok if
1541 -- a) we're compiling a source file, and the old HPT
1542 -- entry is for a source file
1543 -- b) we're compiling a hs-boot file
1544 -- Case (b) allows an hs-boot file to get the interface of its
1545 -- real source file on the second iteration of the compilation
1546 -- manager, but that does no harm. Otherwise the hs-boot file
1547 -- will always be recompiled
1552 Just hm_info | isBootSummary summary -> Just iface
1553 | not (mi_boot iface) -> Just iface
1554 | otherwise -> Nothing
1556 iface = hm_iface hm_info
1558 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1559 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1561 compile_it_discard_iface :: GhcMonad m =>
1562 Maybe Linkable -> m HomeModInfo
1563 compile_it_discard_iface
1564 = compile hsc_env summary' mod_index nmods Nothing
1570 -- Regardless of whether we're generating object code or
1571 -- byte code, we can always use an existing object file
1572 -- if it is *stable* (see checkStability).
1573 | is_stable_obj, isJust old_hmi ->
1574 let Just hmi = old_hmi in
1576 -- object is stable, and we have an entry in the
1577 -- old HPT: nothing to do
1579 | is_stable_obj, isNothing old_hmi -> do
1580 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1581 (expectJust "upsweep1" mb_obj_date)
1582 compile_it (Just linkable)
1583 -- object is stable, but we need to load the interface
1584 -- off disk to make a HMI.
1588 ASSERT(isJust old_hmi) -- must be in the old_hpt
1589 let Just hmi = old_hmi in
1591 -- BCO is stable: nothing to do
1593 | Just hmi <- old_hmi,
1594 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1595 linkableTime l >= ms_hs_date summary ->
1597 -- we have an old BCO that is up to date with respect
1598 -- to the source: do a recompilation check as normal.
1602 -- no existing code at all: we must recompile.
1604 -- When generating object code, if there's an up-to-date
1605 -- object file on the disk, then we can use it.
1606 -- However, if the object file is new (compared to any
1607 -- linkable we had from a previous compilation), then we
1608 -- must discard any in-memory interface, because this
1609 -- means the user has compiled the source file
1610 -- separately and generated a new interface, that we must
1611 -- read from the disk.
1613 obj | isObjectTarget obj,
1614 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1617 | Just l <- hm_linkable hmi,
1618 isObjectLinkable l && linkableTime l == obj_date
1619 -> compile_it (Just l)
1621 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1622 compile_it_discard_iface (Just linkable)
1629 -- Filter modules in the HPT
1630 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1631 retainInTopLevelEnvs keep_these hpt
1632 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1634 , let mb_mod_info = lookupUFM hpt mod
1635 , isJust mb_mod_info ]
1637 -- ---------------------------------------------------------------------------
1638 -- Typecheck module loops
1641 See bug #930. This code fixes a long-standing bug in --make. The
1642 problem is that when compiling the modules *inside* a loop, a data
1643 type that is only defined at the top of the loop looks opaque; but
1644 after the loop is done, the structure of the data type becomes
1647 The difficulty is then that two different bits of code have
1648 different notions of what the data type looks like.
1650 The idea is that after we compile a module which also has an .hs-boot
1651 file, we re-generate the ModDetails for each of the modules that
1652 depends on the .hs-boot file, so that everyone points to the proper
1653 TyCons, Ids etc. defined by the real module, not the boot module.
1654 Fortunately re-generating a ModDetails from a ModIface is easy: the
1655 function TcIface.typecheckIface does exactly that.
1657 Picking the modules to re-typecheck is slightly tricky. Starting from
1658 the module graph consisting of the modules that have already been
1659 compiled, we reverse the edges (so they point from the imported module
1660 to the importing module), and depth-first-search from the .hs-boot
1661 node. This gives us all the modules that depend transitively on the
1662 .hs-boot module, and those are exactly the modules that we need to
1665 Following this fix, GHC can compile itself with --make -O2.
1668 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1669 reTypecheckLoop hsc_env ms graph
1670 | not (isBootSummary ms) &&
1671 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1673 let mss = reachableBackwards (ms_mod_name ms) graph
1674 non_boot = filter (not.isBootSummary) mss
1675 debugTraceMsg (hsc_dflags hsc_env) 2 $
1676 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1677 typecheckLoop hsc_env (map ms_mod_name non_boot)
1681 this_mod = ms_mod ms
1683 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1684 typecheckLoop hsc_env mods = do
1686 fixIO $ \new_hpt -> do
1687 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1688 mds <- initIfaceCheck new_hsc_env $
1689 mapM (typecheckIface . hm_iface) hmis
1690 let new_hpt = addListToUFM old_hpt
1691 (zip mods [ hmi{ hm_details = details }
1692 | (hmi,details) <- zip hmis mds ])
1694 return hsc_env{ hsc_HPT = new_hpt }
1696 old_hpt = hsc_HPT hsc_env
1697 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1699 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1700 reachableBackwards mod summaries
1701 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1702 where -- the rest just sets up the graph:
1703 (graph, lookup_node) = moduleGraphNodes False summaries
1704 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1706 -- ---------------------------------------------------------------------------
1707 -- Topological sort of the module graph
1709 type SummaryNode = (ModSummary, Int, [Int])
1713 -- ^ Drop hi-boot nodes? (see below)
1717 -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1718 -- The resulting list of strongly-connected-components is in topologically
1719 -- sorted order, starting with the module(s) at the bottom of the
1720 -- dependency graph (ie compile them first) and ending with the ones at
1723 -- Drop hi-boot nodes (first boolean arg)?
1725 -- - @False@: treat the hi-boot summaries as nodes of the graph,
1726 -- so the graph must be acyclic
1728 -- - @True@: eliminate the hi-boot nodes, and instead pretend
1729 -- the a source-import of Foo is an import of Foo
1730 -- The resulting graph has no hi-boot nodes, but can be cyclic
1732 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1733 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1735 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1737 initial_graph = case mb_root_mod of
1740 -- restrict the graph to just those modules reachable from
1741 -- the specified module. We do this by building a graph with
1742 -- the full set of nodes, and determining the reachable set from
1743 -- the specified node.
1744 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1745 | otherwise = ghcError (ProgramError "module does not exist")
1746 in graphFromEdgedVertices (seq root (reachableG graph root))
1748 summaryNodeKey :: SummaryNode -> Int
1749 summaryNodeKey (_, k, _) = k
1751 summaryNodeSummary :: SummaryNode -> ModSummary
1752 summaryNodeSummary (s, _, _) = s
1754 moduleGraphNodes :: Bool -> [ModSummary]
1755 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1756 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1758 numbered_summaries = zip summaries [1..]
1760 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1761 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1763 lookup_key :: HscSource -> ModuleName -> Maybe Int
1764 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1766 node_map :: NodeMap SummaryNode
1767 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1768 | node@(s, _, _) <- nodes ]
1770 -- We use integers as the keys for the SCC algorithm
1771 nodes :: [SummaryNode]
1772 nodes = [ (s, key, out_keys)
1773 | (s, key) <- numbered_summaries
1774 -- Drop the hi-boot ones if told to do so
1775 , not (isBootSummary s && drop_hs_boot_nodes)
1776 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1777 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1778 (-- see [boot-edges] below
1779 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1781 else case lookup_key HsBootFile (ms_mod_name s) of
1785 -- [boot-edges] if this is a .hs and there is an equivalent
1786 -- .hs-boot, add a link from the former to the latter. This
1787 -- has the effect of detecting bogus cases where the .hs-boot
1788 -- depends on the .hs, by introducing a cycle. Additionally,
1789 -- it ensures that we will always process the .hs-boot before
1790 -- the .hs, and so the HomePackageTable will always have the
1791 -- most up to date information.
1793 -- Drop hs-boot nodes by using HsSrcFile as the key
1794 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1795 | otherwise = HsBootFile
1797 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1798 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1799 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1800 -- the IsBootInterface parameter True; else False
1803 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1804 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1806 msKey :: ModSummary -> NodeKey
1807 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1809 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1810 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1812 nodeMapElts :: NodeMap a -> [a]
1813 nodeMapElts = eltsFM
1815 -- | If there are {-# SOURCE #-} imports between strongly connected
1816 -- components in the topological sort, then those imports can
1817 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1818 -- were necessary, then the edge would be part of a cycle.
1819 warnUnnecessarySourceImports :: GhcMonad m => DynFlags -> [SCC ModSummary] -> m ()
1820 warnUnnecessarySourceImports dflags sccs =
1821 liftIO $ printBagOfWarnings dflags (listToBag (concatMap (check.flattenSCC) sccs))
1823 let mods_in_this_cycle = map ms_mod_name ms in
1824 [ warn i | m <- ms, i <- ms_srcimps m,
1825 unLoc i `notElem` mods_in_this_cycle ]
1827 warn :: Located ModuleName -> WarnMsg
1830 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1831 <+> quotes (ppr mod))
1833 -----------------------------------------------------------------------------
1834 -- Downsweep (dependency analysis)
1836 -- Chase downwards from the specified root set, returning summaries
1837 -- for all home modules encountered. Only follow source-import
1840 -- We pass in the previous collection of summaries, which is used as a
1841 -- cache to avoid recalculating a module summary if the source is
1844 -- The returned list of [ModSummary] nodes has one node for each home-package
1845 -- module, plus one for any hs-boot files. The imports of these nodes
1846 -- are all there, including the imports of non-home-package modules.
1848 downsweep :: GhcMonad m =>
1850 -> [ModSummary] -- Old summaries
1851 -> [ModuleName] -- Ignore dependencies on these; treat
1852 -- them as if they were package modules
1853 -> Bool -- True <=> allow multiple targets to have
1854 -- the same module name; this is
1855 -- very useful for ghc -M
1857 -- The elts of [ModSummary] all have distinct
1858 -- (Modules, IsBoot) identifiers, unless the Bool is true
1859 -- in which case there can be repeats
1860 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1861 = do -- catch error messages and return them
1862 --handleErrMsg -- should be covered by GhcMonad now
1863 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1864 rootSummaries <- mapM getRootSummary roots
1865 let root_map = mkRootMap rootSummaries
1866 checkDuplicates root_map
1867 summs <- loop (concatMap msDeps rootSummaries) root_map
1870 roots = hsc_targets hsc_env
1872 old_summary_map :: NodeMap ModSummary
1873 old_summary_map = mkNodeMap old_summaries
1875 getRootSummary :: GhcMonad m => Target -> m ModSummary
1876 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1877 = do exists <- liftIO $ doesFileExist file
1879 then summariseFile hsc_env old_summaries file mb_phase
1880 obj_allowed maybe_buf
1881 else throwOneError $ mkPlainErrMsg noSrcSpan $
1882 text "can't find file:" <+> text file
1883 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1884 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1885 (L rootLoc modl) obj_allowed
1887 case maybe_summary of
1888 Nothing -> packageModErr modl
1891 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1893 -- In a root module, the filename is allowed to diverge from the module
1894 -- name, so we have to check that there aren't multiple root files
1895 -- defining the same module (otherwise the duplicates will be silently
1896 -- ignored, leading to confusing behaviour).
1897 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1898 checkDuplicates root_map
1899 | allow_dup_roots = return ()
1900 | null dup_roots = return ()
1901 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1903 dup_roots :: [[ModSummary]] -- Each at least of length 2
1904 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1906 loop :: GhcMonad m =>
1907 [(Located ModuleName,IsBootInterface)]
1908 -- Work list: process these modules
1909 -> NodeMap [ModSummary]
1910 -- Visited set; the range is a list because
1911 -- the roots can have the same module names
1912 -- if allow_dup_roots is True
1914 -- The result includes the worklist, except
1915 -- for those mentioned in the visited set
1916 loop [] done = return (concat (nodeMapElts done))
1917 loop ((wanted_mod, is_boot) : ss) done
1918 | Just summs <- lookupFM done key
1919 = if isSingleton summs then
1922 do { liftIO $ multiRootsErr summs; return [] }
1924 = do mb_s <- summariseModule hsc_env old_summary_map
1925 is_boot wanted_mod True
1928 Nothing -> loop ss done
1929 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
1931 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1933 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1934 mkRootMap summaries = addListToFM_C (++) emptyFM
1935 [ (msKey s, [s]) | s <- summaries ]
1937 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1938 -- (msDeps s) returns the dependencies of the ModSummary s.
1939 -- A wrinkle is that for a {-# SOURCE #-} import we return
1940 -- *both* the hs-boot file
1941 -- *and* the source file
1942 -- as "dependencies". That ensures that the list of all relevant
1943 -- modules always contains B.hs if it contains B.hs-boot.
1944 -- Remember, this pass isn't doing the topological sort. It's
1945 -- just gathering the list of all relevant ModSummaries
1947 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1948 ++ [ (m,False) | m <- ms_imps s ]
1950 -----------------------------------------------------------------------------
1951 -- Summarising modules
1953 -- We have two types of summarisation:
1955 -- * Summarise a file. This is used for the root module(s) passed to
1956 -- cmLoadModules. The file is read, and used to determine the root
1957 -- module name. The module name may differ from the filename.
1959 -- * Summarise a module. We are given a module name, and must provide
1960 -- a summary. The finder is used to locate the file in which the module
1966 -> [ModSummary] -- old summaries
1967 -> FilePath -- source file name
1968 -> Maybe Phase -- start phase
1969 -> Bool -- object code allowed?
1970 -> Maybe (StringBuffer,ClockTime)
1973 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1974 -- we can use a cached summary if one is available and the
1975 -- source file hasn't changed, But we have to look up the summary
1976 -- by source file, rather than module name as we do in summarise.
1977 | Just old_summary <- findSummaryBySourceFile old_summaries file
1979 let location = ms_location old_summary
1981 -- return the cached summary if the source didn't change
1982 src_timestamp <- case maybe_buf of
1983 Just (_,t) -> return t
1984 Nothing -> liftIO $ getModificationTime file
1985 -- The file exists; we checked in getRootSummary above.
1986 -- If it gets removed subsequently, then this
1987 -- getModificationTime may fail, but that's the right
1990 if ms_hs_date old_summary == src_timestamp
1991 then do -- update the object-file timestamp
1993 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1994 || obj_allowed -- bug #1205
1995 then liftIO $ getObjTimestamp location False
1997 return old_summary{ ms_obj_date = obj_timestamp }
2005 let dflags = hsc_dflags hsc_env
2007 (dflags', hspp_fn, buf)
2008 <- preprocessFile hsc_env file mb_phase maybe_buf
2010 (srcimps,the_imps, L _ mod_name) <- liftIO $ getImports dflags' buf hspp_fn file
2012 -- Make a ModLocation for this file
2013 location <- liftIO $ mkHomeModLocation dflags mod_name file
2015 -- Tell the Finder cache where it is, so that subsequent calls
2016 -- to findModule will find it, even if it's not on any search path
2017 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2019 src_timestamp <- case maybe_buf of
2020 Just (_,t) -> return t
2021 Nothing -> liftIO $ getModificationTime file
2022 -- getMofificationTime may fail
2024 -- when the user asks to load a source file by name, we only
2025 -- use an object file if -fobject-code is on. See #1205.
2027 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2028 || obj_allowed -- bug #1205
2029 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2032 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2033 ms_location = location,
2034 ms_hspp_file = hspp_fn,
2035 ms_hspp_opts = dflags',
2036 ms_hspp_buf = Just buf,
2037 ms_srcimps = srcimps, ms_imps = the_imps,
2038 ms_hs_date = src_timestamp,
2039 ms_obj_date = obj_timestamp })
2041 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2042 findSummaryBySourceFile summaries file
2043 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2044 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2048 -- Summarise a module, and pick up source and timestamp.
2052 -> NodeMap ModSummary -- Map of old summaries
2053 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2054 -> Located ModuleName -- Imported module to be summarised
2055 -> Bool -- object code allowed?
2056 -> Maybe (StringBuffer, ClockTime)
2057 -> [ModuleName] -- Modules to exclude
2058 -> m (Maybe ModSummary) -- Its new summary
2060 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2061 obj_allowed maybe_buf excl_mods
2062 | wanted_mod `elem` excl_mods
2065 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2066 = do -- Find its new timestamp; all the
2067 -- ModSummaries in the old map have valid ml_hs_files
2068 let location = ms_location old_summary
2069 src_fn = expectJust "summariseModule" (ml_hs_file location)
2071 -- check the modification time on the source file, and
2072 -- return the cached summary if it hasn't changed. If the
2073 -- file has disappeared, we need to call the Finder again.
2075 Just (_,t) -> check_timestamp old_summary location src_fn t
2077 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2079 Right t -> check_timestamp old_summary location src_fn t
2080 Left e | isDoesNotExistError e -> find_it
2081 | otherwise -> liftIO $ ioError e
2083 | otherwise = find_it
2085 dflags = hsc_dflags hsc_env
2087 hsc_src = if is_boot then HsBootFile else HsSrcFile
2089 check_timestamp old_summary location src_fn src_timestamp
2090 | ms_hs_date old_summary == src_timestamp = do
2091 -- update the object-file timestamp
2092 obj_timestamp <- liftIO $
2093 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2094 || obj_allowed -- bug #1205
2095 then getObjTimestamp location is_boot
2097 return (Just old_summary{ ms_obj_date = obj_timestamp })
2099 -- source changed: re-summarise.
2100 new_summary location (ms_mod old_summary) src_fn src_timestamp
2103 -- Don't use the Finder's cache this time. If the module was
2104 -- previously a package module, it may have now appeared on the
2105 -- search path, so we want to consider it to be a home module. If
2106 -- the module was previously a home module, it may have moved.
2107 liftIO $ uncacheModule hsc_env wanted_mod
2108 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2111 | isJust (ml_hs_file location) ->
2113 just_found location mod
2115 -- Drop external-pkg
2116 ASSERT(modulePackageId mod /= thisPackage dflags)
2119 err -> liftIO $ noModError dflags loc wanted_mod err
2122 just_found location mod = do
2123 -- Adjust location to point to the hs-boot source file,
2124 -- hi file, object file, when is_boot says so
2125 let location' | is_boot = addBootSuffixLocn location
2126 | otherwise = location
2127 src_fn = expectJust "summarise2" (ml_hs_file location')
2129 -- Check that it exists
2130 -- It might have been deleted since the Finder last found it
2131 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2133 Nothing -> noHsFileErr loc src_fn
2134 Just t -> new_summary location' mod src_fn t
2137 new_summary location mod src_fn src_timestamp
2139 -- Preprocess the source file and get its imports
2140 -- The dflags' contains the OPTIONS pragmas
2141 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2142 (srcimps, the_imps, L mod_loc mod_name) <- liftIO $ getImports dflags' buf hspp_fn src_fn
2144 when (mod_name /= wanted_mod) $
2145 throwOneError $ mkPlainErrMsg mod_loc $
2146 text "File name does not match module name:"
2147 $$ text "Saw:" <+> quotes (ppr mod_name)
2148 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2150 -- Find the object timestamp, and return the summary
2151 obj_timestamp <- liftIO $
2152 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2153 || obj_allowed -- bug #1205
2154 then getObjTimestamp location is_boot
2157 return (Just (ModSummary { ms_mod = mod,
2158 ms_hsc_src = hsc_src,
2159 ms_location = location,
2160 ms_hspp_file = hspp_fn,
2161 ms_hspp_opts = dflags',
2162 ms_hspp_buf = Just buf,
2163 ms_srcimps = srcimps,
2165 ms_hs_date = src_timestamp,
2166 ms_obj_date = obj_timestamp }))
2169 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2170 getObjTimestamp location is_boot
2171 = if is_boot then return Nothing
2172 else modificationTimeIfExists (ml_obj_file location)
2175 preprocessFile :: GhcMonad m =>
2178 -> Maybe Phase -- ^ Starting phase
2179 -> Maybe (StringBuffer,ClockTime)
2180 -> m (DynFlags, FilePath, StringBuffer)
2181 preprocessFile hsc_env src_fn mb_phase Nothing
2183 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2184 buf <- liftIO $ hGetStringBuffer hspp_fn
2185 return (dflags', hspp_fn, buf)
2187 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2189 let dflags = hsc_dflags hsc_env
2190 -- case we bypass the preprocessing stage?
2192 local_opts = getOptions dflags buf src_fn
2194 (dflags', leftovers, warns)
2195 <- parseDynamicNoPackageFlags dflags local_opts
2196 liftIO $ checkProcessArgsResult leftovers -- XXX: throws exceptions
2197 liftIO $ handleFlagWarnings dflags' warns -- XXX: throws exceptions
2201 | Just (Unlit _) <- mb_phase = True
2202 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2203 -- note: local_opts is only required if there's no Unlit phase
2204 | dopt Opt_Cpp dflags' = True
2205 | dopt Opt_Pp dflags' = True
2208 when needs_preprocessing $
2209 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2211 return (dflags', src_fn, buf)
2214 -----------------------------------------------------------------------------
2216 -----------------------------------------------------------------------------
2218 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2219 -- ToDo: we don't have a proper line number for this error
2220 noModError dflags loc wanted_mod err
2221 = throwOneError $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2223 noHsFileErr :: GhcMonad m => SrcSpan -> String -> m a
2224 noHsFileErr loc path
2225 = throwOneError $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2227 packageModErr :: GhcMonad m => ModuleName -> m a
2229 = throwOneError $ mkPlainErrMsg noSrcSpan $
2230 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2232 multiRootsErr :: [ModSummary] -> IO ()
2233 multiRootsErr [] = panic "multiRootsErr"
2234 multiRootsErr summs@(summ1:_)
2235 = throwOneError $ mkPlainErrMsg noSrcSpan $
2236 text "module" <+> quotes (ppr mod) <+>
2237 text "is defined in multiple files:" <+>
2238 sep (map text files)
2241 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2243 cyclicModuleErr :: [ModSummary] -> SDoc
2245 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2246 2 (vcat (map show_one ms))
2248 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2249 nest 2 $ ptext (sLit "imports:") <+>
2250 (pp_imps HsBootFile (ms_srcimps ms)
2251 $$ pp_imps HsSrcFile (ms_imps ms))]
2252 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2253 pp_imps src mods = fsep (map (show_mod src) mods)
2256 -- | Inform GHC that the working directory has changed. GHC will flush
2257 -- its cache of module locations, since it may no longer be valid.
2258 -- Note: if you change the working directory, you should also unload
2259 -- the current program (set targets to empty, followed by load).
2260 workingDirectoryChanged :: GhcMonad m => m ()
2261 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2263 -- -----------------------------------------------------------------------------
2264 -- inspecting the session
2266 -- | Get the module dependency graph.
2267 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2268 getModuleGraph = liftM hsc_mod_graph getSession
2270 -- | Return @True@ <==> module is loaded.
2271 isLoaded :: GhcMonad m => ModuleName -> m Bool
2272 isLoaded m = withSession $ \hsc_env ->
2273 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2275 -- | Return the bindings for the current interactive session.
2276 getBindings :: GhcMonad m => m [TyThing]
2277 getBindings = withSession $ \hsc_env ->
2278 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2279 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2281 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2282 filtered = foldr f (const []) tmp_ids emptyUniqSet
2284 | uniq `elementOfUniqSet` set = rest set
2285 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2286 where uniq = getUnique (nameOccName (idName id))
2290 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2291 getPrintUnqual = withSession $ \hsc_env ->
2292 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2294 -- | Container for information about a 'Module'.
2295 data ModuleInfo = ModuleInfo {
2296 minf_type_env :: TypeEnv,
2297 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2298 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2299 minf_instances :: [Instance]
2301 ,minf_modBreaks :: ModBreaks
2303 -- ToDo: this should really contain the ModIface too
2305 -- We don't want HomeModInfo here, because a ModuleInfo applies
2306 -- to package modules too.
2308 -- | Request information about a loaded 'Module'
2309 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2310 getModuleInfo mdl = withSession $ \hsc_env -> do
2311 let mg = hsc_mod_graph hsc_env
2312 if mdl `elem` map ms_mod mg
2313 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2315 {- if isHomeModule (hsc_dflags hsc_env) mdl
2317 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2318 -- getPackageModuleInfo will attempt to find the interface, so
2319 -- we don't want to call it for a home module, just in case there
2320 -- was a problem loading the module and the interface doesn't
2321 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2323 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2325 getPackageModuleInfo hsc_env mdl = do
2326 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2328 Nothing -> return Nothing
2330 eps <- readIORef (hsc_EPS hsc_env)
2332 names = availsToNameSet avails
2334 tys = [ ty | name <- concatMap availNames avails,
2335 Just ty <- [lookupTypeEnv pte name] ]
2337 return (Just (ModuleInfo {
2338 minf_type_env = mkTypeEnv tys,
2339 minf_exports = names,
2340 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2341 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2342 minf_modBreaks = emptyModBreaks
2345 getPackageModuleInfo _hsc_env _mdl = do
2346 -- bogusly different for non-GHCI (ToDo)
2350 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2351 getHomeModuleInfo hsc_env mdl =
2352 case lookupUFM (hsc_HPT hsc_env) mdl of
2353 Nothing -> return Nothing
2355 let details = hm_details hmi
2356 return (Just (ModuleInfo {
2357 minf_type_env = md_types details,
2358 minf_exports = availsToNameSet (md_exports details),
2359 minf_rdr_env = mi_globals $! hm_iface hmi,
2360 minf_instances = md_insts details
2362 ,minf_modBreaks = getModBreaks hmi
2366 -- | The list of top-level entities defined in a module
2367 modInfoTyThings :: ModuleInfo -> [TyThing]
2368 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2370 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2371 modInfoTopLevelScope minf
2372 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2374 modInfoExports :: ModuleInfo -> [Name]
2375 modInfoExports minf = nameSetToList $! minf_exports minf
2377 -- | Returns the instances defined by the specified module.
2378 -- Warning: currently unimplemented for package modules.
2379 modInfoInstances :: ModuleInfo -> [Instance]
2380 modInfoInstances = minf_instances
2382 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2383 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2385 mkPrintUnqualifiedForModule :: GhcMonad m =>
2387 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2388 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2389 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2391 modInfoLookupName :: GhcMonad m =>
2393 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2394 modInfoLookupName minf name = withSession $ \hsc_env -> do
2395 case lookupTypeEnv (minf_type_env minf) name of
2396 Just tyThing -> return (Just tyThing)
2398 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2399 return $! lookupType (hsc_dflags hsc_env)
2400 (hsc_HPT hsc_env) (eps_PTE eps) name
2403 modInfoModBreaks :: ModuleInfo -> ModBreaks
2404 modInfoModBreaks = minf_modBreaks
2407 isDictonaryId :: Id -> Bool
2409 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2411 -- | Looks up a global name: that is, any top-level name in any
2412 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2413 -- the interactive context, and therefore does not require a preceding
2415 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2416 lookupGlobalName name = withSession $ \hsc_env -> do
2417 liftIO $ lookupTypeHscEnv hsc_env name
2419 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
2420 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
2421 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
2422 return (findAnns deserialize ann_env target)
2425 -- | get the GlobalRdrEnv for a session
2426 getGRE :: GhcMonad m => m GlobalRdrEnv
2427 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2430 -- -----------------------------------------------------------------------------
2431 -- Misc exported utils
2433 dataConType :: DataCon -> Type
2434 dataConType dc = idType (dataConWrapId dc)
2436 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2437 pprParenSymName :: NamedThing a => a -> SDoc
2438 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2440 -- ----------------------------------------------------------------------------
2445 -- - Data and Typeable instances for HsSyn.
2447 -- ToDo: check for small transformations that happen to the syntax in
2448 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2450 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2451 -- to get from TyCons, Ids etc. to TH syntax (reify).
2453 -- :browse will use either lm_toplev or inspect lm_interface, depending
2454 -- on whether the module is interpreted or not.
2458 -- Extract the filename, stringbuffer content and dynflags associed to a module
2460 -- XXX: Explain pre-conditions
2461 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
2462 getModuleSourceAndFlags mod = do
2463 m <- getModSummary (moduleName mod)
2464 case ml_hs_file $ ms_location m of
2465 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
2466 Just sourceFile -> do
2467 source <- liftIO $ hGetStringBuffer sourceFile
2468 return (sourceFile, source, ms_hspp_opts m)
2471 -- | Return module source as token stream, including comments.
2473 -- The module must be in the module graph and its source must be available.
2474 -- Throws a 'HscTypes.SourceError' on parse error.
2475 getTokenStream :: GhcMonad m => Module -> m [Located Token]
2476 getTokenStream mod = do
2477 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2478 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2479 case lexTokenStream source startLoc flags of
2480 POk _ ts -> return ts
2481 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2483 -- | Give even more information on the source than 'getTokenStream'
2484 -- This function allows reconstructing the source completely with
2485 -- 'showRichTokenStream'.
2486 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
2487 getRichTokenStream mod = do
2488 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2489 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2490 case lexTokenStream source startLoc flags of
2491 POk _ ts -> return $ addSourceToTokens startLoc source ts
2492 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2494 -- | Given a source location and a StringBuffer corresponding to this
2495 -- location, return a rich token stream with the source associated to the
2497 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
2498 -> [(Located Token, String)]
2499 addSourceToTokens _ _ [] = []
2500 addSourceToTokens loc buf (t@(L span _) : ts)
2501 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
2502 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
2504 (newLoc, newBuf, str) = go "" loc buf
2505 start = srcSpanStart span
2506 end = srcSpanEnd span
2507 go acc loc buf | loc < start = go acc nLoc nBuf
2508 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
2509 | otherwise = (loc, buf, reverse acc)
2510 where (ch, nBuf) = nextChar buf
2511 nLoc = advanceSrcLoc loc ch
2514 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
2515 -- return source code almost identical to the original code (except for
2516 -- insignificant whitespace.)
2517 showRichTokenStream :: [(Located Token, String)] -> String
2518 showRichTokenStream ts = go startLoc ts ""
2519 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
2520 startLoc = mkSrcLoc sourceFile 0 0
2522 go loc ((L span _, str):ts)
2523 | not (isGoodSrcSpan span) = go loc ts
2524 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
2527 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
2528 . ((replicate tokCol ' ') ++)
2531 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
2532 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
2533 tokEnd = srcSpanEnd span
2535 -- -----------------------------------------------------------------------------
2536 -- Interactive evaluation
2538 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2539 -- filesystem and package database to find the corresponding 'Module',
2540 -- using the algorithm that is used for an @import@ declaration.
2541 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2542 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2544 dflags = hsc_dflags hsc_env
2545 hpt = hsc_HPT hsc_env
2546 this_pkg = thisPackage dflags
2548 case lookupUFM hpt mod_name of
2549 Just mod_info -> return (mi_module (hm_iface mod_info))
2550 _not_a_home_module -> do
2551 res <- findImportedModule hsc_env mod_name maybe_pkg
2553 Found _ m | modulePackageId m /= this_pkg -> return m
2554 | otherwise -> ghcError (CmdLineError (showSDoc $
2555 text "module" <+> quotes (ppr (moduleName m)) <+>
2556 text "is not loaded"))
2557 err -> let msg = cannotFindModule dflags mod_name err in
2558 ghcError (CmdLineError (showSDoc msg))
2561 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2562 getHistorySpan h = withSession $ \hsc_env ->
2563 return$ InteractiveEval.getHistorySpan hsc_env h
2565 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
2566 obtainTermFromVal bound force ty a =
2567 withSession $ \hsc_env ->
2568 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
2570 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
2571 obtainTermFromId bound force id =
2572 withSession $ \hsc_env ->
2573 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id