1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
12 defaultCleanupHandler,
15 Ghc, GhcT, GhcMonad(..),
16 runGhc, runGhcT, initGhcMonad,
17 gcatch, gbracket, gfinally,
18 clearWarnings, getWarnings, hasWarnings,
19 printExceptionAndWarnings, printWarnings,
20 handleSourceError, defaultCallbacks, GhcApiCallbacks(..),
23 -- * Flags and settings
24 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
25 GhcMode(..), GhcLink(..), defaultObjectTarget,
32 Target(..), TargetId(..), Phase,
39 -- * Extending the program scope
42 extendGlobalTypeScope,
45 -- * Loading\/compiling the program
47 load, loadWithLogger, LoadHowMuch(..),
48 SuccessFlag(..), succeeded, failed,
49 defaultWarnErrLogger, WarnErrLogger,
50 workingDirectoryChanged,
51 parseModule, typecheckModule, desugarModule, loadModule,
52 ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
53 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
54 TypecheckedMod, ParsedMod,
55 moduleInfo, renamedSource, typecheckedSource,
56 parsedSource, coreModule,
57 compileToCoreModule, compileToCoreSimplified,
61 -- * Parsing Haddock comments
64 -- * Inspecting the module structure of the program
65 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
70 -- * Inspecting modules
77 modInfoIsExportedName,
81 mkPrintUnqualifiedForModule,
83 -- * Querying the environment
87 PrintUnqualified, alwaysQualify,
89 -- * Interactive evaluation
90 getBindings, getPrintUnqual,
93 setContext, getContext,
103 runStmt, SingleStep(..),
105 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
106 resumeHistory, resumeHistoryIx),
107 History(historyBreakInfo, historyEnclosingDecl),
108 GHC.getHistorySpan, getHistoryModule,
111 InteractiveEval.back,
112 InteractiveEval.forward,
115 InteractiveEval.compileExpr, HValue, dynCompileExpr,
117 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
119 ModBreaks(..), BreakIndex,
120 BreakInfo(breakInfo_number, breakInfo_module),
121 BreakArray, setBreakOn, setBreakOff, getBreak,
124 -- * Abstract syntax elements
130 Module, mkModule, pprModule, moduleName, modulePackageId,
131 ModuleName, mkModuleName, moduleNameString,
135 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
137 RdrName(Qual,Unqual),
141 isImplicitId, isDeadBinder,
142 isExportedId, isLocalId, isGlobalId,
144 isPrimOpId, isFCallId, isClassOpId_maybe,
145 isDataConWorkId, idDataCon,
146 isBottomingId, isDictonaryId,
147 recordSelectorFieldLabel,
149 -- ** Type constructors
151 tyConTyVars, tyConDataCons, tyConArity,
152 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
154 synTyConDefn, synTyConType, synTyConResKind,
160 -- ** Data constructors
162 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
163 dataConIsInfix, isVanillaDataCon,
165 StrictnessMark(..), isMarkedStrict,
169 classMethods, classSCTheta, classTvsFds,
174 instanceDFunId, pprInstance, pprInstanceHdr,
176 -- ** Types and Kinds
177 Type, splitForAllTys, funResultTy,
178 pprParendType, pprTypeApp,
181 ThetaType, pprThetaArrow,
187 module HsSyn, -- ToDo: remove extraneous bits
191 defaultFixity, maxPrecedence,
195 -- ** Source locations
197 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
198 srcLocFile, srcLocLine, srcLocCol,
200 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
201 srcSpanStart, srcSpanEnd,
203 srcSpanStartLine, srcSpanEndLine,
204 srcSpanStartCol, srcSpanEndCol,
209 -- *** Constructing Located
210 noLoc, mkGeneralLocated,
212 -- *** Deconstructing Located
215 -- *** Combining and comparing Located values
216 eqLocated, cmpLocated, combineLocs, addCLoc,
217 leftmost_smallest, leftmost_largest, rightmost,
221 GhcException(..), showGhcException,
223 -- * Token stream manipulations
225 getTokenStream, getRichTokenStream,
226 showRichTokenStream, addSourceToTokens,
236 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
237 * what StaticFlags should we expose, if any?
240 #include "HsVersions.h"
243 import qualified Linker
244 import Linker ( HValue )
248 import InteractiveEval
253 import TcRnTypes hiding (LIE)
254 import TcRnMonad ( initIfaceCheck )
258 import qualified HsSyn -- hack as we want to reexport the whole module
259 import HsSyn hiding ((<.>))
260 import Type hiding (typeKind)
261 import TcType hiding (typeKind)
264 import TysPrim ( alphaTyVars )
269 import Name hiding ( varName )
270 import OccName ( parenSymOcc )
271 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
273 import FamInstEnv ( emptyFamInstEnv )
277 import DriverPipeline
278 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
284 import StaticFlagParser
285 import qualified StaticFlags
286 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
291 import qualified UniqFM as UFM
297 import Bag ( unitBag, listToBag, emptyBag, isEmptyBag )
301 import StringBuffer ( StringBuffer, hGetStringBuffer, nextChar )
304 import Maybes ( expectJust, mapCatMaybes )
306 import HaddockLex ( tokenise )
310 import Control.Concurrent
311 import System.Directory ( getModificationTime, doesFileExist,
312 getCurrentDirectory )
315 import qualified Data.List as List
316 import Data.Typeable ( Typeable )
317 import Data.Word ( Word8 )
319 import System.Exit ( exitWith, ExitCode(..) )
320 import System.Time ( ClockTime, getClockTime )
323 import System.FilePath
325 import System.IO.Error ( try, isDoesNotExistError )
326 import Prelude hiding (init)
329 -- -----------------------------------------------------------------------------
330 -- Exception handlers
332 -- | Install some default exception handlers and run the inner computation.
333 -- Unless you want to handle exceptions yourself, you should wrap this around
334 -- the top level of your program. The default handlers output the error
335 -- message(s) to stderr and exit cleanly.
336 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
337 defaultErrorHandler dflags inner =
338 -- top-level exception handler: any unrecognised exception is a compiler bug.
339 ghandle (\exception -> liftIO $ do
341 case fromException exception of
342 -- an IO exception probably isn't our fault, so don't panic
343 Just (ioe :: IOException) ->
344 fatalErrorMsg dflags (text (show ioe))
345 _ -> case fromException exception of
346 Just StackOverflow ->
347 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
348 _ -> case fromException exception of
349 Just (ex :: ExitCode) -> throw ex
352 (text (show (Panic (show exception))))
353 exitWith (ExitFailure 1)
356 -- error messages propagated as exceptions
361 PhaseFailed _ code -> exitWith code
362 Interrupted -> exitWith (ExitFailure 1)
363 _ -> do fatalErrorMsg dflags (text (show ge))
364 exitWith (ExitFailure 1)
368 -- | Install a default cleanup handler to remove temporary files deposited by
369 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
370 -- want to override the error handling, but still get the ordinary cleanup
372 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
373 DynFlags -> m a -> m a
374 defaultCleanupHandler dflags inner =
375 -- make sure we clean up after ourselves
378 cleanTempFiles dflags
381 -- exceptions will be blocked while we clean the temporary files,
382 -- so there shouldn't be any difficulty if we receive further
385 -- | Print the error message and all warnings. Useful inside exception
386 -- handlers. Clears warnings after printing.
387 printExceptionAndWarnings :: GhcMonad m => SourceError -> m ()
388 printExceptionAndWarnings err = do
389 let errs = srcErrorMessages err
391 dflags <- getSessionDynFlags
393 -- Empty errors means we failed due to -Werror. (Since this function
394 -- takes a source error as argument, we know for sure _some_ error
395 -- did indeed happen.)
397 printBagOfWarnings dflags warns
398 printBagOfErrors dflags (unitBag warnIsErrorMsg)
399 else liftIO $ printBagOfErrors dflags errs
402 -- | Print all accumulated warnings using 'log_action'.
403 printWarnings :: GhcMonad m => m ()
405 dflags <- getSessionDynFlags
407 liftIO $ printBagOfWarnings dflags warns
410 -- | Run function for the 'Ghc' monad.
412 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
413 -- to this function will create a new session which should not be shared among
416 -- Any errors not handled inside the 'Ghc' action are propagated as IO
419 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
420 -> Ghc a -- ^ The action to perform.
422 runGhc mb_top_dir ghc = do
423 wref <- newIORef emptyBag
424 ref <- newIORef undefined
425 let session = Session ref wref
426 flip unGhc session $ do
427 initGhcMonad mb_top_dir
429 -- XXX: unregister interrupt handlers here?
431 -- | Run function for 'GhcT' monad transformer.
433 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
434 -- to this function will create a new session which should not be shared among
437 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
438 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
439 -> GhcT m a -- ^ The action to perform.
441 runGhcT mb_top_dir ghct = do
442 wref <- liftIO $ newIORef emptyBag
443 ref <- liftIO $ newIORef undefined
444 let session = Session ref wref
445 flip unGhcT session $ do
446 initGhcMonad mb_top_dir
449 -- | Initialise a GHC session.
451 -- If you implement a custom 'GhcMonad' you must call this function in the
452 -- monad run function. It will initialise the session variable and clear all
455 -- The first argument should point to the directory where GHC's library files
456 -- reside. More precisely, this should be the output of @ghc --print-libdir@
457 -- of the version of GHC the module using this API is compiled with. For
458 -- portability, you should use the @ghc-paths@ package, available at
459 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
461 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
462 initGhcMonad mb_top_dir = do
464 main_thread <- liftIO $ myThreadId
465 liftIO $ modifyMVar_ interruptTargetThread (return . (main_thread :))
466 liftIO $ installSignalHandlers
468 liftIO $ StaticFlags.initStaticOpts
470 dflags0 <- liftIO $ initDynFlags defaultDynFlags
471 dflags <- liftIO $ initSysTools mb_top_dir dflags0
472 env <- liftIO $ newHscEnv defaultCallbacks dflags
476 defaultCallbacks :: GhcApiCallbacks
479 reportModuleCompilationResult =
480 \_ mb_err -> defaultWarnErrLogger mb_err
483 -- -----------------------------------------------------------------------------
486 -- | Grabs the DynFlags from the Session
487 getSessionDynFlags :: GhcMonad m => m DynFlags
488 getSessionDynFlags = withSession (return . hsc_dflags)
490 -- | Updates the DynFlags in a Session. This also reads
491 -- the package database (unless it has already been read),
492 -- and prepares the compilers knowledge about packages. It
493 -- can be called again to load new packages: just add new
494 -- package flags to (packageFlags dflags).
496 -- Returns a list of new packages that may need to be linked in using
497 -- the dynamic linker (see 'linkPackages') as a result of new package
498 -- flags. If you are not doing linking or doing static linking, you
499 -- can ignore the list of packages returned.
501 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
502 setSessionDynFlags dflags = do
503 (dflags', preload) <- liftIO $ initPackages dflags
504 modifySession (\h -> h{ hsc_dflags = dflags' })
507 -- | If there is no -o option, guess the name of target executable
508 -- by using top-level source file name as a base.
509 guessOutputFile :: GhcMonad m => m ()
510 guessOutputFile = modifySession $ \env ->
511 let dflags = hsc_dflags env
512 mod_graph = hsc_mod_graph env
513 mainModuleSrcPath :: Maybe String
514 mainModuleSrcPath = do
515 let isMain = (== mainModIs dflags) . ms_mod
516 [ms] <- return (filter isMain mod_graph)
517 ml_hs_file (ms_location ms)
518 name = fmap dropExtension mainModuleSrcPath
520 #if defined(mingw32_HOST_OS)
521 -- we must add the .exe extention unconditionally here, otherwise
522 -- when name has an extension of its own, the .exe extension will
523 -- not be added by DriverPipeline.exeFileName. See #2248
524 name_exe = fmap (<.> "exe") name
529 case outputFile dflags of
531 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
533 -- -----------------------------------------------------------------------------
536 -- ToDo: think about relative vs. absolute file paths. And what
537 -- happens when the current directory changes.
539 -- | Sets the targets for this session. Each target may be a module name
540 -- or a filename. The targets correspond to the set of root modules for
541 -- the program\/library. Unloading the current program is achieved by
542 -- setting the current set of targets to be empty, followed by 'load'.
543 setTargets :: GhcMonad m => [Target] -> m ()
544 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
546 -- | Returns the current set of targets
547 getTargets :: GhcMonad m => m [Target]
548 getTargets = withSession (return . hsc_targets)
550 -- | Add another target.
551 addTarget :: GhcMonad m => Target -> m ()
553 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
556 removeTarget :: GhcMonad m => TargetId -> m ()
557 removeTarget target_id
558 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
560 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
562 -- | Attempts to guess what Target a string refers to. This function
563 -- implements the @--make@/GHCi command-line syntax for filenames:
565 -- - if the string looks like a Haskell source filename, then interpret it
568 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
571 -- - otherwise interpret the string as a module name
573 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
574 guessTarget str (Just phase)
575 = return (Target (TargetFile str (Just phase)) True Nothing)
576 guessTarget str Nothing
577 | isHaskellSrcFilename file
578 = return (target (TargetFile file Nothing))
580 = do exists <- liftIO $ doesFileExist hs_file
582 then return (target (TargetFile hs_file Nothing))
584 exists <- liftIO $ doesFileExist lhs_file
586 then return (target (TargetFile lhs_file Nothing))
588 if looksLikeModuleName file
589 then return (target (TargetModule (mkModuleName file)))
592 (ProgramError (showSDoc $
593 text "target" <+> quotes (text file) <+>
594 text "is not a module name or a source file"))
597 | '*':rest <- str = (rest, False)
598 | otherwise = (str, True)
600 hs_file = file <.> "hs"
601 lhs_file = file <.> "lhs"
603 target tid = Target tid obj_allowed Nothing
605 -- -----------------------------------------------------------------------------
606 -- Extending the program scope
608 extendGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
609 extendGlobalRdrScope rdrElts
610 = modifySession $ \hscEnv ->
611 let global_rdr = hsc_global_rdr_env hscEnv
612 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
614 setGlobalRdrScope :: GhcMonad m => [GlobalRdrElt] -> m ()
615 setGlobalRdrScope rdrElts
616 = modifySession $ \hscEnv ->
617 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
619 extendGlobalTypeScope :: GhcMonad m => [Id] -> m ()
620 extendGlobalTypeScope ids
621 = modifySession $ \hscEnv ->
622 let global_type = hsc_global_type_env hscEnv
623 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
625 setGlobalTypeScope :: GhcMonad m => [Id] -> m ()
626 setGlobalTypeScope ids
627 = modifySession $ \hscEnv ->
628 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
630 -- -----------------------------------------------------------------------------
631 -- Parsing Haddock comments
633 parseHaddockComment :: String -> Either String (HsDoc RdrName)
634 parseHaddockComment string =
635 case parseHaddockParagraphs (tokenise string) of
639 -- -----------------------------------------------------------------------------
640 -- Loading the program
642 -- | Perform a dependency analysis starting from the current targets
643 -- and update the session with the new module graph.
645 -- Dependency analysis entails parsing the @import@ directives and may
646 -- therefore require running certain preprocessors.
648 -- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
649 -- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
650 -- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want to
651 -- changes to the 'DynFlags' to take effect you need to call this function
654 depanal :: GhcMonad m =>
655 [ModuleName] -- ^ excluded modules
656 -> Bool -- ^ allow duplicate roots
658 depanal excluded_mods allow_dup_roots = do
659 hsc_env <- getSession
661 dflags = hsc_dflags hsc_env
662 targets = hsc_targets hsc_env
663 old_graph = hsc_mod_graph hsc_env
665 liftIO $ showPass dflags "Chasing dependencies"
666 liftIO $ debugTraceMsg dflags 2 (hcat [
667 text "Chasing modules from: ",
668 hcat (punctuate comma (map pprTarget targets))])
670 mod_graph <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
671 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
674 -- | Describes which modules of the module graph need to be loaded.
677 -- ^ Load all targets and its dependencies.
678 | LoadUpTo ModuleName
679 -- ^ Load only the given module and its dependencies.
680 | LoadDependenciesOf ModuleName
681 -- ^ Load only the dependencies of the given module, but not the module
684 -- | Try to load the program. See 'LoadHowMuch' for the different modes.
686 -- This function implements the core of GHC's @--make@ mode. It preprocesses,
687 -- compiles and loads the specified modules, avoiding re-compilation wherever
688 -- possible. Depending on the target (see 'DynFlags.hscTarget') compilating
689 -- and loading may result in files being created on disk.
691 -- Calls the 'reportModuleCompilationResult' callback after each compiling
692 -- each module, whether successful or not.
694 -- Throw a 'SourceError' if errors are encountered before the actual
695 -- compilation starts (e.g., during dependency analysis). All other errors
696 -- are reported using the callback.
698 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
700 mod_graph <- depanal [] False
701 load2 how_much mod_graph
703 -- | A function called to log warnings and errors.
704 type WarnErrLogger = GhcMonad m => Maybe SourceError -> m ()
706 defaultWarnErrLogger :: WarnErrLogger
707 defaultWarnErrLogger Nothing = printWarnings
708 defaultWarnErrLogger (Just e) = printExceptionAndWarnings e
710 -- | Try to load the program. If a Module is supplied, then just
711 -- attempt to load up to this target. If no Module is supplied,
712 -- then try to load all targets.
714 -- The first argument is a function that is called after compiling each
715 -- module to print wanrings and errors.
717 -- While compiling a module, all 'SourceError's are caught and passed to the
718 -- logger, however, this function may still throw a 'SourceError' if
719 -- dependency analysis failed (e.g., due to a parse error).
721 loadWithLogger :: GhcMonad m => WarnErrLogger -> LoadHowMuch -> m SuccessFlag
722 loadWithLogger logger how_much = do
723 -- Dependency analysis first. Note that this fixes the module graph:
724 -- even if we don't get a fully successful upsweep, the full module
725 -- graph is still retained in the Session. We can tell which modules
726 -- were successfully loaded by inspecting the Session's HPT.
727 withLocalCallbacks (\cbs -> cbs { reportModuleCompilationResult =
731 load2 :: GhcMonad m => LoadHowMuch -> [ModSummary]
733 load2 how_much mod_graph = do
735 hsc_env <- getSession
737 let hpt1 = hsc_HPT hsc_env
738 let dflags = hsc_dflags hsc_env
740 -- The "bad" boot modules are the ones for which we have
741 -- B.hs-boot in the module graph, but no B.hs
742 -- The downsweep should have ensured this does not happen
744 let all_home_mods = [ms_mod_name s
745 | s <- mod_graph, not (isBootSummary s)]
746 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
747 not (ms_mod_name s `elem` all_home_mods)]
748 ASSERT( null bad_boot_mods ) return ()
750 -- check that the module given in HowMuch actually exists, otherwise
751 -- topSortModuleGraph will bomb later.
752 let checkHowMuch (LoadUpTo m) = checkMod m
753 checkHowMuch (LoadDependenciesOf m) = checkMod m
757 | m `elem` all_home_mods = and_then
759 liftIO $ errorMsg dflags (text "no such module:" <+>
763 checkHowMuch how_much $ do
765 -- mg2_with_srcimps drops the hi-boot nodes, returning a
766 -- graph with cycles. Among other things, it is used for
767 -- backing out partially complete cycles following a failed
768 -- upsweep, and for removing from hpt all the modules
769 -- not in strict downwards closure, during calls to compile.
770 let mg2_with_srcimps :: [SCC ModSummary]
771 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
773 -- If we can determine that any of the {-# SOURCE #-} imports
774 -- are definitely unnecessary, then emit a warning.
775 warnUnnecessarySourceImports mg2_with_srcimps
778 -- check the stability property for each module.
779 stable_mods@(stable_obj,stable_bco)
780 = checkStability hpt1 mg2_with_srcimps all_home_mods
782 -- prune bits of the HPT which are definitely redundant now,
784 pruned_hpt = pruneHomePackageTable hpt1
785 (flattenSCCs mg2_with_srcimps)
788 liftIO $ evaluate pruned_hpt
790 -- before we unload anything, make sure we don't leave an old
791 -- interactive context around pointing to dead bindings. Also,
792 -- write the pruned HPT to allow the old HPT to be GC'd.
793 modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext,
794 hsc_HPT = pruned_hpt }
796 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
797 text "Stable BCO:" <+> ppr stable_bco)
799 -- Unload any modules which are going to be re-linked this time around.
800 let stable_linkables = [ linkable
801 | m <- stable_obj++stable_bco,
802 Just hmi <- [lookupUFM pruned_hpt m],
803 Just linkable <- [hm_linkable hmi] ]
804 liftIO $ unload hsc_env stable_linkables
806 -- We could at this point detect cycles which aren't broken by
807 -- a source-import, and complain immediately, but it seems better
808 -- to let upsweep_mods do this, so at least some useful work gets
809 -- done before the upsweep is abandoned.
810 --hPutStrLn stderr "after tsort:\n"
811 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
813 -- Now do the upsweep, calling compile for each module in
814 -- turn. Final result is version 3 of everything.
816 -- Topologically sort the module graph, this time including hi-boot
817 -- nodes, and possibly just including the portion of the graph
818 -- reachable from the module specified in the 2nd argument to load.
819 -- This graph should be cycle-free.
820 -- If we're restricting the upsweep to a portion of the graph, we
821 -- also want to retain everything that is still stable.
822 let full_mg :: [SCC ModSummary]
823 full_mg = topSortModuleGraph False mod_graph Nothing
825 maybe_top_mod = case how_much of
827 LoadDependenciesOf m -> Just m
830 partial_mg0 :: [SCC ModSummary]
831 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
833 -- LoadDependenciesOf m: we want the upsweep to stop just
834 -- short of the specified module (unless the specified module
837 | LoadDependenciesOf _mod <- how_much
838 = ASSERT( case last partial_mg0 of
839 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
840 List.init partial_mg0
846 | AcyclicSCC ms <- full_mg,
847 ms_mod_name ms `elem` stable_obj++stable_bco,
848 ms_mod_name ms `notElem` [ ms_mod_name ms' |
849 AcyclicSCC ms' <- partial_mg ] ]
851 mg = stable_mg ++ partial_mg
853 -- clean up between compilations
854 let cleanup = cleanTempFilesExcept dflags
855 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
857 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
859 (upsweep_ok, hsc_env1, modsUpswept)
860 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
861 pruned_hpt stable_mods cleanup mg
863 -- Make modsDone be the summaries for each home module now
864 -- available; this should equal the domain of hpt3.
865 -- Get in in a roughly top .. bottom order (hence reverse).
867 let modsDone = reverse modsUpswept
869 -- Try and do linking in some form, depending on whether the
870 -- upsweep was completely or only partially successful.
872 if succeeded upsweep_ok
875 -- Easy; just relink it all.
876 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
878 -- Clean up after ourselves
879 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
881 -- Issue a warning for the confusing case where the user
882 -- said '-o foo' but we're not going to do any linking.
883 -- We attempt linking if either (a) one of the modules is
884 -- called Main, or (b) the user said -no-hs-main, indicating
885 -- that main() is going to come from somewhere else.
887 let ofile = outputFile dflags
888 let no_hs_main = dopt Opt_NoHsMain dflags
890 main_mod = mainModIs dflags
891 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
892 do_linking = a_root_is_Main || no_hs_main
894 when (ghcLink dflags == LinkBinary
895 && isJust ofile && not do_linking) $
896 liftIO $ debugTraceMsg dflags 1 $
897 text ("Warning: output was redirected with -o, " ++
898 "but no output will be generated\n" ++
899 "because there is no " ++
900 moduleNameString (moduleName main_mod) ++ " module.")
902 -- link everything together
903 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
905 loadFinish Succeeded linkresult hsc_env1
908 -- Tricky. We need to back out the effects of compiling any
909 -- half-done cycles, both so as to clean up the top level envs
910 -- and to avoid telling the interactive linker to link them.
911 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
914 = map ms_mod modsDone
915 let mods_to_zap_names
916 = findPartiallyCompletedCycles modsDone_names
919 = filter ((`notElem` mods_to_zap_names).ms_mod)
922 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
925 -- Clean up after ourselves
926 liftIO $ cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
928 -- there should be no Nothings where linkables should be, now
929 ASSERT(all (isJust.hm_linkable)
930 (eltsUFM (hsc_HPT hsc_env))) do
932 -- Link everything together
933 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
935 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
936 loadFinish Failed linkresult hsc_env4
938 -- Finish up after a load.
940 -- If the link failed, unload everything and return.
941 loadFinish :: GhcMonad m =>
942 SuccessFlag -> SuccessFlag -> HscEnv
944 loadFinish _all_ok Failed hsc_env
945 = do liftIO $ unload hsc_env []
946 modifySession $ \_ -> discardProg hsc_env
949 -- Empty the interactive context and set the module context to the topmost
950 -- newly loaded module, or the Prelude if none were loaded.
951 loadFinish all_ok Succeeded hsc_env
952 = do modifySession $ \_ -> hsc_env{ hsc_IC = emptyInteractiveContext }
956 -- Forget the current program, but retain the persistent info in HscEnv
957 discardProg :: HscEnv -> HscEnv
959 = hsc_env { hsc_mod_graph = emptyMG,
960 hsc_IC = emptyInteractiveContext,
961 hsc_HPT = emptyHomePackageTable }
963 -- used to fish out the preprocess output files for the purposes of
964 -- cleaning up. The preprocessed file *might* be the same as the
965 -- source file, but that doesn't do any harm.
966 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
967 ppFilesFromSummaries summaries = map ms_hspp_file summaries
969 -- -----------------------------------------------------------------------------
971 class ParsedMod m where
972 modSummary :: m -> ModSummary
973 parsedSource :: m -> ParsedSource
975 class ParsedMod m => TypecheckedMod m where
976 renamedSource :: m -> Maybe RenamedSource
977 typecheckedSource :: m -> TypecheckedSource
978 moduleInfo :: m -> ModuleInfo
979 tm_internals :: m -> (TcGblEnv, ModDetails)
980 -- ToDo: improvements that could be made here:
981 -- if the module succeeded renaming but not typechecking,
982 -- we can still get back the GlobalRdrEnv and exports, so
983 -- perhaps the ModuleInfo should be split up into separate
986 class TypecheckedMod m => DesugaredMod m where
987 coreModule :: m -> ModGuts
989 -- | The result of successful parsing.
991 ParsedModule { pm_mod_summary :: ModSummary
992 , pm_parsed_source :: ParsedSource }
994 instance ParsedMod ParsedModule where
995 modSummary m = pm_mod_summary m
996 parsedSource m = pm_parsed_source m
998 -- | The result of successful typechecking. It also contains the parser
1000 data TypecheckedModule =
1001 TypecheckedModule { tm_parsed_module :: ParsedModule
1002 , tm_renamed_source :: Maybe RenamedSource
1003 , tm_typechecked_source :: TypecheckedSource
1004 , tm_checked_module_info :: ModuleInfo
1005 , tm_internals_ :: (TcGblEnv, ModDetails)
1008 instance ParsedMod TypecheckedModule where
1009 modSummary m = modSummary (tm_parsed_module m)
1010 parsedSource m = parsedSource (tm_parsed_module m)
1012 instance TypecheckedMod TypecheckedModule where
1013 renamedSource m = tm_renamed_source m
1014 typecheckedSource m = tm_typechecked_source m
1015 moduleInfo m = tm_checked_module_info m
1016 tm_internals m = tm_internals_ m
1018 -- | The result of successful desugaring (i.e., translation to core). Also
1019 -- contains all the information of a typechecked module.
1020 data DesugaredModule =
1021 DesugaredModule { dm_typechecked_module :: TypecheckedModule
1022 , dm_core_module :: ModGuts
1025 instance ParsedMod DesugaredModule where
1026 modSummary m = modSummary (dm_typechecked_module m)
1027 parsedSource m = parsedSource (dm_typechecked_module m)
1029 instance TypecheckedMod DesugaredModule where
1030 renamedSource m = renamedSource (dm_typechecked_module m)
1031 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
1032 moduleInfo m = moduleInfo (dm_typechecked_module m)
1033 tm_internals m = tm_internals_ (dm_typechecked_module m)
1035 instance DesugaredMod DesugaredModule where
1036 coreModule m = dm_core_module m
1038 type ParsedSource = Located (HsModule RdrName)
1039 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
1040 Maybe (HsDoc Name), HaddockModInfo Name)
1041 type TypecheckedSource = LHsBinds Id
1044 -- - things that aren't in the output of the typechecker right now:
1045 -- - the export list
1047 -- - type signatures
1048 -- - type/data/newtype declarations
1049 -- - class declarations
1051 -- - extra things in the typechecker's output:
1052 -- - default methods are turned into top-level decls.
1053 -- - dictionary bindings
1055 -- | Return the 'ModSummary' of a module with the given name.
1057 -- The module must be part of the module graph (see 'hsc_mod_graph' and
1058 -- 'ModuleGraph'). If this is not the case, this function will throw a
1061 -- This function ignores boot modules and requires that there is only one
1062 -- non-boot module with the given name.
1063 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
1064 getModSummary mod = do
1065 mg <- liftM hsc_mod_graph getSession
1066 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
1067 [] -> throw $ mkApiErr (text "Module not part of module graph")
1069 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
1071 -- | Parse a module.
1073 -- Throws a 'SourceError' on parse error.
1074 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
1076 rdr_module <- withTempSession
1077 (\e -> e { hsc_dflags = ms_hspp_opts ms }) $
1079 return (ParsedModule ms rdr_module)
1081 -- | Typecheck and rename a parsed module.
1083 -- Throws a 'SourceError' if either fails.
1084 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
1085 typecheckModule pmod = do
1086 let ms = modSummary pmod
1087 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1088 (tc_gbl_env, rn_info)
1089 <- hscTypecheckRename ms (parsedSource pmod)
1090 details <- makeSimpleDetails tc_gbl_env
1093 tm_internals_ = (tc_gbl_env, details),
1094 tm_parsed_module = pmod,
1095 tm_renamed_source = rn_info,
1096 tm_typechecked_source = tcg_binds tc_gbl_env,
1097 tm_checked_module_info =
1099 minf_type_env = md_types details,
1100 minf_exports = availsToNameSet $ md_exports details,
1101 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
1102 minf_instances = md_insts details
1104 ,minf_modBreaks = emptyModBreaks
1108 -- | Desugar a typechecked module.
1109 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
1110 desugarModule tcm = do
1111 let ms = modSummary tcm
1112 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1113 let (tcg, _) = tm_internals tcm
1114 guts <- hscDesugar ms tcg
1117 dm_typechecked_module = tcm,
1118 dm_core_module = guts
1121 -- | Load a module. Input doesn't need to be desugared.
1123 -- XXX: Describe usage.
1124 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
1126 let ms = modSummary tcm
1127 let mod = ms_mod_name ms
1128 let (tcg, _details) = tm_internals tcm
1130 withTempSession (\e -> e { hsc_dflags = ms_hspp_opts ms }) $ do
1132 let compilerBackend comp env ms' _ _mb_old_iface _ =
1133 withTempSession (\_ -> env) $
1134 hscBackend comp tcg ms'
1136 hsc_env <- getSession
1138 <- compile' (compilerBackend hscNothingCompiler
1139 ,compilerBackend hscInteractiveCompiler
1140 ,compilerBackend hscBatchCompiler)
1141 hsc_env ms 1 1 Nothing Nothing
1142 -- compile' shouldn't change the environment
1143 return $ addToUFM (hsc_HPT hsc_env) mod mod_info
1144 modifySession $ \e -> e{ hsc_HPT = hpt_new }
1147 -- | This is the way to get access to the Core bindings corresponding
1148 -- to a module. 'compileToCore' parses, typechecks, and
1149 -- desugars the module, then returns the resulting Core module (consisting of
1150 -- the module name, type declarations, and function declarations) if
1152 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
1153 compileToCoreModule = compileCore False
1155 -- | Like compileToCoreModule, but invokes the simplifier, so
1156 -- as to return simplified and tidied Core.
1157 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
1158 compileToCoreSimplified = compileCore True
1160 -- | Provided for backwards-compatibility: compileToCore returns just the Core
1161 -- bindings, but for most purposes, you probably want to call
1162 -- compileToCoreModule.
1163 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
1164 compileToCore fn = do
1165 mod <- compileToCoreModule session fn
1166 return $ cm_binds mod
1168 -- | Takes a CoreModule and compiles the bindings therein
1169 -- to object code. The first argument is a bool flag indicating
1170 -- whether to run the simplifier.
1171 -- The resulting .o, .hi, and executable files, if any, are stored in the
1172 -- current directory, and named according to the module name.
1173 -- This has only so far been tested with a single self-contained module.
1174 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
1175 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
1176 dflags <- getSessionDynFlags
1177 currentTime <- liftIO $ getClockTime
1178 cwd <- liftIO $ getCurrentDirectory
1179 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
1180 ((moduleNameSlashes . moduleName) mName)
1182 let modSummary = ModSummary { ms_mod = mName,
1183 ms_hsc_src = ExtCoreFile,
1184 ms_location = modLocation,
1185 -- By setting the object file timestamp to Nothing,
1186 -- we always force recompilation, which is what we
1187 -- want. (Thus it doesn't matter what the timestamp
1188 -- for the (nonexistent) source file is.)
1189 ms_hs_date = currentTime,
1190 ms_obj_date = Nothing,
1191 -- Only handling the single-module case for now, so no imports.
1196 ms_hspp_opts = dflags,
1197 ms_hspp_buf = Nothing
1200 let maybe_simplify mod_guts | simplify = hscSimplify mod_guts
1201 | otherwise = return mod_guts
1202 guts <- maybe_simplify (mkModGuts cm)
1203 (iface, changed, _details, cgguts)
1204 <- hscNormalIface guts Nothing
1205 hscWriteIface iface changed modSummary
1206 hscGenHardCode cgguts modSummary
1209 -- Makes a "vanilla" ModGuts.
1210 mkModGuts :: CoreModule -> ModGuts
1211 mkModGuts coreModule = ModGuts {
1212 mg_module = cm_module coreModule,
1215 mg_deps = noDependencies,
1216 mg_dir_imps = emptyModuleEnv,
1217 mg_used_names = emptyNameSet,
1218 mg_rdr_env = emptyGlobalRdrEnv,
1219 mg_fix_env = emptyFixityEnv,
1220 mg_types = emptyTypeEnv,
1224 mg_binds = cm_binds coreModule,
1225 mg_foreign = NoStubs,
1226 mg_warns = NoWarnings,
1228 mg_hpc_info = emptyHpcInfo False,
1229 mg_modBreaks = emptyModBreaks,
1230 mg_vect_info = noVectInfo,
1231 mg_inst_env = emptyInstEnv,
1232 mg_fam_inst_env = emptyFamInstEnv
1235 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
1236 compileCore simplify fn = do
1237 -- First, set the target to the desired filename
1238 target <- guessTarget fn Nothing
1241 -- Then find dependencies
1242 modGraph <- depanal [] True
1243 case find ((== fn) . msHsFilePath) modGraph of
1244 Just modSummary -> do
1245 -- Now we have the module name;
1246 -- parse, typecheck and desugar the module
1247 mod_guts <- coreModule `fmap`
1248 -- TODO: space leaky: call hsc* directly?
1249 (desugarModule =<< typecheckModule =<< parseModule modSummary)
1250 liftM gutsToCoreModule $
1253 -- If simplify is true: simplify (hscSimplify), then tidy
1255 hsc_env <- getSession
1256 simpl_guts <- hscSimplify mod_guts
1257 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
1258 return $ Left tidy_guts
1260 return $ Right mod_guts
1262 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1263 module dependency graph"
1264 where -- two versions, based on whether we simplify (thus run tidyProgram,
1265 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1266 -- we just have a ModGuts.
1267 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1268 gutsToCoreModule (Left (cg, md)) = CoreModule {
1269 cm_module = cg_module cg, cm_types = md_types md,
1270 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1272 gutsToCoreModule (Right mg) = CoreModule {
1273 cm_module = mg_module mg, cm_types = mg_types mg,
1274 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1277 -- ---------------------------------------------------------------------------
1280 unload :: HscEnv -> [Linkable] -> IO ()
1281 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1282 = case ghcLink (hsc_dflags hsc_env) of
1284 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1286 LinkInMemory -> panic "unload: no interpreter"
1287 -- urgh. avoid warnings:
1288 hsc_env stable_linkables
1292 -- -----------------------------------------------------------------------------
1296 Stability tells us which modules definitely do not need to be recompiled.
1297 There are two main reasons for having stability:
1299 - avoid doing a complete upsweep of the module graph in GHCi when
1300 modules near the bottom of the tree have not changed.
1302 - to tell GHCi when it can load object code: we can only load object code
1303 for a module when we also load object code fo all of the imports of the
1304 module. So we need to know that we will definitely not be recompiling
1305 any of these modules, and we can use the object code.
1307 The stability check is as follows. Both stableObject and
1308 stableBCO are used during the upsweep phase later.
1311 stable m = stableObject m || stableBCO m
1314 all stableObject (imports m)
1315 && old linkable does not exist, or is == on-disk .o
1316 && date(on-disk .o) > date(.hs)
1319 all stable (imports m)
1320 && date(BCO) > date(.hs)
1323 These properties embody the following ideas:
1325 - if a module is stable, then:
1327 - if it has been compiled in a previous pass (present in HPT)
1328 then it does not need to be compiled or re-linked.
1330 - if it has not been compiled in a previous pass,
1331 then we only need to read its .hi file from disk and
1332 link it to produce a 'ModDetails'.
1334 - if a modules is not stable, we will definitely be at least
1335 re-linking, and possibly re-compiling it during the 'upsweep'.
1336 All non-stable modules can (and should) therefore be unlinked
1337 before the 'upsweep'.
1339 - Note that objects are only considered stable if they only depend
1340 on other objects. We can't link object code against byte code.
1344 :: HomePackageTable -- HPT from last compilation
1345 -> [SCC ModSummary] -- current module graph (cyclic)
1346 -> [ModuleName] -- all home modules
1347 -> ([ModuleName], -- stableObject
1348 [ModuleName]) -- stableBCO
1350 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1352 checkSCC (stable_obj, stable_bco) scc0
1353 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1354 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1355 | otherwise = (stable_obj, stable_bco)
1357 scc = flattenSCC scc0
1358 scc_mods = map ms_mod_name scc
1359 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1361 scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
1362 -- all imports outside the current SCC, but in the home pkg
1364 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1365 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1369 && all object_ok scc
1372 and (zipWith (||) stable_obj_imps stable_bco_imps)
1376 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1380 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1381 Just hmi | Just l <- hm_linkable hmi
1382 -> isObjectLinkable l && t == linkableTime l
1384 -- why '>=' rather than '>' above? If the filesystem stores
1385 -- times to the nearset second, we may occasionally find that
1386 -- the object & source have the same modification time,
1387 -- especially if the source was automatically generated
1388 -- and compiled. Using >= is slightly unsafe, but it matches
1389 -- make's behaviour.
1392 = case lookupUFM hpt (ms_mod_name ms) of
1393 Just hmi | Just l <- hm_linkable hmi ->
1394 not (isObjectLinkable l) &&
1395 linkableTime l >= ms_hs_date ms
1398 -- -----------------------------------------------------------------------------
1400 -- | Prune the HomePackageTable
1402 -- Before doing an upsweep, we can throw away:
1404 -- - For non-stable modules:
1405 -- - all ModDetails, all linked code
1406 -- - all unlinked code that is out of date with respect to
1409 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1410 -- space at the end of the upsweep, because the topmost ModDetails of the
1411 -- old HPT holds on to the entire type environment from the previous
1414 pruneHomePackageTable
1417 -> ([ModuleName],[ModuleName])
1420 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1423 | is_stable modl = hmi'
1424 | otherwise = hmi'{ hm_details = emptyModDetails }
1426 modl = moduleName (mi_module (hm_iface hmi))
1427 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1428 = hmi{ hm_linkable = Nothing }
1431 where ms = expectJust "prune" (lookupUFM ms_map modl)
1433 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1435 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1437 -- -----------------------------------------------------------------------------
1439 -- Return (names of) all those in modsDone who are part of a cycle
1440 -- as defined by theGraph.
1441 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1442 findPartiallyCompletedCycles modsDone theGraph
1446 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1447 chew ((CyclicSCC vs):rest)
1448 = let names_in_this_cycle = nub (map ms_mod vs)
1450 = nub ([done | done <- modsDone,
1451 done `elem` names_in_this_cycle])
1452 chewed_rest = chew rest
1454 if notNull mods_in_this_cycle
1455 && length mods_in_this_cycle < length names_in_this_cycle
1456 then mods_in_this_cycle ++ chewed_rest
1459 -- -----------------------------------------------------------------------------
1463 -- This is where we compile each module in the module graph, in a pass
1464 -- from the bottom to the top of the graph.
1466 -- There better had not be any cyclic groups here -- we check for them.
1470 HscEnv -- ^ Includes initially-empty HPT
1471 -> HomePackageTable -- ^ HPT from last time round (pruned)
1472 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1473 -> IO () -- ^ How to clean up unwanted tmp files
1474 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1480 -- 1. A flag whether the complete upsweep was successful.
1481 -- 2. The 'HscEnv' with an updated HPT
1482 -- 3. A list of modules which succeeded loading.
1484 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1485 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1486 return (res, hsc_env, reverse done)
1489 upsweep' hsc_env _old_hpt done
1491 = return (Succeeded, hsc_env, done)
1493 upsweep' hsc_env _old_hpt done
1494 (CyclicSCC ms:_) _ _
1495 = do liftIO $ fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1496 return (Failed, hsc_env, done)
1498 upsweep' hsc_env old_hpt done
1499 (AcyclicSCC mod:mods) mod_index nmods
1500 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1501 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1502 -- (moduleEnvElts (hsc_HPT hsc_env)))
1503 let logger = reportModuleCompilationResult (hsc_callbacks hsc_env)
1506 <- handleSourceError
1507 (\err -> do logger mod (Just err); return Nothing) $ do
1508 mod_info <- upsweep_mod hsc_env old_hpt stable_mods
1510 logger mod Nothing -- log warnings
1511 return (Just mod_info)
1513 liftIO cleanup -- Remove unwanted tmp files between compilations
1516 Nothing -> return (Failed, hsc_env, done)
1518 let this_mod = ms_mod_name mod
1520 -- Add new info to hsc_env
1521 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1522 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1524 -- Space-saving: delete the old HPT entry
1525 -- for mod BUT if mod is a hs-boot
1526 -- node, don't delete it. For the
1527 -- interface, the HPT entry is probaby for the
1528 -- main Haskell source file. Deleting it
1529 -- would force the real module to be recompiled
1531 old_hpt1 | isBootSummary mod = old_hpt
1532 | otherwise = delFromUFM old_hpt this_mod
1536 -- fixup our HomePackageTable after we've finished compiling
1537 -- a mutually-recursive loop. See reTypecheckLoop, below.
1538 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1540 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1542 -- | Compile a single module. Always produce a Linkable for it if
1543 -- successful. If no compilation happened, return the old Linkable.
1544 upsweep_mod :: GhcMonad m =>
1547 -> ([ModuleName],[ModuleName])
1549 -> Int -- index of module
1550 -> Int -- total number of modules
1553 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1555 this_mod_name = ms_mod_name summary
1556 this_mod = ms_mod summary
1557 mb_obj_date = ms_obj_date summary
1558 obj_fn = ml_obj_file (ms_location summary)
1559 hs_date = ms_hs_date summary
1561 is_stable_obj = this_mod_name `elem` stable_obj
1562 is_stable_bco = this_mod_name `elem` stable_bco
1564 old_hmi = lookupUFM old_hpt this_mod_name
1566 -- We're using the dflags for this module now, obtained by
1567 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1568 dflags = ms_hspp_opts summary
1569 prevailing_target = hscTarget (hsc_dflags hsc_env)
1570 local_target = hscTarget dflags
1572 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1573 -- we don't do anything dodgy: these should only work to change
1574 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1575 -- end up trying to link object code to byte code.
1576 target = if prevailing_target /= local_target
1577 && (not (isObjectTarget prevailing_target)
1578 || not (isObjectTarget local_target))
1579 then prevailing_target
1582 -- store the corrected hscTarget into the summary
1583 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1585 -- The old interface is ok if
1586 -- a) we're compiling a source file, and the old HPT
1587 -- entry is for a source file
1588 -- b) we're compiling a hs-boot file
1589 -- Case (b) allows an hs-boot file to get the interface of its
1590 -- real source file on the second iteration of the compilation
1591 -- manager, but that does no harm. Otherwise the hs-boot file
1592 -- will always be recompiled
1597 Just hm_info | isBootSummary summary -> Just iface
1598 | not (mi_boot iface) -> Just iface
1599 | otherwise -> Nothing
1601 iface = hm_iface hm_info
1603 compile_it :: GhcMonad m => Maybe Linkable -> m HomeModInfo
1604 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1606 compile_it_discard_iface :: GhcMonad m =>
1607 Maybe Linkable -> m HomeModInfo
1608 compile_it_discard_iface
1609 = compile hsc_env summary' mod_index nmods Nothing
1611 -- With the HscNothing target we create empty linkables to avoid
1612 -- recompilation. We have to detect these to recompile anyway if
1613 -- the target changed since the last compile.
1615 | Just hmi <- old_hmi, Just l <- hm_linkable hmi =
1616 null (linkableUnlinked l)
1618 -- we have no linkable, so it cannot be fake
1621 implies False _ = True
1627 -- Regardless of whether we're generating object code or
1628 -- byte code, we can always use an existing object file
1629 -- if it is *stable* (see checkStability).
1630 | is_stable_obj, Just hmi <- old_hmi -> do
1631 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1632 (text "skipping stable obj mod:" <+> ppr this_mod_name)
1634 -- object is stable, and we have an entry in the
1635 -- old HPT: nothing to do
1637 | is_stable_obj, isNothing old_hmi -> do
1638 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1639 (text "compiling stable on-disk mod:" <+> ppr this_mod_name)
1640 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1641 (expectJust "upsweep1" mb_obj_date)
1642 compile_it (Just linkable)
1643 -- object is stable, but we need to load the interface
1644 -- off disk to make a HMI.
1646 | not (isObjectTarget target), is_stable_bco,
1647 (target /= HscNothing) `implies` not is_fake_linkable ->
1648 ASSERT(isJust old_hmi) -- must be in the old_hpt
1649 let Just hmi = old_hmi in do
1650 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1651 (text "skipping stable BCO mod:" <+> ppr this_mod_name)
1653 -- BCO is stable: nothing to do
1655 | not (isObjectTarget target),
1656 Just hmi <- old_hmi,
1657 Just l <- hm_linkable hmi,
1658 not (isObjectLinkable l),
1659 (target /= HscNothing) `implies` not is_fake_linkable,
1660 linkableTime l >= ms_hs_date summary -> do
1661 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1662 (text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
1664 -- we have an old BCO that is up to date with respect
1665 -- to the source: do a recompilation check as normal.
1667 -- When generating object code, if there's an up-to-date
1668 -- object file on the disk, then we can use it.
1669 -- However, if the object file is new (compared to any
1670 -- linkable we had from a previous compilation), then we
1671 -- must discard any in-memory interface, because this
1672 -- means the user has compiled the source file
1673 -- separately and generated a new interface, that we must
1674 -- read from the disk.
1676 | isObjectTarget target,
1677 Just obj_date <- mb_obj_date,
1678 obj_date >= hs_date -> do
1681 | Just l <- hm_linkable hmi,
1682 isObjectLinkable l && linkableTime l == obj_date -> do
1683 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1684 (text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
1687 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1688 (text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
1689 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1690 compile_it_discard_iface (Just linkable)
1693 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1694 (text "compiling mod:" <+> ppr this_mod_name)
1699 -- Filter modules in the HPT
1700 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1701 retainInTopLevelEnvs keep_these hpt
1702 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1704 , let mb_mod_info = lookupUFM hpt mod
1705 , isJust mb_mod_info ]
1707 -- ---------------------------------------------------------------------------
1708 -- Typecheck module loops
1711 See bug #930. This code fixes a long-standing bug in --make. The
1712 problem is that when compiling the modules *inside* a loop, a data
1713 type that is only defined at the top of the loop looks opaque; but
1714 after the loop is done, the structure of the data type becomes
1717 The difficulty is then that two different bits of code have
1718 different notions of what the data type looks like.
1720 The idea is that after we compile a module which also has an .hs-boot
1721 file, we re-generate the ModDetails for each of the modules that
1722 depends on the .hs-boot file, so that everyone points to the proper
1723 TyCons, Ids etc. defined by the real module, not the boot module.
1724 Fortunately re-generating a ModDetails from a ModIface is easy: the
1725 function TcIface.typecheckIface does exactly that.
1727 Picking the modules to re-typecheck is slightly tricky. Starting from
1728 the module graph consisting of the modules that have already been
1729 compiled, we reverse the edges (so they point from the imported module
1730 to the importing module), and depth-first-search from the .hs-boot
1731 node. This gives us all the modules that depend transitively on the
1732 .hs-boot module, and those are exactly the modules that we need to
1735 Following this fix, GHC can compile itself with --make -O2.
1738 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1739 reTypecheckLoop hsc_env ms graph
1740 | not (isBootSummary ms) &&
1741 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1743 let mss = reachableBackwards (ms_mod_name ms) graph
1744 non_boot = filter (not.isBootSummary) mss
1745 debugTraceMsg (hsc_dflags hsc_env) 2 $
1746 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1747 typecheckLoop hsc_env (map ms_mod_name non_boot)
1751 this_mod = ms_mod ms
1753 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1754 typecheckLoop hsc_env mods = do
1756 fixIO $ \new_hpt -> do
1757 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1758 mds <- initIfaceCheck new_hsc_env $
1759 mapM (typecheckIface . hm_iface) hmis
1760 let new_hpt = addListToUFM old_hpt
1761 (zip mods [ hmi{ hm_details = details }
1762 | (hmi,details) <- zip hmis mds ])
1764 return hsc_env{ hsc_HPT = new_hpt }
1766 old_hpt = hsc_HPT hsc_env
1767 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1769 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1770 reachableBackwards mod summaries
1771 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1772 where -- the rest just sets up the graph:
1773 (graph, lookup_node) = moduleGraphNodes False summaries
1774 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1776 -- ---------------------------------------------------------------------------
1777 -- Topological sort of the module graph
1779 type SummaryNode = (ModSummary, Int, [Int])
1783 -- ^ Drop hi-boot nodes? (see below)
1786 -- ^ Root module name. If @Nothing@, use the full graph.
1788 -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1789 -- The resulting list of strongly-connected-components is in topologically
1790 -- sorted order, starting with the module(s) at the bottom of the
1791 -- dependency graph (ie compile them first) and ending with the ones at
1794 -- Drop hi-boot nodes (first boolean arg)?
1796 -- - @False@: treat the hi-boot summaries as nodes of the graph,
1797 -- so the graph must be acyclic
1799 -- - @True@: eliminate the hi-boot nodes, and instead pretend
1800 -- the a source-import of Foo is an import of Foo
1801 -- The resulting graph has no hi-boot nodes, but can be cyclic
1803 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1804 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1806 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1808 initial_graph = case mb_root_mod of
1811 -- restrict the graph to just those modules reachable from
1812 -- the specified module. We do this by building a graph with
1813 -- the full set of nodes, and determining the reachable set from
1814 -- the specified node.
1815 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1816 | otherwise = ghcError (ProgramError "module does not exist")
1817 in graphFromEdgedVertices (seq root (reachableG graph root))
1819 summaryNodeKey :: SummaryNode -> Int
1820 summaryNodeKey (_, k, _) = k
1822 summaryNodeSummary :: SummaryNode -> ModSummary
1823 summaryNodeSummary (s, _, _) = s
1825 moduleGraphNodes :: Bool -> [ModSummary]
1826 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1827 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1829 numbered_summaries = zip summaries [1..]
1831 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1832 lookup_node hs_src mod = lookupFM node_map (mod, hs_src)
1834 lookup_key :: HscSource -> ModuleName -> Maybe Int
1835 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1837 node_map :: NodeMap SummaryNode
1838 node_map = listToFM [ ((moduleName (ms_mod s), ms_hsc_src s), node)
1839 | node@(s, _, _) <- nodes ]
1841 -- We use integers as the keys for the SCC algorithm
1842 nodes :: [SummaryNode]
1843 nodes = [ (s, key, out_keys)
1844 | (s, key) <- numbered_summaries
1845 -- Drop the hi-boot ones if told to do so
1846 , not (isBootSummary s && drop_hs_boot_nodes)
1847 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
1848 out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
1849 (-- see [boot-edges] below
1850 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1852 else case lookup_key HsBootFile (ms_mod_name s) of
1856 -- [boot-edges] if this is a .hs and there is an equivalent
1857 -- .hs-boot, add a link from the former to the latter. This
1858 -- has the effect of detecting bogus cases where the .hs-boot
1859 -- depends on the .hs, by introducing a cycle. Additionally,
1860 -- it ensures that we will always process the .hs-boot before
1861 -- the .hs, and so the HomePackageTable will always have the
1862 -- most up to date information.
1864 -- Drop hs-boot nodes by using HsSrcFile as the key
1865 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1866 | otherwise = HsBootFile
1868 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1869 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1870 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1871 -- the IsBootInterface parameter True; else False
1874 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1875 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1877 msKey :: ModSummary -> NodeKey
1878 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1880 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1881 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1883 nodeMapElts :: NodeMap a -> [a]
1884 nodeMapElts = eltsFM
1886 -- | If there are {-# SOURCE #-} imports between strongly connected
1887 -- components in the topological sort, then those imports can
1888 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1889 -- were necessary, then the edge would be part of a cycle.
1890 warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
1891 warnUnnecessarySourceImports sccs =
1892 logWarnings (listToBag (concatMap (check.flattenSCC) sccs))
1894 let mods_in_this_cycle = map ms_mod_name ms in
1895 [ warn i | m <- ms, i <- ms_home_srcimps m,
1896 unLoc i `notElem` mods_in_this_cycle ]
1898 warn :: Located ModuleName -> WarnMsg
1901 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1902 <+> quotes (ppr mod))
1904 -----------------------------------------------------------------------------
1905 -- Downsweep (dependency analysis)
1907 -- Chase downwards from the specified root set, returning summaries
1908 -- for all home modules encountered. Only follow source-import
1911 -- We pass in the previous collection of summaries, which is used as a
1912 -- cache to avoid recalculating a module summary if the source is
1915 -- The returned list of [ModSummary] nodes has one node for each home-package
1916 -- module, plus one for any hs-boot files. The imports of these nodes
1917 -- are all there, including the imports of non-home-package modules.
1919 downsweep :: GhcMonad m =>
1921 -> [ModSummary] -- Old summaries
1922 -> [ModuleName] -- Ignore dependencies on these; treat
1923 -- them as if they were package modules
1924 -> Bool -- True <=> allow multiple targets to have
1925 -- the same module name; this is
1926 -- very useful for ghc -M
1928 -- The elts of [ModSummary] all have distinct
1929 -- (Modules, IsBoot) identifiers, unless the Bool is true
1930 -- in which case there can be repeats
1931 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1932 = do -- catch error messages and return them
1933 --handleErrMsg -- should be covered by GhcMonad now
1934 -- (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1935 rootSummaries <- mapM getRootSummary roots
1936 let root_map = mkRootMap rootSummaries
1937 checkDuplicates root_map
1938 summs <- loop (concatMap msDeps rootSummaries) root_map
1941 roots = hsc_targets hsc_env
1943 old_summary_map :: NodeMap ModSummary
1944 old_summary_map = mkNodeMap old_summaries
1946 getRootSummary :: GhcMonad m => Target -> m ModSummary
1947 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1948 = do exists <- liftIO $ doesFileExist file
1950 then summariseFile hsc_env old_summaries file mb_phase
1951 obj_allowed maybe_buf
1952 else throwOneError $ mkPlainErrMsg noSrcSpan $
1953 text "can't find file:" <+> text file
1954 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1955 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1956 (L rootLoc modl) obj_allowed
1958 case maybe_summary of
1959 Nothing -> packageModErr modl
1962 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1964 -- In a root module, the filename is allowed to diverge from the module
1965 -- name, so we have to check that there aren't multiple root files
1966 -- defining the same module (otherwise the duplicates will be silently
1967 -- ignored, leading to confusing behaviour).
1968 checkDuplicates :: GhcMonad m => NodeMap [ModSummary] -> m ()
1969 checkDuplicates root_map
1970 | allow_dup_roots = return ()
1971 | null dup_roots = return ()
1972 | otherwise = liftIO $ multiRootsErr (head dup_roots)
1974 dup_roots :: [[ModSummary]] -- Each at least of length 2
1975 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1977 loop :: GhcMonad m =>
1978 [(Located ModuleName,IsBootInterface)]
1979 -- Work list: process these modules
1980 -> NodeMap [ModSummary]
1981 -- Visited set; the range is a list because
1982 -- the roots can have the same module names
1983 -- if allow_dup_roots is True
1985 -- The result includes the worklist, except
1986 -- for those mentioned in the visited set
1987 loop [] done = return (concat (nodeMapElts done))
1988 loop ((wanted_mod, is_boot) : ss) done
1989 | Just summs <- lookupFM done key
1990 = if isSingleton summs then
1993 do { liftIO $ multiRootsErr summs; return [] }
1995 = do mb_s <- summariseModule hsc_env old_summary_map
1996 is_boot wanted_mod True
1999 Nothing -> loop ss done
2000 Just s -> loop (msDeps s ++ ss) (addToFM done key [s])
2002 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
2004 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
2005 mkRootMap summaries = addListToFM_C (++) emptyFM
2006 [ (msKey s, [s]) | s <- summaries ]
2008 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
2009 -- (msDeps s) returns the dependencies of the ModSummary s.
2010 -- A wrinkle is that for a {-# SOURCE #-} import we return
2011 -- *both* the hs-boot file
2012 -- *and* the source file
2013 -- as "dependencies". That ensures that the list of all relevant
2014 -- modules always contains B.hs if it contains B.hs-boot.
2015 -- Remember, this pass isn't doing the topological sort. It's
2016 -- just gathering the list of all relevant ModSummaries
2018 concat [ [(m,True), (m,False)] | m <- ms_home_srcimps s ]
2019 ++ [ (m,False) | m <- ms_home_imps s ]
2021 home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName]
2022 home_imps imps = [ ideclName i | L _ i <- imps, isNothing (ideclPkgQual i) ]
2024 ms_home_allimps :: ModSummary -> [ModuleName]
2025 ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
2027 ms_home_srcimps :: ModSummary -> [Located ModuleName]
2028 ms_home_srcimps = home_imps . ms_srcimps
2030 ms_home_imps :: ModSummary -> [Located ModuleName]
2031 ms_home_imps = home_imps . ms_imps
2033 -----------------------------------------------------------------------------
2034 -- Summarising modules
2036 -- We have two types of summarisation:
2038 -- * Summarise a file. This is used for the root module(s) passed to
2039 -- cmLoadModules. The file is read, and used to determine the root
2040 -- module name. The module name may differ from the filename.
2042 -- * Summarise a module. We are given a module name, and must provide
2043 -- a summary. The finder is used to locate the file in which the module
2049 -> [ModSummary] -- old summaries
2050 -> FilePath -- source file name
2051 -> Maybe Phase -- start phase
2052 -> Bool -- object code allowed?
2053 -> Maybe (StringBuffer,ClockTime)
2056 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
2057 -- we can use a cached summary if one is available and the
2058 -- source file hasn't changed, But we have to look up the summary
2059 -- by source file, rather than module name as we do in summarise.
2060 | Just old_summary <- findSummaryBySourceFile old_summaries file
2062 let location = ms_location old_summary
2064 -- return the cached summary if the source didn't change
2065 src_timestamp <- case maybe_buf of
2066 Just (_,t) -> return t
2067 Nothing -> liftIO $ getModificationTime file
2068 -- The file exists; we checked in getRootSummary above.
2069 -- If it gets removed subsequently, then this
2070 -- getModificationTime may fail, but that's the right
2073 if ms_hs_date old_summary == src_timestamp
2074 then do -- update the object-file timestamp
2076 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2077 || obj_allowed -- bug #1205
2078 then liftIO $ getObjTimestamp location False
2080 return old_summary{ ms_obj_date = obj_timestamp }
2088 let dflags = hsc_dflags hsc_env
2090 (dflags', hspp_fn, buf)
2091 <- preprocessFile hsc_env file mb_phase maybe_buf
2093 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
2095 -- Make a ModLocation for this file
2096 location <- liftIO $ mkHomeModLocation dflags mod_name file
2098 -- Tell the Finder cache where it is, so that subsequent calls
2099 -- to findModule will find it, even if it's not on any search path
2100 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
2102 src_timestamp <- case maybe_buf of
2103 Just (_,t) -> return t
2104 Nothing -> liftIO $ getModificationTime file
2105 -- getMofificationTime may fail
2107 -- when the user asks to load a source file by name, we only
2108 -- use an object file if -fobject-code is on. See #1205.
2110 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2111 || obj_allowed -- bug #1205
2112 then liftIO $ modificationTimeIfExists (ml_obj_file location)
2115 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
2116 ms_location = location,
2117 ms_hspp_file = hspp_fn,
2118 ms_hspp_opts = dflags',
2119 ms_hspp_buf = Just buf,
2120 ms_srcimps = srcimps, ms_imps = the_imps,
2121 ms_hs_date = src_timestamp,
2122 ms_obj_date = obj_timestamp })
2124 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
2125 findSummaryBySourceFile summaries file
2126 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
2127 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
2131 -- Summarise a module, and pick up source and timestamp.
2135 -> NodeMap ModSummary -- Map of old summaries
2136 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
2137 -> Located ModuleName -- Imported module to be summarised
2138 -> Bool -- object code allowed?
2139 -> Maybe (StringBuffer, ClockTime)
2140 -> [ModuleName] -- Modules to exclude
2141 -> m (Maybe ModSummary) -- Its new summary
2143 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
2144 obj_allowed maybe_buf excl_mods
2145 | wanted_mod `elem` excl_mods
2148 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
2149 = do -- Find its new timestamp; all the
2150 -- ModSummaries in the old map have valid ml_hs_files
2151 let location = ms_location old_summary
2152 src_fn = expectJust "summariseModule" (ml_hs_file location)
2154 -- check the modification time on the source file, and
2155 -- return the cached summary if it hasn't changed. If the
2156 -- file has disappeared, we need to call the Finder again.
2158 Just (_,t) -> check_timestamp old_summary location src_fn t
2160 m <- liftIO $ System.IO.Error.try (getModificationTime src_fn)
2162 Right t -> check_timestamp old_summary location src_fn t
2163 Left e | isDoesNotExistError e -> find_it
2164 | otherwise -> liftIO $ ioError e
2166 | otherwise = find_it
2168 dflags = hsc_dflags hsc_env
2170 hsc_src = if is_boot then HsBootFile else HsSrcFile
2172 check_timestamp old_summary location src_fn src_timestamp
2173 | ms_hs_date old_summary == src_timestamp = do
2174 -- update the object-file timestamp
2175 obj_timestamp <- liftIO $
2176 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2177 || obj_allowed -- bug #1205
2178 then getObjTimestamp location is_boot
2180 return (Just old_summary{ ms_obj_date = obj_timestamp })
2182 -- source changed: re-summarise.
2183 new_summary location (ms_mod old_summary) src_fn src_timestamp
2186 -- Don't use the Finder's cache this time. If the module was
2187 -- previously a package module, it may have now appeared on the
2188 -- search path, so we want to consider it to be a home module. If
2189 -- the module was previously a home module, it may have moved.
2190 liftIO $ uncacheModule hsc_env wanted_mod
2191 found <- liftIO $ findImportedModule hsc_env wanted_mod Nothing
2194 | isJust (ml_hs_file location) ->
2196 just_found location mod
2198 -- Drop external-pkg
2199 ASSERT(modulePackageId mod /= thisPackage dflags)
2202 err -> liftIO $ noModError dflags loc wanted_mod err
2205 just_found location mod = do
2206 -- Adjust location to point to the hs-boot source file,
2207 -- hi file, object file, when is_boot says so
2208 let location' | is_boot = addBootSuffixLocn location
2209 | otherwise = location
2210 src_fn = expectJust "summarise2" (ml_hs_file location')
2212 -- Check that it exists
2213 -- It might have been deleted since the Finder last found it
2214 maybe_t <- liftIO $ modificationTimeIfExists src_fn
2216 Nothing -> noHsFileErr loc src_fn
2217 Just t -> new_summary location' mod src_fn t
2220 new_summary location mod src_fn src_timestamp
2222 -- Preprocess the source file and get its imports
2223 -- The dflags' contains the OPTIONS pragmas
2224 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
2225 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
2227 when (mod_name /= wanted_mod) $
2228 throwOneError $ mkPlainErrMsg mod_loc $
2229 text "File name does not match module name:"
2230 $$ text "Saw:" <+> quotes (ppr mod_name)
2231 $$ text "Expected:" <+> quotes (ppr wanted_mod)
2233 -- Find the object timestamp, and return the summary
2234 obj_timestamp <- liftIO $
2235 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
2236 || obj_allowed -- bug #1205
2237 then getObjTimestamp location is_boot
2240 return (Just (ModSummary { ms_mod = mod,
2241 ms_hsc_src = hsc_src,
2242 ms_location = location,
2243 ms_hspp_file = hspp_fn,
2244 ms_hspp_opts = dflags',
2245 ms_hspp_buf = Just buf,
2246 ms_srcimps = srcimps,
2248 ms_hs_date = src_timestamp,
2249 ms_obj_date = obj_timestamp }))
2252 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
2253 getObjTimestamp location is_boot
2254 = if is_boot then return Nothing
2255 else modificationTimeIfExists (ml_obj_file location)
2258 preprocessFile :: GhcMonad m =>
2261 -> Maybe Phase -- ^ Starting phase
2262 -> Maybe (StringBuffer,ClockTime)
2263 -> m (DynFlags, FilePath, StringBuffer)
2264 preprocessFile hsc_env src_fn mb_phase Nothing
2266 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
2267 buf <- liftIO $ hGetStringBuffer hspp_fn
2268 return (dflags', hspp_fn, buf)
2270 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
2272 let dflags = hsc_dflags hsc_env
2273 -- case we bypass the preprocessing stage?
2275 local_opts = getOptions dflags buf src_fn
2277 (dflags', leftovers, warns)
2278 <- parseDynamicNoPackageFlags dflags local_opts
2279 checkProcessArgsResult leftovers
2280 handleFlagWarnings dflags' warns
2284 | Just (Unlit _) <- mb_phase = True
2285 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2286 -- note: local_opts is only required if there's no Unlit phase
2287 | dopt Opt_Cpp dflags' = True
2288 | dopt Opt_Pp dflags' = True
2291 when needs_preprocessing $
2292 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2294 return (dflags', src_fn, buf)
2297 -----------------------------------------------------------------------------
2299 -----------------------------------------------------------------------------
2301 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2302 -- ToDo: we don't have a proper line number for this error
2303 noModError dflags loc wanted_mod err
2304 = throwOneError $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2306 noHsFileErr :: GhcMonad m => SrcSpan -> String -> m a
2307 noHsFileErr loc path
2308 = throwOneError $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2310 packageModErr :: GhcMonad m => ModuleName -> m a
2312 = throwOneError $ mkPlainErrMsg noSrcSpan $
2313 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2315 multiRootsErr :: [ModSummary] -> IO ()
2316 multiRootsErr [] = panic "multiRootsErr"
2317 multiRootsErr summs@(summ1:_)
2318 = throwOneError $ mkPlainErrMsg noSrcSpan $
2319 text "module" <+> quotes (ppr mod) <+>
2320 text "is defined in multiple files:" <+>
2321 sep (map text files)
2324 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2326 cyclicModuleErr :: [ModSummary] -> SDoc
2328 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2329 2 (vcat (map show_one ms))
2331 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2332 nest 2 $ ptext (sLit "imports:") <+>
2333 (pp_imps HsBootFile (ms_srcimps ms)
2334 $$ pp_imps HsSrcFile (ms_imps ms))]
2335 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2336 pp_imps src mods = fsep (map (show_mod src) mods)
2339 -- | Inform GHC that the working directory has changed. GHC will flush
2340 -- its cache of module locations, since it may no longer be valid.
2341 -- Note: if you change the working directory, you should also unload
2342 -- the current program (set targets to empty, followed by load).
2343 workingDirectoryChanged :: GhcMonad m => m ()
2344 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
2346 -- -----------------------------------------------------------------------------
2347 -- inspecting the session
2349 -- | Get the module dependency graph.
2350 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
2351 getModuleGraph = liftM hsc_mod_graph getSession
2353 -- | Determines whether a set of modules requires Template Haskell.
2355 -- Note that if the session's 'DynFlags' enabled Template Haskell when
2356 -- 'depanal' was called, then each module in the returned module graph will
2357 -- have Template Haskell enabled whether it is actually needed or not.
2358 needsTemplateHaskell :: ModuleGraph -> Bool
2359 needsTemplateHaskell ms =
2360 any (dopt Opt_TemplateHaskell . ms_hspp_opts) ms
2362 -- | Return @True@ <==> module is loaded.
2363 isLoaded :: GhcMonad m => ModuleName -> m Bool
2364 isLoaded m = withSession $ \hsc_env ->
2365 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2367 -- | Return the bindings for the current interactive session.
2368 getBindings :: GhcMonad m => m [TyThing]
2369 getBindings = withSession $ \hsc_env ->
2370 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2371 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2373 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2374 filtered = foldr f (const []) tmp_ids emptyUniqSet
2376 | uniq `elementOfUniqSet` set = rest set
2377 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2378 where uniq = getUnique (nameOccName (idName id))
2382 getPrintUnqual :: GhcMonad m => m PrintUnqualified
2383 getPrintUnqual = withSession $ \hsc_env ->
2384 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2386 -- | Container for information about a 'Module'.
2387 data ModuleInfo = ModuleInfo {
2388 minf_type_env :: TypeEnv,
2389 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2390 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2391 minf_instances :: [Instance]
2393 ,minf_modBreaks :: ModBreaks
2395 -- ToDo: this should really contain the ModIface too
2397 -- We don't want HomeModInfo here, because a ModuleInfo applies
2398 -- to package modules too.
2400 -- | Request information about a loaded 'Module'
2401 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
2402 getModuleInfo mdl = withSession $ \hsc_env -> do
2403 let mg = hsc_mod_graph hsc_env
2404 if mdl `elem` map ms_mod mg
2405 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
2407 {- if isHomeModule (hsc_dflags hsc_env) mdl
2409 else -} liftIO $ getPackageModuleInfo hsc_env mdl
2410 -- getPackageModuleInfo will attempt to find the interface, so
2411 -- we don't want to call it for a home module, just in case there
2412 -- was a problem loading the module and the interface doesn't
2413 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2415 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2417 getPackageModuleInfo hsc_env mdl = do
2418 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2420 Nothing -> return Nothing
2422 eps <- readIORef (hsc_EPS hsc_env)
2424 names = availsToNameSet avails
2426 tys = [ ty | name <- concatMap availNames avails,
2427 Just ty <- [lookupTypeEnv pte name] ]
2429 return (Just (ModuleInfo {
2430 minf_type_env = mkTypeEnv tys,
2431 minf_exports = names,
2432 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2433 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2434 minf_modBreaks = emptyModBreaks
2437 getPackageModuleInfo _hsc_env _mdl = do
2438 -- bogusly different for non-GHCI (ToDo)
2442 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2443 getHomeModuleInfo hsc_env mdl =
2444 case lookupUFM (hsc_HPT hsc_env) mdl of
2445 Nothing -> return Nothing
2447 let details = hm_details hmi
2448 return (Just (ModuleInfo {
2449 minf_type_env = md_types details,
2450 minf_exports = availsToNameSet (md_exports details),
2451 minf_rdr_env = mi_globals $! hm_iface hmi,
2452 minf_instances = md_insts details
2454 ,minf_modBreaks = getModBreaks hmi
2458 -- | The list of top-level entities defined in a module
2459 modInfoTyThings :: ModuleInfo -> [TyThing]
2460 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2462 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2463 modInfoTopLevelScope minf
2464 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2466 modInfoExports :: ModuleInfo -> [Name]
2467 modInfoExports minf = nameSetToList $! minf_exports minf
2469 -- | Returns the instances defined by the specified module.
2470 -- Warning: currently unimplemented for package modules.
2471 modInfoInstances :: ModuleInfo -> [Instance]
2472 modInfoInstances = minf_instances
2474 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2475 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2477 mkPrintUnqualifiedForModule :: GhcMonad m =>
2479 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
2480 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
2481 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2483 modInfoLookupName :: GhcMonad m =>
2485 -> m (Maybe TyThing) -- XXX: returns a Maybe X
2486 modInfoLookupName minf name = withSession $ \hsc_env -> do
2487 case lookupTypeEnv (minf_type_env minf) name of
2488 Just tyThing -> return (Just tyThing)
2490 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
2491 return $! lookupType (hsc_dflags hsc_env)
2492 (hsc_HPT hsc_env) (eps_PTE eps) name
2495 modInfoModBreaks :: ModuleInfo -> ModBreaks
2496 modInfoModBreaks = minf_modBreaks
2499 isDictonaryId :: Id -> Bool
2501 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2503 -- | Looks up a global name: that is, any top-level name in any
2504 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2505 -- the interactive context, and therefore does not require a preceding
2507 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
2508 lookupGlobalName name = withSession $ \hsc_env -> do
2509 liftIO $ lookupTypeHscEnv hsc_env name
2511 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
2512 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
2513 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
2514 return (findAnns deserialize ann_env target)
2517 -- | get the GlobalRdrEnv for a session
2518 getGRE :: GhcMonad m => m GlobalRdrEnv
2519 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2522 -- -----------------------------------------------------------------------------
2524 -- | Return all /external/ modules available in the package database.
2525 -- Modules from the current session (i.e., from the 'HomePackageTable') are
2527 packageDbModules :: GhcMonad m =>
2528 Bool -- ^ Only consider exposed packages.
2530 packageDbModules only_exposed = do
2531 dflags <- getSessionDynFlags
2532 let pkgs = UFM.eltsUFM (pkgIdMap (pkgState dflags))
2534 [ mkModule pid modname | p <- pkgs
2535 , not only_exposed || exposed p
2536 , pid <- [mkPackageId (package p)]
2537 , modname <- exposedModules p ]
2539 -- -----------------------------------------------------------------------------
2540 -- Misc exported utils
2542 dataConType :: DataCon -> Type
2543 dataConType dc = idType (dataConWrapId dc)
2545 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2546 pprParenSymName :: NamedThing a => a -> SDoc
2547 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2549 -- ----------------------------------------------------------------------------
2554 -- - Data and Typeable instances for HsSyn.
2556 -- ToDo: check for small transformations that happen to the syntax in
2557 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2559 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2560 -- to get from TyCons, Ids etc. to TH syntax (reify).
2562 -- :browse will use either lm_toplev or inspect lm_interface, depending
2563 -- on whether the module is interpreted or not.
2567 -- Extract the filename, stringbuffer content and dynflags associed to a module
2569 -- XXX: Explain pre-conditions
2570 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
2571 getModuleSourceAndFlags mod = do
2572 m <- getModSummary (moduleName mod)
2573 case ml_hs_file $ ms_location m of
2574 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
2575 Just sourceFile -> do
2576 source <- liftIO $ hGetStringBuffer sourceFile
2577 return (sourceFile, source, ms_hspp_opts m)
2580 -- | Return module source as token stream, including comments.
2582 -- The module must be in the module graph and its source must be available.
2583 -- Throws a 'HscTypes.SourceError' on parse error.
2584 getTokenStream :: GhcMonad m => Module -> m [Located Token]
2585 getTokenStream mod = do
2586 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2587 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2588 case lexTokenStream source startLoc flags of
2589 POk _ ts -> return ts
2590 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2592 -- | Give even more information on the source than 'getTokenStream'
2593 -- This function allows reconstructing the source completely with
2594 -- 'showRichTokenStream'.
2595 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
2596 getRichTokenStream mod = do
2597 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
2598 let startLoc = mkSrcLoc (mkFastString sourceFile) 0 0
2599 case lexTokenStream source startLoc flags of
2600 POk _ ts -> return $ addSourceToTokens startLoc source ts
2601 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
2603 -- | Given a source location and a StringBuffer corresponding to this
2604 -- location, return a rich token stream with the source associated to the
2606 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
2607 -> [(Located Token, String)]
2608 addSourceToTokens _ _ [] = []
2609 addSourceToTokens loc buf (t@(L span _) : ts)
2610 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
2611 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
2613 (newLoc, newBuf, str) = go "" loc buf
2614 start = srcSpanStart span
2615 end = srcSpanEnd span
2616 go acc loc buf | loc < start = go acc nLoc nBuf
2617 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
2618 | otherwise = (loc, buf, reverse acc)
2619 where (ch, nBuf) = nextChar buf
2620 nLoc = advanceSrcLoc loc ch
2623 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
2624 -- return source code almost identical to the original code (except for
2625 -- insignificant whitespace.)
2626 showRichTokenStream :: [(Located Token, String)] -> String
2627 showRichTokenStream ts = go startLoc ts ""
2628 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
2629 startLoc = mkSrcLoc sourceFile 0 0
2631 go loc ((L span _, str):ts)
2632 | not (isGoodSrcSpan span) = go loc ts
2633 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
2636 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
2637 . ((replicate tokCol ' ') ++)
2640 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
2641 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
2642 tokEnd = srcSpanEnd span
2644 -- -----------------------------------------------------------------------------
2645 -- Interactive evaluation
2647 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2648 -- filesystem and package database to find the corresponding 'Module',
2649 -- using the algorithm that is used for an @import@ declaration.
2650 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
2651 findModule mod_name maybe_pkg = withSession $ \hsc_env -> liftIO $ -- XXX
2653 dflags = hsc_dflags hsc_env
2654 hpt = hsc_HPT hsc_env
2655 this_pkg = thisPackage dflags
2657 case lookupUFM hpt mod_name of
2658 Just mod_info -> return (mi_module (hm_iface mod_info))
2659 _not_a_home_module -> do
2660 res <- findImportedModule hsc_env mod_name maybe_pkg
2662 Found _ m | modulePackageId m /= this_pkg -> return m
2663 | otherwise -> ghcError (CmdLineError (showSDoc $
2664 text "module" <+> quotes (ppr (moduleName m)) <+>
2665 text "is not loaded"))
2666 err -> let msg = cannotFindModule dflags mod_name err in
2667 ghcError (CmdLineError (showSDoc msg))
2670 getHistorySpan :: GhcMonad m => History -> m SrcSpan
2671 getHistorySpan h = withSession $ \hsc_env ->
2672 return$ InteractiveEval.getHistorySpan hsc_env h
2674 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
2675 obtainTermFromVal bound force ty a =
2676 withSession $ \hsc_env ->
2677 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
2679 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
2680 obtainTermFromId bound force id =
2681 withSession $ \hsc_env ->
2682 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id