1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18 GhcMode(..), GhcLink(..), defaultObjectTarget,
25 Target(..), TargetId(..), Phase,
32 -- * Extending the program scope
33 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
34 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
35 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
36 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
38 -- * Loading\/compiling the program
40 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
41 workingDirectoryChanged,
42 checkModule, checkAndLoadModule, CheckedModule(..),
43 TypecheckedSource, ParsedSource, RenamedSource,
44 compileToCore, compileToCoreModule, compileToCoreSimplified,
47 -- * Parsing Haddock comments
50 -- * Inspecting the module structure of the program
51 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
56 -- * Inspecting modules
63 modInfoIsExportedName,
66 mkPrintUnqualifiedForModule,
69 PrintUnqualified, alwaysQualify,
71 -- * Interactive evaluation
72 getBindings, getPrintUnqual,
75 setContext, getContext,
85 runStmt, SingleStep(..),
87 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
88 resumeHistory, resumeHistoryIx),
89 History(historyBreakInfo, historyEnclosingDecl),
90 GHC.getHistorySpan, getHistoryModule,
94 InteractiveEval.forward,
97 InteractiveEval.compileExpr, HValue, dynCompileExpr,
99 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
101 ModBreaks(..), BreakIndex,
102 BreakInfo(breakInfo_number, breakInfo_module),
103 BreakArray, setBreakOn, setBreakOff, getBreak,
106 -- * Abstract syntax elements
112 Module, mkModule, pprModule, moduleName, modulePackageId,
113 ModuleName, mkModuleName, moduleNameString,
117 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
119 RdrName(Qual,Unqual),
123 isImplicitId, isDeadBinder,
124 isExportedId, isLocalId, isGlobalId,
126 isPrimOpId, isFCallId, isClassOpId_maybe,
127 isDataConWorkId, idDataCon,
128 isBottomingId, isDictonaryId,
129 recordSelectorFieldLabel,
131 -- ** Type constructors
133 tyConTyVars, tyConDataCons, tyConArity,
134 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
136 synTyConDefn, synTyConType, synTyConResKind,
142 -- ** Data constructors
144 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
145 dataConIsInfix, isVanillaDataCon,
147 StrictnessMark(..), isMarkedStrict,
151 classMethods, classSCTheta, classTvsFds,
156 instanceDFunId, pprInstance, pprInstanceHdr,
158 -- ** Types and Kinds
159 Type, splitForAllTys, funResultTy,
160 pprParendType, pprTypeApp,
163 ThetaType, pprThetaArrow,
169 module HsSyn, -- ToDo: remove extraneous bits
173 defaultFixity, maxPrecedence,
177 -- ** Source locations
179 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
180 srcLocFile, srcLocLine, srcLocCol,
182 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
183 srcSpanStart, srcSpanEnd,
185 srcSpanStartLine, srcSpanEndLine,
186 srcSpanStartCol, srcSpanEndCol,
189 GhcException(..), showGhcException,
199 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
200 * what StaticFlags should we expose, if any?
203 #include "HsVersions.h"
206 import qualified Linker
207 import Linker ( HValue )
211 import InteractiveEval
216 import TcRnTypes hiding (LIE)
217 import TcRnMonad ( initIfaceCheck )
221 import qualified HsSyn -- hack as we want to reexport the whole module
222 import HsSyn hiding ((<.>))
223 import Type hiding (typeKind)
224 import TcType hiding (typeKind)
226 import Var hiding (setIdType)
227 import TysPrim ( alphaTyVars )
232 import Name hiding ( varName )
233 import OccName ( parenSymOcc )
234 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
236 import FamInstEnv ( emptyFamInstEnv )
240 import DriverPipeline
241 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
248 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
257 import Bag ( unitBag, listToBag )
260 import StringBuffer ( StringBuffer, hGetStringBuffer )
263 import Maybes ( expectJust, mapCatMaybes )
265 import HaddockLex ( tokenise )
268 import Control.Concurrent
269 import System.Directory ( getModificationTime, doesFileExist,
270 getCurrentDirectory )
273 import qualified Data.List as List
275 import System.Exit ( exitWith, ExitCode(..) )
276 import System.Time ( ClockTime, getClockTime )
279 import System.FilePath
281 import System.IO.Error ( try, isDoesNotExistError )
282 #if __GLASGOW_HASKELL__ >= 609
283 import Data.Typeable (cast)
285 import Prelude hiding (init)
288 -- -----------------------------------------------------------------------------
289 -- Exception handlers
291 -- | Install some default exception handlers and run the inner computation.
292 -- Unless you want to handle exceptions yourself, you should wrap this around
293 -- the top level of your program. The default handlers output the error
294 -- message(s) to stderr and exit cleanly.
295 defaultErrorHandler :: DynFlags -> IO a -> IO a
296 defaultErrorHandler dflags inner =
297 -- top-level exception handler: any unrecognised exception is a compiler bug.
298 #if __GLASGOW_HASKELL__ < 609
299 handle (\exception -> do
302 -- an IO exception probably isn't our fault, so don't panic
304 fatalErrorMsg dflags (text (show exception))
305 AsyncException StackOverflow ->
306 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
307 ExitException _ -> throw exception
309 fatalErrorMsg dflags (text (show (Panic (show exception))))
310 exitWith (ExitFailure 1)
313 handle (\(SomeException exception) -> do
315 case cast exception of
316 -- an IO exception probably isn't our fault, so don't panic
317 Just (ioe :: IOException) ->
318 fatalErrorMsg dflags (text (show ioe))
319 _ -> case cast exception of
320 Just StackOverflow ->
321 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
322 _ -> case cast exception of
323 Just (ex :: ExitCode) -> throw ex
326 (text (show (Panic (show exception))))
327 exitWith (ExitFailure 1)
331 -- program errors: messages with locations attached. Sometimes it is
332 -- convenient to just throw these as exceptions.
334 (\em -> do printBagOfErrors dflags (unitBag em)
335 exitWith (ExitFailure 1)) $
337 -- error messages propagated as exceptions
342 PhaseFailed _ code -> exitWith code
343 Interrupted -> exitWith (ExitFailure 1)
344 _ -> do fatalErrorMsg dflags (text (show ge))
345 exitWith (ExitFailure 1)
349 -- | Install a default cleanup handler to remove temporary files
350 -- deposited by a GHC run. This is seperate from
351 -- 'defaultErrorHandler', because you might want to override the error
352 -- handling, but still get the ordinary cleanup behaviour.
353 defaultCleanupHandler :: DynFlags -> IO a -> IO a
354 defaultCleanupHandler dflags inner =
355 -- make sure we clean up after ourselves
357 (do cleanTempFiles dflags
360 -- exceptions will be blocked while we clean the temporary files,
361 -- so there shouldn't be any difficulty if we receive further
365 -- | Starts a new session. A session consists of a set of loaded
366 -- modules, a set of options (DynFlags), and an interactive context.
367 -- ToDo: explain argument [[mb_top_dir]]
368 newSession :: Maybe FilePath -> IO Session
369 newSession mb_top_dir = do
371 main_thread <- myThreadId
372 modifyMVar_ interruptTargetThread (return . (main_thread :))
373 installSignalHandlers
376 dflags0 <- initDynFlags defaultDynFlags
377 dflags <- initSysTools mb_top_dir dflags0
378 env <- newHscEnv dflags
382 -- tmp: this breaks the abstraction, but required because DriverMkDepend
383 -- needs to call the Finder. ToDo: untangle this.
384 sessionHscEnv :: Session -> IO HscEnv
385 sessionHscEnv (Session ref) = readIORef ref
387 -- -----------------------------------------------------------------------------
390 -- | Grabs the DynFlags from the Session
391 getSessionDynFlags :: Session -> IO DynFlags
392 getSessionDynFlags s = withSession s (return . hsc_dflags)
394 -- | Updates the DynFlags in a Session. This also reads
395 -- the package database (unless it has already been read),
396 -- and prepares the compilers knowledge about packages. It
397 -- can be called again to load new packages: just add new
398 -- package flags to (packageFlags dflags).
400 -- Returns a list of new packages that may need to be linked in using
401 -- the dynamic linker (see 'linkPackages') as a result of new package
402 -- flags. If you are not doing linking or doing static linking, you
403 -- can ignore the list of packages returned.
405 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
406 setSessionDynFlags (Session ref) dflags = do
407 hsc_env <- readIORef ref
408 (dflags', preload) <- initPackages dflags
409 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
412 -- | If there is no -o option, guess the name of target executable
413 -- by using top-level source file name as a base.
414 guessOutputFile :: Session -> IO ()
415 guessOutputFile s = modifySession s $ \env ->
416 let dflags = hsc_dflags env
417 mod_graph = hsc_mod_graph env
418 mainModuleSrcPath :: Maybe String
419 mainModuleSrcPath = do
420 let isMain = (== mainModIs dflags) . ms_mod
421 [ms] <- return (filter isMain mod_graph)
422 ml_hs_file (ms_location ms)
423 name = fmap dropExtension mainModuleSrcPath
425 #if defined(mingw32_HOST_OS)
426 -- we must add the .exe extention unconditionally here, otherwise
427 -- when name has an extension of its own, the .exe extension will
428 -- not be added by DriverPipeline.exeFileName. See #2248
429 name_exe = fmap (<.> "exe") name
434 case outputFile dflags of
436 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
438 -- -----------------------------------------------------------------------------
441 -- ToDo: think about relative vs. absolute file paths. And what
442 -- happens when the current directory changes.
444 -- | Sets the targets for this session. Each target may be a module name
445 -- or a filename. The targets correspond to the set of root modules for
446 -- the program\/library. Unloading the current program is achieved by
447 -- setting the current set of targets to be empty, followed by load.
448 setTargets :: Session -> [Target] -> IO ()
449 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
451 -- | returns the current set of targets
452 getTargets :: Session -> IO [Target]
453 getTargets s = withSession s (return . hsc_targets)
455 -- | Add another target
456 addTarget :: Session -> Target -> IO ()
458 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
461 removeTarget :: Session -> TargetId -> IO ()
462 removeTarget s target_id
463 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
465 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
467 -- Attempts to guess what Target a string refers to. This function implements
468 -- the --make/GHCi command-line syntax for filenames:
470 -- - if the string looks like a Haskell source filename, then interpret
472 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
474 -- - otherwise interpret the string as a module name
476 guessTarget :: String -> Maybe Phase -> IO Target
477 guessTarget file (Just phase)
478 = return (Target (TargetFile file (Just phase)) Nothing)
479 guessTarget file Nothing
480 | isHaskellSrcFilename file
481 = return (Target (TargetFile file Nothing) Nothing)
482 | looksLikeModuleName file
483 = return (Target (TargetModule (mkModuleName file)) Nothing)
485 = do exists <- doesFileExist hs_file
487 then return (Target (TargetFile hs_file Nothing) Nothing)
489 exists <- doesFileExist lhs_file
491 then return (Target (TargetFile lhs_file Nothing) Nothing)
494 (ProgramError (showSDoc $
495 text "target" <+> quotes (text file) <+>
496 text "is not a module name or a source file"))
498 hs_file = file <.> "hs"
499 lhs_file = file <.> "lhs"
501 -- -----------------------------------------------------------------------------
502 -- Extending the program scope
504 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
505 extendGlobalRdrScope session rdrElts
506 = modifySession session $ \hscEnv ->
507 let global_rdr = hsc_global_rdr_env hscEnv
508 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
510 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
511 setGlobalRdrScope session rdrElts
512 = modifySession session $ \hscEnv ->
513 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
515 extendGlobalTypeScope :: Session -> [Id] -> IO ()
516 extendGlobalTypeScope session ids
517 = modifySession session $ \hscEnv ->
518 let global_type = hsc_global_type_env hscEnv
519 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
521 setGlobalTypeScope :: Session -> [Id] -> IO ()
522 setGlobalTypeScope session ids
523 = modifySession session $ \hscEnv ->
524 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
526 -- -----------------------------------------------------------------------------
527 -- Parsing Haddock comments
529 parseHaddockComment :: String -> Either String (HsDoc RdrName)
530 parseHaddockComment string =
531 case parseHaddockParagraphs (tokenise string) of
535 -- -----------------------------------------------------------------------------
536 -- Loading the program
538 -- Perform a dependency analysis starting from the current targets
539 -- and update the session with the new module graph.
540 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
541 depanal (Session ref) excluded_mods allow_dup_roots = do
542 hsc_env <- readIORef ref
544 dflags = hsc_dflags hsc_env
545 targets = hsc_targets hsc_env
546 old_graph = hsc_mod_graph hsc_env
548 showPass dflags "Chasing dependencies"
549 debugTraceMsg dflags 2 (hcat [
550 text "Chasing modules from: ",
551 hcat (punctuate comma (map pprTarget targets))])
553 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
555 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
560 -- | The result of load.
562 = LoadOk Errors -- ^ all specified targets were loaded successfully.
563 | LoadFailed Errors -- ^ not all modules were loaded.
565 type Errors = [String]
567 data ErrMsg = ErrMsg {
568 errMsgSeverity :: Severity, -- warning, error, etc.
569 errMsgSpans :: [SrcSpan],
570 errMsgShortDoc :: Doc,
571 errMsgExtraInfo :: Doc
577 | LoadUpTo ModuleName
578 | LoadDependenciesOf ModuleName
580 -- | Try to load the program. If a Module is supplied, then just
581 -- attempt to load up to this target. If no Module is supplied,
582 -- then try to load all targets.
583 load :: Session -> LoadHowMuch -> IO SuccessFlag
586 -- Dependency analysis first. Note that this fixes the module graph:
587 -- even if we don't get a fully successful upsweep, the full module
588 -- graph is still retained in the Session. We can tell which modules
589 -- were successfully loaded by inspecting the Session's HPT.
590 mb_graph <- depanal s [] False
592 Just mod_graph -> load2 s how_much mod_graph
593 Nothing -> return Failed
595 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
596 load2 s@(Session ref) how_much mod_graph = do
598 hsc_env <- readIORef ref
600 let hpt1 = hsc_HPT hsc_env
601 let dflags = hsc_dflags hsc_env
603 -- The "bad" boot modules are the ones for which we have
604 -- B.hs-boot in the module graph, but no B.hs
605 -- The downsweep should have ensured this does not happen
607 let all_home_mods = [ms_mod_name s
608 | s <- mod_graph, not (isBootSummary s)]
609 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
610 not (ms_mod_name s `elem` all_home_mods)]
611 ASSERT( null bad_boot_mods ) return ()
613 -- check that the module given in HowMuch actually exists, otherwise
614 -- topSortModuleGraph will bomb later.
615 let checkHowMuch (LoadUpTo m) = checkMod m
616 checkHowMuch (LoadDependenciesOf m) = checkMod m
620 | m `elem` all_home_mods = and_then
622 errorMsg dflags (text "no such module:" <+>
626 checkHowMuch how_much $ do
628 -- mg2_with_srcimps drops the hi-boot nodes, returning a
629 -- graph with cycles. Among other things, it is used for
630 -- backing out partially complete cycles following a failed
631 -- upsweep, and for removing from hpt all the modules
632 -- not in strict downwards closure, during calls to compile.
633 let mg2_with_srcimps :: [SCC ModSummary]
634 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
636 -- If we can determine that any of the {-# SOURCE #-} imports
637 -- are definitely unnecessary, then emit a warning.
638 warnUnnecessarySourceImports dflags mg2_with_srcimps
641 -- check the stability property for each module.
642 stable_mods@(stable_obj,stable_bco)
643 = checkStability hpt1 mg2_with_srcimps all_home_mods
645 -- prune bits of the HPT which are definitely redundant now,
647 pruned_hpt = pruneHomePackageTable hpt1
648 (flattenSCCs mg2_with_srcimps)
653 -- before we unload anything, make sure we don't leave an old
654 -- interactive context around pointing to dead bindings. Also,
655 -- write the pruned HPT to allow the old HPT to be GC'd.
656 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext,
657 hsc_HPT = pruned_hpt }
659 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
660 text "Stable BCO:" <+> ppr stable_bco)
662 -- Unload any modules which are going to be re-linked this time around.
663 let stable_linkables = [ linkable
664 | m <- stable_obj++stable_bco,
665 Just hmi <- [lookupUFM pruned_hpt m],
666 Just linkable <- [hm_linkable hmi] ]
667 unload hsc_env stable_linkables
669 -- We could at this point detect cycles which aren't broken by
670 -- a source-import, and complain immediately, but it seems better
671 -- to let upsweep_mods do this, so at least some useful work gets
672 -- done before the upsweep is abandoned.
673 --hPutStrLn stderr "after tsort:\n"
674 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
676 -- Now do the upsweep, calling compile for each module in
677 -- turn. Final result is version 3 of everything.
679 -- Topologically sort the module graph, this time including hi-boot
680 -- nodes, and possibly just including the portion of the graph
681 -- reachable from the module specified in the 2nd argument to load.
682 -- This graph should be cycle-free.
683 -- If we're restricting the upsweep to a portion of the graph, we
684 -- also want to retain everything that is still stable.
685 let full_mg :: [SCC ModSummary]
686 full_mg = topSortModuleGraph False mod_graph Nothing
688 maybe_top_mod = case how_much of
690 LoadDependenciesOf m -> Just m
693 partial_mg0 :: [SCC ModSummary]
694 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
696 -- LoadDependenciesOf m: we want the upsweep to stop just
697 -- short of the specified module (unless the specified module
700 | LoadDependenciesOf _mod <- how_much
701 = ASSERT( case last partial_mg0 of
702 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
703 List.init partial_mg0
709 | AcyclicSCC ms <- full_mg,
710 ms_mod_name ms `elem` stable_obj++stable_bco,
711 ms_mod_name ms `notElem` [ ms_mod_name ms' |
712 AcyclicSCC ms' <- partial_mg ] ]
714 mg = stable_mg ++ partial_mg
716 -- clean up between compilations
717 let cleanup = cleanTempFilesExcept dflags
718 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
720 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
722 (upsweep_ok, hsc_env1, modsUpswept)
723 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
724 pruned_hpt stable_mods cleanup mg
726 -- Make modsDone be the summaries for each home module now
727 -- available; this should equal the domain of hpt3.
728 -- Get in in a roughly top .. bottom order (hence reverse).
730 let modsDone = reverse modsUpswept
732 -- Try and do linking in some form, depending on whether the
733 -- upsweep was completely or only partially successful.
735 if succeeded upsweep_ok
738 -- Easy; just relink it all.
739 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
741 -- Clean up after ourselves
742 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
744 -- Issue a warning for the confusing case where the user
745 -- said '-o foo' but we're not going to do any linking.
746 -- We attempt linking if either (a) one of the modules is
747 -- called Main, or (b) the user said -no-hs-main, indicating
748 -- that main() is going to come from somewhere else.
750 let ofile = outputFile dflags
751 let no_hs_main = dopt Opt_NoHsMain dflags
753 main_mod = mainModIs dflags
754 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
755 do_linking = a_root_is_Main || no_hs_main
757 when (ghcLink dflags == LinkBinary
758 && isJust ofile && not do_linking) $
759 debugTraceMsg dflags 1 $
760 text ("Warning: output was redirected with -o, " ++
761 "but no output will be generated\n" ++
762 "because there is no " ++
763 moduleNameString (moduleName main_mod) ++ " module.")
765 -- link everything together
766 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
768 loadFinish Succeeded linkresult ref hsc_env1
771 -- Tricky. We need to back out the effects of compiling any
772 -- half-done cycles, both so as to clean up the top level envs
773 -- and to avoid telling the interactive linker to link them.
774 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
777 = map ms_mod modsDone
778 let mods_to_zap_names
779 = findPartiallyCompletedCycles modsDone_names
782 = filter ((`notElem` mods_to_zap_names).ms_mod)
785 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
788 -- Clean up after ourselves
789 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
791 -- there should be no Nothings where linkables should be, now
792 ASSERT(all (isJust.hm_linkable)
793 (eltsUFM (hsc_HPT hsc_env))) do
795 -- Link everything together
796 linkresult <- link (ghcLink dflags) dflags False hpt4
798 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
799 loadFinish Failed linkresult ref hsc_env4
801 -- Finish up after a load.
803 -- If the link failed, unload everything and return.
804 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
805 loadFinish _all_ok Failed ref hsc_env
806 = do unload hsc_env []
807 writeIORef ref $! discardProg hsc_env
810 -- Empty the interactive context and set the module context to the topmost
811 -- newly loaded module, or the Prelude if none were loaded.
812 loadFinish all_ok Succeeded ref hsc_env
813 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
817 -- Forget the current program, but retain the persistent info in HscEnv
818 discardProg :: HscEnv -> HscEnv
820 = hsc_env { hsc_mod_graph = emptyMG,
821 hsc_IC = emptyInteractiveContext,
822 hsc_HPT = emptyHomePackageTable }
824 -- used to fish out the preprocess output files for the purposes of
825 -- cleaning up. The preprocessed file *might* be the same as the
826 -- source file, but that doesn't do any harm.
827 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
828 ppFilesFromSummaries summaries = map ms_hspp_file summaries
830 -- -----------------------------------------------------------------------------
834 CheckedModule { parsedSource :: ParsedSource,
835 renamedSource :: Maybe RenamedSource,
836 typecheckedSource :: Maybe TypecheckedSource,
837 checkedModuleInfo :: Maybe ModuleInfo,
838 coreModule :: Maybe ModGuts
840 -- ToDo: improvements that could be made here:
841 -- if the module succeeded renaming but not typechecking,
842 -- we can still get back the GlobalRdrEnv and exports, so
843 -- perhaps the ModuleInfo should be split up into separate
844 -- fields within CheckedModule.
846 type ParsedSource = Located (HsModule RdrName)
847 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
848 Maybe (HsDoc Name), HaddockModInfo Name)
849 type TypecheckedSource = LHsBinds Id
852 -- - things that aren't in the output of the typechecker right now:
856 -- - type/data/newtype declarations
857 -- - class declarations
859 -- - extra things in the typechecker's output:
860 -- - default methods are turned into top-level decls.
861 -- - dictionary bindings
864 -- | This is the way to get access to parsed and typechecked source code
865 -- for a module. 'checkModule' attempts to typecheck the module. If
866 -- successful, it returns the abstract syntax for the module.
867 -- If compileToCore is true, it also desugars the module and returns the
868 -- resulting Core bindings as a component of the CheckedModule.
869 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
870 checkModule (Session ref) mod compile_to_core
872 hsc_env <- readIORef ref
873 let mg = hsc_mod_graph hsc_env
874 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
876 (ms:_) -> checkModule_ ref ms compile_to_core False
878 -- | parses and typechecks a module, optionally generates Core, and also
879 -- loads the module into the 'Session' so that modules which depend on
880 -- this one may subsequently be typechecked using 'checkModule' or
881 -- 'checkAndLoadModule'. If you need to check more than one module,
882 -- you probably want to use 'checkAndLoadModule'. Constructing the
883 -- interface takes a little work, so it might be slightly slower than
885 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
886 checkAndLoadModule (Session ref) ms compile_to_core
887 = checkModule_ ref ms compile_to_core True
889 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
890 -> IO (Maybe CheckedModule)
891 checkModule_ ref ms compile_to_core load
893 let mod = ms_mod_name ms
894 hsc_env0 <- readIORef ref
895 let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
896 mb_parsed <- parseFile hsc_env ms
898 Nothing -> return Nothing
899 Just rdr_module -> do
900 mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
901 case mb_typechecked of
902 Nothing -> return (Just CheckedModule {
903 parsedSource = rdr_module,
904 renamedSource = Nothing,
905 typecheckedSource = Nothing,
906 checkedModuleInfo = Nothing,
907 coreModule = Nothing })
908 Just (tcg, rn_info) -> do
909 details <- makeSimpleDetails hsc_env tcg
911 let tc_binds = tcg_binds tcg
912 let rdr_env = tcg_rdr_env tcg
913 let minf = ModuleInfo {
914 minf_type_env = md_types details,
915 minf_exports = availsToNameSet $
917 minf_rdr_env = Just rdr_env,
918 minf_instances = md_insts details
920 ,minf_modBreaks = emptyModBreaks
924 mb_guts <- if compile_to_core
925 then deSugarModule hsc_env ms tcg
928 -- If we are loading this module so that we can typecheck
929 -- dependent modules, generate an interface and stuff it
930 -- all in the HomePackageTable.
932 (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
933 let mod_info = HomeModInfo {
935 hm_details = details,
936 hm_linkable = Nothing }
937 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
938 writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
940 return (Just (CheckedModule {
941 parsedSource = rdr_module,
942 renamedSource = rn_info,
943 typecheckedSource = Just tc_binds,
944 checkedModuleInfo = Just minf,
945 coreModule = mb_guts }))
947 -- | This is the way to get access to the Core bindings corresponding
948 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
949 -- desugar the module, then returns the resulting Core module (consisting of
950 -- the module name, type declarations, and function declarations) if
952 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
953 compileToCoreModule = compileCore False
955 -- | Like compileToCoreModule, but invokes the simplifier, so
956 -- as to return simplified and tidied Core.
957 compileToCoreSimplified :: Session -> FilePath -> IO (Maybe CoreModule)
958 compileToCoreSimplified = compileCore True
960 -- | Provided for backwards-compatibility: compileToCore returns just the Core
961 -- bindings, but for most purposes, you probably want to call
962 -- compileToCoreModule.
963 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
964 compileToCore session fn = do
965 maybeCoreModule <- compileToCoreModule session fn
966 return $ fmap cm_binds maybeCoreModule
968 -- | Takes a CoreModule and compiles the bindings therein
969 -- to object code. The first argument is a bool flag indicating
970 -- whether to run the simplifier.
971 -- The resulting .o, .hi, and executable files, if any, are stored in the
972 -- current directory, and named according to the module name.
973 -- Returns True iff compilation succeeded.
974 -- This has only so far been tested with a single self-contained module.
975 compileCoreToObj :: Bool -> Session -> CoreModule -> IO Bool
976 compileCoreToObj simplify session cm@(CoreModule{ cm_module = mName }) = do
977 hscEnv <- sessionHscEnv session
978 dflags <- getSessionDynFlags session
979 currentTime <- getClockTime
980 cwd <- getCurrentDirectory
981 modLocation <- mkHiOnlyModLocation dflags (hiSuf dflags) cwd
982 ((moduleNameSlashes . moduleName) mName)
984 let modSummary = ModSummary { ms_mod = mName,
985 ms_hsc_src = ExtCoreFile,
986 ms_location = modLocation,
987 -- By setting the object file timestamp to Nothing,
988 -- we always force recompilation, which is what we
989 -- want. (Thus it doesn't matter what the timestamp
990 -- for the (nonexistent) source file is.)
991 ms_hs_date = currentTime,
992 ms_obj_date = Nothing,
993 -- Only handling the single-module case for now, so no imports.
998 ms_hspp_opts = dflags,
999 ms_hspp_buf = Nothing
1002 mbHscResult <- evalComp
1003 ((if simplify then hscSimplify else return) (mkModGuts cm)
1004 >>= hscNormalIface >>= hscWriteIface >>= hscOneShot)
1005 (CompState{ compHscEnv=hscEnv,
1006 compModSummary=modSummary,
1007 compOldIface=Nothing})
1008 return $ isJust mbHscResult
1010 -- Makes a "vanilla" ModGuts.
1011 mkModGuts :: CoreModule -> ModGuts
1012 mkModGuts coreModule = ModGuts {
1013 mg_module = cm_module coreModule,
1016 mg_deps = noDependencies,
1017 mg_dir_imps = emptyModuleEnv,
1018 mg_used_names = emptyNameSet,
1019 mg_rdr_env = emptyGlobalRdrEnv,
1020 mg_fix_env = emptyFixityEnv,
1021 mg_types = emptyTypeEnv,
1025 mg_binds = cm_binds coreModule,
1026 mg_foreign = NoStubs,
1027 mg_warns = NoWarnings,
1028 mg_hpc_info = emptyHpcInfo False,
1029 mg_modBreaks = emptyModBreaks,
1030 mg_vect_info = noVectInfo,
1031 mg_inst_env = emptyInstEnv,
1032 mg_fam_inst_env = emptyFamInstEnv
1035 compileCore :: Bool -> Session -> FilePath -> IO (Maybe CoreModule)
1036 compileCore simplify session fn = do
1037 -- First, set the target to the desired filename
1038 target <- guessTarget fn Nothing
1039 addTarget session target
1040 load session LoadAllTargets
1041 -- Then find dependencies
1042 maybeModGraph <- depanal session [] True
1043 case maybeModGraph of
1044 Nothing -> return Nothing
1046 case find ((== fn) . msHsFilePath) modGraph of
1047 Just modSummary -> do
1048 -- Now we have the module name;
1049 -- parse, typecheck and desugar the module
1050 let mod = ms_mod_name modSummary
1051 maybeCheckedModule <- checkModule session mod True
1052 case maybeCheckedModule of
1053 Nothing -> return Nothing
1054 Just checkedMod -> (liftM $ fmap gutsToCoreModule) $
1055 case (coreModule checkedMod) of
1056 Just mg | simplify -> (sessionHscEnv session)
1057 -- If simplify is true: simplify (hscSimplify),
1058 -- then tidy (tidyProgram).
1059 >>= \ hscEnv -> evalComp (hscSimplify mg)
1060 (CompState{ compHscEnv=hscEnv,
1061 compModSummary=modSummary,
1062 compOldIface=Nothing})
1063 >>= (tidyProgram hscEnv)
1064 >>= (return . Just . Left)
1065 Just guts -> return $ Just $ Right guts
1066 Nothing -> return Nothing
1067 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1068 module dependency graph"
1069 where -- two versions, based on whether we simplify (thus run tidyProgram,
1070 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1071 -- we just have a ModGuts.
1072 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1073 gutsToCoreModule (Left (cg, md)) = CoreModule {
1074 cm_module = cg_module cg, cm_types = md_types md,
1075 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1077 gutsToCoreModule (Right mg) = CoreModule {
1078 cm_module = mg_module mg, cm_types = mg_types mg,
1079 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1082 -- ---------------------------------------------------------------------------
1085 unload :: HscEnv -> [Linkable] -> IO ()
1086 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1087 = case ghcLink (hsc_dflags hsc_env) of
1089 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1091 LinkInMemory -> panic "unload: no interpreter"
1092 -- urgh. avoid warnings:
1093 hsc_env stable_linkables
1097 -- -----------------------------------------------------------------------------
1101 Stability tells us which modules definitely do not need to be recompiled.
1102 There are two main reasons for having stability:
1104 - avoid doing a complete upsweep of the module graph in GHCi when
1105 modules near the bottom of the tree have not changed.
1107 - to tell GHCi when it can load object code: we can only load object code
1108 for a module when we also load object code fo all of the imports of the
1109 module. So we need to know that we will definitely not be recompiling
1110 any of these modules, and we can use the object code.
1112 The stability check is as follows. Both stableObject and
1113 stableBCO are used during the upsweep phase later.
1116 stable m = stableObject m || stableBCO m
1119 all stableObject (imports m)
1120 && old linkable does not exist, or is == on-disk .o
1121 && date(on-disk .o) > date(.hs)
1124 all stable (imports m)
1125 && date(BCO) > date(.hs)
1128 These properties embody the following ideas:
1130 - if a module is stable, then:
1131 - if it has been compiled in a previous pass (present in HPT)
1132 then it does not need to be compiled or re-linked.
1133 - if it has not been compiled in a previous pass,
1134 then we only need to read its .hi file from disk and
1135 link it to produce a ModDetails.
1137 - if a modules is not stable, we will definitely be at least
1138 re-linking, and possibly re-compiling it during the upsweep.
1139 All non-stable modules can (and should) therefore be unlinked
1142 - Note that objects are only considered stable if they only depend
1143 on other objects. We can't link object code against byte code.
1147 :: HomePackageTable -- HPT from last compilation
1148 -> [SCC ModSummary] -- current module graph (cyclic)
1149 -> [ModuleName] -- all home modules
1150 -> ([ModuleName], -- stableObject
1151 [ModuleName]) -- stableBCO
1153 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1155 checkSCC (stable_obj, stable_bco) scc0
1156 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1157 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1158 | otherwise = (stable_obj, stable_bco)
1160 scc = flattenSCC scc0
1161 scc_mods = map ms_mod_name scc
1162 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1164 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1165 -- all imports outside the current SCC, but in the home pkg
1167 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1168 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1172 && all object_ok scc
1175 and (zipWith (||) stable_obj_imps stable_bco_imps)
1179 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1183 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1184 Just hmi | Just l <- hm_linkable hmi
1185 -> isObjectLinkable l && t == linkableTime l
1187 -- why '>=' rather than '>' above? If the filesystem stores
1188 -- times to the nearset second, we may occasionally find that
1189 -- the object & source have the same modification time,
1190 -- especially if the source was automatically generated
1191 -- and compiled. Using >= is slightly unsafe, but it matches
1192 -- make's behaviour.
1195 = case lookupUFM hpt (ms_mod_name ms) of
1196 Just hmi | Just l <- hm_linkable hmi ->
1197 not (isObjectLinkable l) &&
1198 linkableTime l >= ms_hs_date ms
1201 ms_allimps :: ModSummary -> [ModuleName]
1202 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1204 -- -----------------------------------------------------------------------------
1205 -- Prune the HomePackageTable
1207 -- Before doing an upsweep, we can throw away:
1209 -- - For non-stable modules:
1210 -- - all ModDetails, all linked code
1211 -- - all unlinked code that is out of date with respect to
1214 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1215 -- space at the end of the upsweep, because the topmost ModDetails of the
1216 -- old HPT holds on to the entire type environment from the previous
1219 pruneHomePackageTable
1222 -> ([ModuleName],[ModuleName])
1225 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1228 | is_stable modl = hmi'
1229 | otherwise = hmi'{ hm_details = emptyModDetails }
1231 modl = moduleName (mi_module (hm_iface hmi))
1232 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1233 = hmi{ hm_linkable = Nothing }
1236 where ms = expectJust "prune" (lookupUFM ms_map modl)
1238 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1240 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1242 -- -----------------------------------------------------------------------------
1244 -- Return (names of) all those in modsDone who are part of a cycle
1245 -- as defined by theGraph.
1246 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1247 findPartiallyCompletedCycles modsDone theGraph
1251 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1252 chew ((CyclicSCC vs):rest)
1253 = let names_in_this_cycle = nub (map ms_mod vs)
1255 = nub ([done | done <- modsDone,
1256 done `elem` names_in_this_cycle])
1257 chewed_rest = chew rest
1259 if notNull mods_in_this_cycle
1260 && length mods_in_this_cycle < length names_in_this_cycle
1261 then mods_in_this_cycle ++ chewed_rest
1264 -- -----------------------------------------------------------------------------
1267 -- This is where we compile each module in the module graph, in a pass
1268 -- from the bottom to the top of the graph.
1270 -- There better had not be any cyclic groups here -- we check for them.
1273 :: HscEnv -- Includes initially-empty HPT
1274 -> HomePackageTable -- HPT from last time round (pruned)
1275 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1276 -> IO () -- How to clean up unwanted tmp files
1277 -> [SCC ModSummary] -- Mods to do (the worklist)
1279 HscEnv, -- With an updated HPT
1280 [ModSummary]) -- Mods which succeeded
1282 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1283 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1284 return (res, hsc_env, reverse done)
1287 upsweep' hsc_env _old_hpt done
1289 = return (Succeeded, hsc_env, done)
1291 upsweep' hsc_env _old_hpt done
1292 (CyclicSCC ms:_) _ _
1293 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1294 return (Failed, hsc_env, done)
1296 upsweep' hsc_env old_hpt done
1297 (AcyclicSCC mod:mods) mod_index nmods
1298 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1299 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1300 -- (moduleEnvElts (hsc_HPT hsc_env)))
1302 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1305 cleanup -- Remove unwanted tmp files between compilations
1308 Nothing -> return (Failed, hsc_env, done)
1310 let this_mod = ms_mod_name mod
1312 -- Add new info to hsc_env
1313 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1314 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1316 -- Space-saving: delete the old HPT entry
1317 -- for mod BUT if mod is a hs-boot
1318 -- node, don't delete it. For the
1319 -- interface, the HPT entry is probaby for the
1320 -- main Haskell source file. Deleting it
1321 -- would force the real module to be recompiled
1323 old_hpt1 | isBootSummary mod = old_hpt
1324 | otherwise = delFromUFM old_hpt this_mod
1328 -- fixup our HomePackageTable after we've finished compiling
1329 -- a mutually-recursive loop. See reTypecheckLoop, below.
1330 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1332 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1335 -- Compile a single module. Always produce a Linkable for it if
1336 -- successful. If no compilation happened, return the old Linkable.
1337 upsweep_mod :: HscEnv
1339 -> ([ModuleName],[ModuleName])
1341 -> Int -- index of module
1342 -> Int -- total number of modules
1343 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1345 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1347 this_mod_name = ms_mod_name summary
1348 this_mod = ms_mod summary
1349 mb_obj_date = ms_obj_date summary
1350 obj_fn = ml_obj_file (ms_location summary)
1351 hs_date = ms_hs_date summary
1353 is_stable_obj = this_mod_name `elem` stable_obj
1354 is_stable_bco = this_mod_name `elem` stable_bco
1356 old_hmi = lookupUFM old_hpt this_mod_name
1358 -- We're using the dflags for this module now, obtained by
1359 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1360 dflags = ms_hspp_opts summary
1361 prevailing_target = hscTarget (hsc_dflags hsc_env)
1362 local_target = hscTarget dflags
1364 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1365 -- we don't do anything dodgy: these should only work to change
1366 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1367 -- end up trying to link object code to byte code.
1368 target = if prevailing_target /= local_target
1369 && (not (isObjectTarget prevailing_target)
1370 || not (isObjectTarget local_target))
1371 then prevailing_target
1374 -- store the corrected hscTarget into the summary
1375 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1377 -- The old interface is ok if
1378 -- a) we're compiling a source file, and the old HPT
1379 -- entry is for a source file
1380 -- b) we're compiling a hs-boot file
1381 -- Case (b) allows an hs-boot file to get the interface of its
1382 -- real source file on the second iteration of the compilation
1383 -- manager, but that does no harm. Otherwise the hs-boot file
1384 -- will always be recompiled
1389 Just hm_info | isBootSummary summary -> Just iface
1390 | not (mi_boot iface) -> Just iface
1391 | otherwise -> Nothing
1393 iface = hm_iface hm_info
1395 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1396 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1398 compile_it_discard_iface
1399 = compile hsc_env summary' mod_index nmods Nothing
1405 -- Regardless of whether we're generating object code or
1406 -- byte code, we can always use an existing object file
1407 -- if it is *stable* (see checkStability).
1408 | is_stable_obj, isJust old_hmi ->
1410 -- object is stable, and we have an entry in the
1411 -- old HPT: nothing to do
1413 | is_stable_obj, isNothing old_hmi -> do
1414 linkable <- findObjectLinkable this_mod obj_fn
1415 (expectJust "upseep1" mb_obj_date)
1416 compile_it (Just linkable)
1417 -- object is stable, but we need to load the interface
1418 -- off disk to make a HMI.
1422 ASSERT(isJust old_hmi) -- must be in the old_hpt
1424 -- BCO is stable: nothing to do
1426 | Just hmi <- old_hmi,
1427 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1428 linkableTime l >= ms_hs_date summary ->
1430 -- we have an old BCO that is up to date with respect
1431 -- to the source: do a recompilation check as normal.
1435 -- no existing code at all: we must recompile.
1437 -- When generating object code, if there's an up-to-date
1438 -- object file on the disk, then we can use it.
1439 -- However, if the object file is new (compared to any
1440 -- linkable we had from a previous compilation), then we
1441 -- must discard any in-memory interface, because this
1442 -- means the user has compiled the source file
1443 -- separately and generated a new interface, that we must
1444 -- read from the disk.
1446 obj | isObjectTarget obj,
1447 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1450 | Just l <- hm_linkable hmi,
1451 isObjectLinkable l && linkableTime l == obj_date
1452 -> compile_it (Just l)
1454 linkable <- findObjectLinkable this_mod obj_fn obj_date
1455 compile_it_discard_iface (Just linkable)
1462 -- Filter modules in the HPT
1463 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1464 retainInTopLevelEnvs keep_these hpt
1465 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1467 , let mb_mod_info = lookupUFM hpt mod
1468 , isJust mb_mod_info ]
1470 -- ---------------------------------------------------------------------------
1471 -- Typecheck module loops
1474 See bug #930. This code fixes a long-standing bug in --make. The
1475 problem is that when compiling the modules *inside* a loop, a data
1476 type that is only defined at the top of the loop looks opaque; but
1477 after the loop is done, the structure of the data type becomes
1480 The difficulty is then that two different bits of code have
1481 different notions of what the data type looks like.
1483 The idea is that after we compile a module which also has an .hs-boot
1484 file, we re-generate the ModDetails for each of the modules that
1485 depends on the .hs-boot file, so that everyone points to the proper
1486 TyCons, Ids etc. defined by the real module, not the boot module.
1487 Fortunately re-generating a ModDetails from a ModIface is easy: the
1488 function TcIface.typecheckIface does exactly that.
1490 Picking the modules to re-typecheck is slightly tricky. Starting from
1491 the module graph consisting of the modules that have already been
1492 compiled, we reverse the edges (so they point from the imported module
1493 to the importing module), and depth-first-search from the .hs-boot
1494 node. This gives us all the modules that depend transitively on the
1495 .hs-boot module, and those are exactly the modules that we need to
1498 Following this fix, GHC can compile itself with --make -O2.
1501 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1502 reTypecheckLoop hsc_env ms graph
1503 | not (isBootSummary ms) &&
1504 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1506 let mss = reachableBackwards (ms_mod_name ms) graph
1507 non_boot = filter (not.isBootSummary) mss
1508 debugTraceMsg (hsc_dflags hsc_env) 2 $
1509 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1510 typecheckLoop hsc_env (map ms_mod_name non_boot)
1514 this_mod = ms_mod ms
1516 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1517 typecheckLoop hsc_env mods = do
1519 fixIO $ \new_hpt -> do
1520 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1521 mds <- initIfaceCheck new_hsc_env $
1522 mapM (typecheckIface . hm_iface) hmis
1523 let new_hpt = addListToUFM old_hpt
1524 (zip mods [ hmi{ hm_details = details }
1525 | (hmi,details) <- zip hmis mds ])
1527 return hsc_env{ hsc_HPT = new_hpt }
1529 old_hpt = hsc_HPT hsc_env
1530 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1532 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1533 reachableBackwards mod summaries
1534 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1536 -- all the nodes reachable by traversing the edges backwards
1537 -- from the root node:
1538 nodes_we_want = reachable (transposeG graph) root
1540 -- the rest just sets up the graph:
1541 (nodes, lookup_key) = moduleGraphNodes False summaries
1542 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1544 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1545 | otherwise = panic "reachableBackwards"
1547 -- ---------------------------------------------------------------------------
1548 -- Topological sort of the module graph
1551 :: Bool -- Drop hi-boot nodes? (see below)
1555 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1556 -- The resulting list of strongly-connected-components is in topologically
1557 -- sorted order, starting with the module(s) at the bottom of the
1558 -- dependency graph (ie compile them first) and ending with the ones at
1561 -- Drop hi-boot nodes (first boolean arg)?
1563 -- False: treat the hi-boot summaries as nodes of the graph,
1564 -- so the graph must be acyclic
1566 -- True: eliminate the hi-boot nodes, and instead pretend
1567 -- the a source-import of Foo is an import of Foo
1568 -- The resulting graph has no hi-boot nodes, but can by cyclic
1570 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1571 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1572 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1573 = stronglyConnComp (map vertex_fn (reachable graph root))
1575 -- restrict the graph to just those modules reachable from
1576 -- the specified module. We do this by building a graph with
1577 -- the full set of nodes, and determining the reachable set from
1578 -- the specified node.
1579 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1580 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1582 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1583 | otherwise = ghcError (ProgramError "module does not exist")
1585 moduleGraphNodes :: Bool -> [ModSummary]
1586 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1587 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1589 -- Drop hs-boot nodes by using HsSrcFile as the key
1590 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1591 | otherwise = HsBootFile
1593 -- We use integers as the keys for the SCC algorithm
1594 nodes :: [(ModSummary, Int, [Int])]
1595 nodes = [(s, expectJust "topSort" $
1596 lookup_key (ms_hsc_src s) (ms_mod_name s),
1597 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1598 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1599 (-- see [boot-edges] below
1600 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1602 else case lookup_key HsBootFile (ms_mod_name s) of
1607 , not (isBootSummary s && drop_hs_boot_nodes) ]
1608 -- Drop the hi-boot ones if told to do so
1610 -- [boot-edges] if this is a .hs and there is an equivalent
1611 -- .hs-boot, add a link from the former to the latter. This
1612 -- has the effect of detecting bogus cases where the .hs-boot
1613 -- depends on the .hs, by introducing a cycle. Additionally,
1614 -- it ensures that we will always process the .hs-boot before
1615 -- the .hs, and so the HomePackageTable will always have the
1616 -- most up to date information.
1618 key_map :: NodeMap Int
1619 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1623 lookup_key :: HscSource -> ModuleName -> Maybe Int
1624 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1626 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1627 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1628 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1629 -- the IsBootInterface parameter True; else False
1632 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1633 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1635 msKey :: ModSummary -> NodeKey
1636 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1638 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1639 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1641 nodeMapElts :: NodeMap a -> [a]
1642 nodeMapElts = eltsFM
1644 -- If there are {-# SOURCE #-} imports between strongly connected
1645 -- components in the topological sort, then those imports can
1646 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1647 -- were necessary, then the edge would be part of a cycle.
1648 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1649 warnUnnecessarySourceImports dflags sccs =
1650 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1652 let mods_in_this_cycle = map ms_mod_name ms in
1653 [ warn i | m <- ms, i <- ms_srcimps m,
1654 unLoc i `notElem` mods_in_this_cycle ]
1656 warn :: Located ModuleName -> WarnMsg
1659 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1660 <+> quotes (ppr mod))
1662 -----------------------------------------------------------------------------
1663 -- Downsweep (dependency analysis)
1665 -- Chase downwards from the specified root set, returning summaries
1666 -- for all home modules encountered. Only follow source-import
1669 -- We pass in the previous collection of summaries, which is used as a
1670 -- cache to avoid recalculating a module summary if the source is
1673 -- The returned list of [ModSummary] nodes has one node for each home-package
1674 -- module, plus one for any hs-boot files. The imports of these nodes
1675 -- are all there, including the imports of non-home-package modules.
1678 -> [ModSummary] -- Old summaries
1679 -> [ModuleName] -- Ignore dependencies on these; treat
1680 -- them as if they were package modules
1681 -> Bool -- True <=> allow multiple targets to have
1682 -- the same module name; this is
1683 -- very useful for ghc -M
1684 -> IO (Maybe [ModSummary])
1685 -- The elts of [ModSummary] all have distinct
1686 -- (Modules, IsBoot) identifiers, unless the Bool is true
1687 -- in which case there can be repeats
1688 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1689 = -- catch error messages and return them
1691 (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1692 rootSummaries <- mapM getRootSummary roots
1693 let root_map = mkRootMap rootSummaries
1694 checkDuplicates root_map
1695 summs <- loop (concatMap msDeps rootSummaries) root_map
1698 roots = hsc_targets hsc_env
1700 old_summary_map :: NodeMap ModSummary
1701 old_summary_map = mkNodeMap old_summaries
1703 getRootSummary :: Target -> IO ModSummary
1704 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1705 = do exists <- doesFileExist file
1707 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1708 else throwErrMsg $ mkPlainErrMsg noSrcSpan $
1709 text "can't find file:" <+> text file
1710 getRootSummary (Target (TargetModule modl) maybe_buf)
1711 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1712 (L rootLoc modl) maybe_buf excl_mods
1713 case maybe_summary of
1714 Nothing -> packageModErr modl
1717 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1719 -- In a root module, the filename is allowed to diverge from the module
1720 -- name, so we have to check that there aren't multiple root files
1721 -- defining the same module (otherwise the duplicates will be silently
1722 -- ignored, leading to confusing behaviour).
1723 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1724 checkDuplicates root_map
1725 | allow_dup_roots = return ()
1726 | null dup_roots = return ()
1727 | otherwise = multiRootsErr (head dup_roots)
1729 dup_roots :: [[ModSummary]] -- Each at least of length 2
1730 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1732 loop :: [(Located ModuleName,IsBootInterface)]
1733 -- Work list: process these modules
1734 -> NodeMap [ModSummary]
1735 -- Visited set; the range is a list because
1736 -- the roots can have the same module names
1737 -- if allow_dup_roots is True
1739 -- The result includes the worklist, except
1740 -- for those mentioned in the visited set
1741 loop [] done = return (concat (nodeMapElts done))
1742 loop ((wanted_mod, is_boot) : ss) done
1743 | Just summs <- lookupFM done key
1744 = if isSingleton summs then
1747 do { multiRootsErr summs; return [] }
1748 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1749 is_boot wanted_mod Nothing excl_mods
1751 Nothing -> loop ss done
1752 Just s -> loop (msDeps s ++ ss)
1753 (addToFM done key [s]) }
1755 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1757 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1758 mkRootMap summaries = addListToFM_C (++) emptyFM
1759 [ (msKey s, [s]) | s <- summaries ]
1761 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1762 -- (msDeps s) returns the dependencies of the ModSummary s.
1763 -- A wrinkle is that for a {-# SOURCE #-} import we return
1764 -- *both* the hs-boot file
1765 -- *and* the source file
1766 -- as "dependencies". That ensures that the list of all relevant
1767 -- modules always contains B.hs if it contains B.hs-boot.
1768 -- Remember, this pass isn't doing the topological sort. It's
1769 -- just gathering the list of all relevant ModSummaries
1771 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1772 ++ [ (m,False) | m <- ms_imps s ]
1774 -----------------------------------------------------------------------------
1775 -- Summarising modules
1777 -- We have two types of summarisation:
1779 -- * Summarise a file. This is used for the root module(s) passed to
1780 -- cmLoadModules. The file is read, and used to determine the root
1781 -- module name. The module name may differ from the filename.
1783 -- * Summarise a module. We are given a module name, and must provide
1784 -- a summary. The finder is used to locate the file in which the module
1789 -> [ModSummary] -- old summaries
1790 -> FilePath -- source file name
1791 -> Maybe Phase -- start phase
1792 -> Maybe (StringBuffer,ClockTime)
1795 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1796 -- we can use a cached summary if one is available and the
1797 -- source file hasn't changed, But we have to look up the summary
1798 -- by source file, rather than module name as we do in summarise.
1799 | Just old_summary <- findSummaryBySourceFile old_summaries file
1801 let location = ms_location old_summary
1803 -- return the cached summary if the source didn't change
1804 src_timestamp <- case maybe_buf of
1805 Just (_,t) -> return t
1806 Nothing -> getModificationTime file
1807 -- The file exists; we checked in getRootSummary above.
1808 -- If it gets removed subsequently, then this
1809 -- getModificationTime may fail, but that's the right
1812 if ms_hs_date old_summary == src_timestamp
1813 then do -- update the object-file timestamp
1815 if isObjectTarget (hscTarget (hsc_dflags hsc_env)) -- bug #1205
1816 then getObjTimestamp location False
1818 return old_summary{ ms_obj_date = obj_timestamp }
1826 let dflags = hsc_dflags hsc_env
1828 (dflags', hspp_fn, buf)
1829 <- preprocessFile hsc_env file mb_phase maybe_buf
1831 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1833 -- Make a ModLocation for this file
1834 location <- mkHomeModLocation dflags mod_name file
1836 -- Tell the Finder cache where it is, so that subsequent calls
1837 -- to findModule will find it, even if it's not on any search path
1838 mod <- addHomeModuleToFinder hsc_env mod_name location
1840 src_timestamp <- case maybe_buf of
1841 Just (_,t) -> return t
1842 Nothing -> getModificationTime file
1843 -- getMofificationTime may fail
1845 -- when the user asks to load a source file by name, we only
1846 -- use an object file if -fobject-code is on. See #1205.
1848 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1849 then modificationTimeIfExists (ml_obj_file location)
1852 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1853 ms_location = location,
1854 ms_hspp_file = hspp_fn,
1855 ms_hspp_opts = dflags',
1856 ms_hspp_buf = Just buf,
1857 ms_srcimps = srcimps, ms_imps = the_imps,
1858 ms_hs_date = src_timestamp,
1859 ms_obj_date = obj_timestamp })
1861 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1862 findSummaryBySourceFile summaries file
1863 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1864 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1868 -- Summarise a module, and pick up source and timestamp.
1871 -> NodeMap ModSummary -- Map of old summaries
1872 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1873 -> Located ModuleName -- Imported module to be summarised
1874 -> Maybe (StringBuffer, ClockTime)
1875 -> [ModuleName] -- Modules to exclude
1876 -> IO (Maybe ModSummary) -- Its new summary
1878 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1879 | wanted_mod `elem` excl_mods
1882 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1883 = do -- Find its new timestamp; all the
1884 -- ModSummaries in the old map have valid ml_hs_files
1885 let location = ms_location old_summary
1886 src_fn = expectJust "summariseModule" (ml_hs_file location)
1888 -- check the modification time on the source file, and
1889 -- return the cached summary if it hasn't changed. If the
1890 -- file has disappeared, we need to call the Finder again.
1892 Just (_,t) -> check_timestamp old_summary location src_fn t
1894 m <- System.IO.Error.try (getModificationTime src_fn)
1896 Right t -> check_timestamp old_summary location src_fn t
1897 Left e | isDoesNotExistError e -> find_it
1898 | otherwise -> ioError e
1900 | otherwise = find_it
1902 dflags = hsc_dflags hsc_env
1904 hsc_src = if is_boot then HsBootFile else HsSrcFile
1906 check_timestamp old_summary location src_fn src_timestamp
1907 | ms_hs_date old_summary == src_timestamp = do
1908 -- update the object-file timestamp
1909 obj_timestamp <- getObjTimestamp location is_boot
1910 return (Just old_summary{ ms_obj_date = obj_timestamp })
1912 -- source changed: re-summarise.
1913 new_summary location (ms_mod old_summary) src_fn src_timestamp
1916 -- Don't use the Finder's cache this time. If the module was
1917 -- previously a package module, it may have now appeared on the
1918 -- search path, so we want to consider it to be a home module. If
1919 -- the module was previously a home module, it may have moved.
1920 uncacheModule hsc_env wanted_mod
1921 found <- findImportedModule hsc_env wanted_mod Nothing
1924 | isJust (ml_hs_file location) ->
1926 just_found location mod
1928 -- Drop external-pkg
1929 ASSERT(modulePackageId mod /= thisPackage dflags)
1932 err -> noModError dflags loc wanted_mod err
1935 just_found location mod = do
1936 -- Adjust location to point to the hs-boot source file,
1937 -- hi file, object file, when is_boot says so
1938 let location' | is_boot = addBootSuffixLocn location
1939 | otherwise = location
1940 src_fn = expectJust "summarise2" (ml_hs_file location')
1942 -- Check that it exists
1943 -- It might have been deleted since the Finder last found it
1944 maybe_t <- modificationTimeIfExists src_fn
1946 Nothing -> noHsFileErr loc src_fn
1947 Just t -> new_summary location' mod src_fn t
1950 new_summary location mod src_fn src_timestamp
1952 -- Preprocess the source file and get its imports
1953 -- The dflags' contains the OPTIONS pragmas
1954 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
1955 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1957 when (mod_name /= wanted_mod) $
1958 throwErrMsg $ mkPlainErrMsg mod_loc $
1959 text "File name does not match module name:"
1960 $$ text "Saw:" <+> quotes (ppr mod_name)
1961 $$ text "Expected:" <+> quotes (ppr wanted_mod)
1963 -- Find the object timestamp, and return the summary
1964 obj_timestamp <- getObjTimestamp location is_boot
1966 return (Just ( ModSummary { ms_mod = mod,
1967 ms_hsc_src = hsc_src,
1968 ms_location = location,
1969 ms_hspp_file = hspp_fn,
1970 ms_hspp_opts = dflags',
1971 ms_hspp_buf = Just buf,
1972 ms_srcimps = srcimps,
1974 ms_hs_date = src_timestamp,
1975 ms_obj_date = obj_timestamp }))
1978 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1979 getObjTimestamp location is_boot
1980 = if is_boot then return Nothing
1981 else modificationTimeIfExists (ml_obj_file location)
1984 preprocessFile :: HscEnv -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1985 -> IO (DynFlags, FilePath, StringBuffer)
1986 preprocessFile hsc_env src_fn mb_phase Nothing
1988 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
1989 buf <- hGetStringBuffer hspp_fn
1990 return (dflags', hspp_fn, buf)
1992 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
1994 let dflags = hsc_dflags hsc_env
1995 -- case we bypass the preprocessing stage?
1997 local_opts = getOptions dflags buf src_fn
1999 (dflags', leftovers, warns) <- parseDynamicFlags dflags (map unLoc local_opts)
2000 checkProcessArgsResult leftovers src_fn
2001 handleFlagWarnings dflags' warns
2005 | Just (Unlit _) <- mb_phase = True
2006 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2007 -- note: local_opts is only required if there's no Unlit phase
2008 | dopt Opt_Cpp dflags' = True
2009 | dopt Opt_Pp dflags' = True
2012 when needs_preprocessing $
2013 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
2015 return (dflags', src_fn, buf)
2018 -----------------------------------------------------------------------------
2020 -----------------------------------------------------------------------------
2022 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
2023 -- ToDo: we don't have a proper line number for this error
2024 noModError dflags loc wanted_mod err
2025 = throwErrMsg $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2027 noHsFileErr :: SrcSpan -> String -> a
2028 noHsFileErr loc path
2029 = throwErrMsg $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2031 packageModErr :: ModuleName -> a
2033 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2034 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2036 multiRootsErr :: [ModSummary] -> IO ()
2037 multiRootsErr [] = panic "multiRootsErr"
2038 multiRootsErr summs@(summ1:_)
2039 = throwErrMsg $ mkPlainErrMsg noSrcSpan $
2040 text "module" <+> quotes (ppr mod) <+>
2041 text "is defined in multiple files:" <+>
2042 sep (map text files)
2045 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2047 cyclicModuleErr :: [ModSummary] -> SDoc
2049 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2050 2 (vcat (map show_one ms))
2052 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2053 nest 2 $ ptext (sLit "imports:") <+>
2054 (pp_imps HsBootFile (ms_srcimps ms)
2055 $$ pp_imps HsSrcFile (ms_imps ms))]
2056 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2057 pp_imps src mods = fsep (map (show_mod src) mods)
2060 -- | Inform GHC that the working directory has changed. GHC will flush
2061 -- its cache of module locations, since it may no longer be valid.
2062 -- Note: if you change the working directory, you should also unload
2063 -- the current program (set targets to empty, followed by load).
2064 workingDirectoryChanged :: Session -> IO ()
2065 workingDirectoryChanged s = withSession s $ flushFinderCaches
2067 -- -----------------------------------------------------------------------------
2068 -- inspecting the session
2070 -- | Get the module dependency graph.
2071 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
2072 getModuleGraph s = withSession s (return . hsc_mod_graph)
2074 isLoaded :: Session -> ModuleName -> IO Bool
2075 isLoaded s m = withSession s $ \hsc_env ->
2076 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2078 getBindings :: Session -> IO [TyThing]
2079 getBindings s = withSession s $ \hsc_env ->
2080 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2081 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2083 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2084 filtered = foldr f (const []) tmp_ids emptyUniqSet
2086 | uniq `elementOfUniqSet` set = rest set
2087 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2088 where uniq = getUnique (nameOccName (idName id))
2092 getPrintUnqual :: Session -> IO PrintUnqualified
2093 getPrintUnqual s = withSession s $ \hsc_env ->
2094 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2096 -- | Container for information about a 'Module'.
2097 data ModuleInfo = ModuleInfo {
2098 minf_type_env :: TypeEnv,
2099 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2100 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2101 minf_instances :: [Instance]
2103 ,minf_modBreaks :: ModBreaks
2105 -- ToDo: this should really contain the ModIface too
2107 -- We don't want HomeModInfo here, because a ModuleInfo applies
2108 -- to package modules too.
2110 -- | Request information about a loaded 'Module'
2111 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
2112 getModuleInfo s mdl = withSession s $ \hsc_env -> do
2113 let mg = hsc_mod_graph hsc_env
2114 if mdl `elem` map ms_mod mg
2115 then getHomeModuleInfo hsc_env (moduleName mdl)
2117 {- if isHomeModule (hsc_dflags hsc_env) mdl
2119 else -} getPackageModuleInfo hsc_env mdl
2120 -- getPackageModuleInfo will attempt to find the interface, so
2121 -- we don't want to call it for a home module, just in case there
2122 -- was a problem loading the module and the interface doesn't
2123 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2125 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2127 getPackageModuleInfo hsc_env mdl = do
2128 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2130 Nothing -> return Nothing
2132 eps <- readIORef (hsc_EPS hsc_env)
2134 names = availsToNameSet avails
2136 tys = [ ty | name <- concatMap availNames avails,
2137 Just ty <- [lookupTypeEnv pte name] ]
2139 return (Just (ModuleInfo {
2140 minf_type_env = mkTypeEnv tys,
2141 minf_exports = names,
2142 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2143 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2144 minf_modBreaks = emptyModBreaks
2147 getPackageModuleInfo _hsc_env _mdl = do
2148 -- bogusly different for non-GHCI (ToDo)
2152 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2153 getHomeModuleInfo hsc_env mdl =
2154 case lookupUFM (hsc_HPT hsc_env) mdl of
2155 Nothing -> return Nothing
2157 let details = hm_details hmi
2158 return (Just (ModuleInfo {
2159 minf_type_env = md_types details,
2160 minf_exports = availsToNameSet (md_exports details),
2161 minf_rdr_env = mi_globals $! hm_iface hmi,
2162 minf_instances = md_insts details
2164 ,minf_modBreaks = getModBreaks hmi
2168 -- | The list of top-level entities defined in a module
2169 modInfoTyThings :: ModuleInfo -> [TyThing]
2170 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2172 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2173 modInfoTopLevelScope minf
2174 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2176 modInfoExports :: ModuleInfo -> [Name]
2177 modInfoExports minf = nameSetToList $! minf_exports minf
2179 -- | Returns the instances defined by the specified module.
2180 -- Warning: currently unimplemented for package modules.
2181 modInfoInstances :: ModuleInfo -> [Instance]
2182 modInfoInstances = minf_instances
2184 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2185 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2187 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2188 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2189 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2191 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2192 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2193 case lookupTypeEnv (minf_type_env minf) name of
2194 Just tyThing -> return (Just tyThing)
2196 eps <- readIORef (hsc_EPS hsc_env)
2197 return $! lookupType (hsc_dflags hsc_env)
2198 (hsc_HPT hsc_env) (eps_PTE eps) name
2201 modInfoModBreaks :: ModuleInfo -> ModBreaks
2202 modInfoModBreaks = minf_modBreaks
2205 isDictonaryId :: Id -> Bool
2207 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2209 -- | Looks up a global name: that is, any top-level name in any
2210 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2211 -- the interactive context, and therefore does not require a preceding
2213 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2214 lookupGlobalName s name = withSession s $ \hsc_env -> do
2215 eps <- readIORef (hsc_EPS hsc_env)
2216 return $! lookupType (hsc_dflags hsc_env)
2217 (hsc_HPT hsc_env) (eps_PTE eps) name
2220 -- | get the GlobalRdrEnv for a session
2221 getGRE :: Session -> IO GlobalRdrEnv
2222 getGRE s = withSession s $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2225 -- -----------------------------------------------------------------------------
2226 -- Misc exported utils
2228 dataConType :: DataCon -> Type
2229 dataConType dc = idType (dataConWrapId dc)
2231 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2232 pprParenSymName :: NamedThing a => a -> SDoc
2233 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2235 -- ----------------------------------------------------------------------------
2240 -- - Data and Typeable instances for HsSyn.
2242 -- ToDo: check for small transformations that happen to the syntax in
2243 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2245 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2246 -- to get from TyCons, Ids etc. to TH syntax (reify).
2248 -- :browse will use either lm_toplev or inspect lm_interface, depending
2249 -- on whether the module is interpreted or not.
2251 -- This is for reconstructing refactored source code
2252 -- Calls the lexer repeatedly.
2253 -- ToDo: add comment tokens to token stream
2254 getTokenStream :: Session -> Module -> IO [Located Token]
2257 -- -----------------------------------------------------------------------------
2258 -- Interactive evaluation
2260 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2261 -- filesystem and package database to find the corresponding 'Module',
2262 -- using the algorithm that is used for an @import@ declaration.
2263 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2264 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2266 dflags = hsc_dflags hsc_env
2267 hpt = hsc_HPT hsc_env
2268 this_pkg = thisPackage dflags
2270 case lookupUFM hpt mod_name of
2271 Just mod_info -> return (mi_module (hm_iface mod_info))
2272 _not_a_home_module -> do
2273 res <- findImportedModule hsc_env mod_name maybe_pkg
2275 Found _ m | modulePackageId m /= this_pkg -> return m
2276 | otherwise -> ghcError (CmdLineError (showSDoc $
2277 text "module" <+> quotes (ppr (moduleName m)) <+>
2278 text "is not loaded"))
2279 err -> let msg = cannotFindModule dflags mod_name err in
2280 ghcError (CmdLineError (showSDoc msg))
2283 getHistorySpan :: Session -> History -> IO SrcSpan
2284 getHistorySpan sess h = withSession sess $ \hsc_env ->
2285 return$ InteractiveEval.getHistorySpan hsc_env h
2287 obtainTerm :: Session -> Bool -> Id -> IO Term
2288 obtainTerm sess force id = withSession sess $ \hsc_env ->
2289 InteractiveEval.obtainTerm hsc_env force id
2291 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2292 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2293 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2295 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2296 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2297 InteractiveEval.obtainTermB hsc_env bound force id