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 )
242 import HeaderInfo ( getImports, getOptions )
248 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
257 import Bag ( unitBag, listToBag )
258 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
259 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
261 import qualified ErrUtils
263 import StringBuffer ( StringBuffer, hGetStringBuffer )
266 import Maybes ( expectJust, mapCatMaybes )
268 import HaddockLex ( tokenise )
271 import Control.Concurrent
272 import System.Directory ( getModificationTime, doesFileExist,
273 getCurrentDirectory )
276 import qualified Data.List as List
278 import System.Exit ( exitWith, ExitCode(..) )
279 import System.Time ( ClockTime, getClockTime )
280 import Control.Exception as Exception hiding (handle)
282 import System.FilePath
284 import System.IO.Error ( try, isDoesNotExistError )
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 handle (\exception -> do
301 -- an IO exception probably isn't our fault, so don't panic
303 fatalErrorMsg dflags (text (show exception))
304 AsyncException StackOverflow ->
305 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
307 fatalErrorMsg dflags (text (show (Panic (show exception))))
308 exitWith (ExitFailure 1)
311 -- program errors: messages with locations attached. Sometimes it is
312 -- convenient to just throw these as exceptions.
313 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
314 exitWith (ExitFailure 1)) $
316 -- error messages propagated as exceptions
317 handleDyn (\dyn -> do
320 PhaseFailed _ code -> exitWith code
321 Interrupted -> exitWith (ExitFailure 1)
322 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
323 exitWith (ExitFailure 1)
327 -- | Install a default cleanup handler to remove temporary files
328 -- deposited by a GHC run. This is seperate from
329 -- 'defaultErrorHandler', because you might want to override the error
330 -- handling, but still get the ordinary cleanup behaviour.
331 defaultCleanupHandler :: DynFlags -> IO a -> IO a
332 defaultCleanupHandler dflags inner =
333 -- make sure we clean up after ourselves
334 later (do cleanTempFiles dflags
337 -- exceptions will be blocked while we clean the temporary files,
338 -- so there shouldn't be any difficulty if we receive further
343 -- | Starts a new session. A session consists of a set of loaded
344 -- modules, a set of options (DynFlags), and an interactive context.
345 -- ToDo: explain argument [[mb_top_dir]]
346 newSession :: Maybe FilePath -> IO Session
347 newSession mb_top_dir = do
349 main_thread <- myThreadId
350 modifyMVar_ interruptTargetThread (return . (main_thread :))
351 installSignalHandlers
354 dflags0 <- initSysTools mb_top_dir defaultDynFlags
355 dflags <- initDynFlags dflags0
356 env <- newHscEnv dflags
360 -- tmp: this breaks the abstraction, but required because DriverMkDepend
361 -- needs to call the Finder. ToDo: untangle this.
362 sessionHscEnv :: Session -> IO HscEnv
363 sessionHscEnv (Session ref) = readIORef ref
365 -- -----------------------------------------------------------------------------
368 -- | Grabs the DynFlags from the Session
369 getSessionDynFlags :: Session -> IO DynFlags
370 getSessionDynFlags s = withSession s (return . hsc_dflags)
372 -- | Updates the DynFlags in a Session. This also reads
373 -- the package database (unless it has already been read),
374 -- and prepares the compilers knowledge about packages. It
375 -- can be called again to load new packages: just add new
376 -- package flags to (packageFlags dflags).
378 -- Returns a list of new packages that may need to be linked in using
379 -- the dynamic linker (see 'linkPackages') as a result of new package
380 -- flags. If you are not doing linking or doing static linking, you
381 -- can ignore the list of packages returned.
383 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
384 setSessionDynFlags (Session ref) dflags = do
385 hsc_env <- readIORef ref
386 (dflags', preload) <- initPackages dflags
387 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
390 -- | If there is no -o option, guess the name of target executable
391 -- by using top-level source file name as a base.
392 guessOutputFile :: Session -> IO ()
393 guessOutputFile s = modifySession s $ \env ->
394 let dflags = hsc_dflags env
395 mod_graph = hsc_mod_graph env
396 mainModuleSrcPath, guessedName :: Maybe String
397 mainModuleSrcPath = do
398 let isMain = (== mainModIs dflags) . ms_mod
399 [ms] <- return (filter isMain mod_graph)
400 ml_hs_file (ms_location ms)
401 guessedName = fmap dropExtension mainModuleSrcPath
403 case outputFile dflags of
405 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
407 -- -----------------------------------------------------------------------------
410 -- ToDo: think about relative vs. absolute file paths. And what
411 -- happens when the current directory changes.
413 -- | Sets the targets for this session. Each target may be a module name
414 -- or a filename. The targets correspond to the set of root modules for
415 -- the program\/library. Unloading the current program is achieved by
416 -- setting the current set of targets to be empty, followed by load.
417 setTargets :: Session -> [Target] -> IO ()
418 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
420 -- | returns the current set of targets
421 getTargets :: Session -> IO [Target]
422 getTargets s = withSession s (return . hsc_targets)
424 -- | Add another target
425 addTarget :: Session -> Target -> IO ()
427 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
430 removeTarget :: Session -> TargetId -> IO ()
431 removeTarget s target_id
432 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
434 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
436 -- Attempts to guess what Target a string refers to. This function implements
437 -- the --make/GHCi command-line syntax for filenames:
439 -- - if the string looks like a Haskell source filename, then interpret
441 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
443 -- - otherwise interpret the string as a module name
445 guessTarget :: String -> Maybe Phase -> IO Target
446 guessTarget file (Just phase)
447 = return (Target (TargetFile file (Just phase)) Nothing)
448 guessTarget file Nothing
449 | isHaskellSrcFilename file
450 = return (Target (TargetFile file Nothing) Nothing)
452 = do exists <- doesFileExist hs_file
454 then return (Target (TargetFile hs_file Nothing) Nothing)
456 exists <- doesFileExist lhs_file
458 then return (Target (TargetFile lhs_file Nothing) Nothing)
460 return (Target (TargetModule (mkModuleName file)) Nothing)
462 hs_file = file <.> "hs"
463 lhs_file = file <.> "lhs"
465 -- -----------------------------------------------------------------------------
466 -- Extending the program scope
468 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
469 extendGlobalRdrScope session rdrElts
470 = modifySession session $ \hscEnv ->
471 let global_rdr = hsc_global_rdr_env hscEnv
472 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
474 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
475 setGlobalRdrScope session rdrElts
476 = modifySession session $ \hscEnv ->
477 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
479 extendGlobalTypeScope :: Session -> [Id] -> IO ()
480 extendGlobalTypeScope session ids
481 = modifySession session $ \hscEnv ->
482 let global_type = hsc_global_type_env hscEnv
483 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
485 setGlobalTypeScope :: Session -> [Id] -> IO ()
486 setGlobalTypeScope session ids
487 = modifySession session $ \hscEnv ->
488 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
490 -- -----------------------------------------------------------------------------
491 -- Parsing Haddock comments
493 parseHaddockComment :: String -> Either String (HsDoc RdrName)
494 parseHaddockComment string =
495 case parseHaddockParagraphs (tokenise string) of
499 -- -----------------------------------------------------------------------------
500 -- Loading the program
502 -- Perform a dependency analysis starting from the current targets
503 -- and update the session with the new module graph.
504 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
505 depanal (Session ref) excluded_mods allow_dup_roots = do
506 hsc_env <- readIORef ref
508 dflags = hsc_dflags hsc_env
509 targets = hsc_targets hsc_env
510 old_graph = hsc_mod_graph hsc_env
512 showPass dflags "Chasing dependencies"
513 debugTraceMsg dflags 2 (hcat [
514 text "Chasing modules from: ",
515 hcat (punctuate comma (map pprTarget targets))])
517 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
519 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
524 -- | The result of load.
526 = LoadOk Errors -- ^ all specified targets were loaded successfully.
527 | LoadFailed Errors -- ^ not all modules were loaded.
529 type Errors = [String]
531 data ErrMsg = ErrMsg {
532 errMsgSeverity :: Severity, -- warning, error, etc.
533 errMsgSpans :: [SrcSpan],
534 errMsgShortDoc :: Doc,
535 errMsgExtraInfo :: Doc
541 | LoadUpTo ModuleName
542 | LoadDependenciesOf ModuleName
544 -- | Try to load the program. If a Module is supplied, then just
545 -- attempt to load up to this target. If no Module is supplied,
546 -- then try to load all targets.
547 load :: Session -> LoadHowMuch -> IO SuccessFlag
548 load s@(Session ref) how_much
550 -- Dependency analysis first. Note that this fixes the module graph:
551 -- even if we don't get a fully successful upsweep, the full module
552 -- graph is still retained in the Session. We can tell which modules
553 -- were successfully loaded by inspecting the Session's HPT.
554 mb_graph <- depanal s [] False
556 Just mod_graph -> catchingFailure $ load2 s how_much mod_graph
557 Nothing -> return Failed
558 where catchingFailure f = f `Exception.catch` \e -> do
559 hsc_env <- readIORef ref
560 -- trac #1565 / test ghci021:
561 -- let bindings may explode if we try to use them after
563 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
566 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
567 load2 s@(Session ref) how_much mod_graph = do
569 hsc_env <- readIORef ref
571 let hpt1 = hsc_HPT hsc_env
572 let dflags = hsc_dflags hsc_env
574 -- The "bad" boot modules are the ones for which we have
575 -- B.hs-boot in the module graph, but no B.hs
576 -- The downsweep should have ensured this does not happen
578 let all_home_mods = [ms_mod_name s
579 | s <- mod_graph, not (isBootSummary s)]
580 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
581 not (ms_mod_name s `elem` all_home_mods)]
582 ASSERT( null bad_boot_mods ) return ()
584 -- mg2_with_srcimps drops the hi-boot nodes, returning a
585 -- graph with cycles. Among other things, it is used for
586 -- backing out partially complete cycles following a failed
587 -- upsweep, and for removing from hpt all the modules
588 -- not in strict downwards closure, during calls to compile.
589 let mg2_with_srcimps :: [SCC ModSummary]
590 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
592 -- If we can determine that any of the {-# SOURCE #-} imports
593 -- are definitely unnecessary, then emit a warning.
594 warnUnnecessarySourceImports dflags mg2_with_srcimps
597 -- check the stability property for each module.
598 stable_mods@(stable_obj,stable_bco)
599 = checkStability hpt1 mg2_with_srcimps all_home_mods
601 -- prune bits of the HPT which are definitely redundant now,
603 pruned_hpt = pruneHomePackageTable hpt1
604 (flattenSCCs mg2_with_srcimps)
609 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
610 text "Stable BCO:" <+> ppr stable_bco)
612 -- Unload any modules which are going to be re-linked this time around.
613 let stable_linkables = [ linkable
614 | m <- stable_obj++stable_bco,
615 Just hmi <- [lookupUFM pruned_hpt m],
616 Just linkable <- [hm_linkable hmi] ]
617 unload hsc_env stable_linkables
619 -- We could at this point detect cycles which aren't broken by
620 -- a source-import, and complain immediately, but it seems better
621 -- to let upsweep_mods do this, so at least some useful work gets
622 -- done before the upsweep is abandoned.
623 --hPutStrLn stderr "after tsort:\n"
624 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
626 -- Now do the upsweep, calling compile for each module in
627 -- turn. Final result is version 3 of everything.
629 -- Topologically sort the module graph, this time including hi-boot
630 -- nodes, and possibly just including the portion of the graph
631 -- reachable from the module specified in the 2nd argument to load.
632 -- This graph should be cycle-free.
633 -- If we're restricting the upsweep to a portion of the graph, we
634 -- also want to retain everything that is still stable.
635 let full_mg :: [SCC ModSummary]
636 full_mg = topSortModuleGraph False mod_graph Nothing
638 maybe_top_mod = case how_much of
640 LoadDependenciesOf m -> Just m
643 partial_mg0 :: [SCC ModSummary]
644 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
646 -- LoadDependenciesOf m: we want the upsweep to stop just
647 -- short of the specified module (unless the specified module
650 | LoadDependenciesOf _mod <- how_much
651 = ASSERT( case last partial_mg0 of
652 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
653 List.init partial_mg0
659 | AcyclicSCC ms <- full_mg,
660 ms_mod_name ms `elem` stable_obj++stable_bco,
661 ms_mod_name ms `notElem` [ ms_mod_name ms' |
662 AcyclicSCC ms' <- partial_mg ] ]
664 mg = stable_mg ++ partial_mg
666 -- clean up between compilations
667 let cleanup = cleanTempFilesExcept dflags
668 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
670 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
672 (upsweep_ok, hsc_env1, modsUpswept)
673 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
674 pruned_hpt stable_mods cleanup mg
676 -- Make modsDone be the summaries for each home module now
677 -- available; this should equal the domain of hpt3.
678 -- Get in in a roughly top .. bottom order (hence reverse).
680 let modsDone = reverse modsUpswept
682 -- Try and do linking in some form, depending on whether the
683 -- upsweep was completely or only partially successful.
685 if succeeded upsweep_ok
688 -- Easy; just relink it all.
689 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
691 -- Clean up after ourselves
692 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
694 -- Issue a warning for the confusing case where the user
695 -- said '-o foo' but we're not going to do any linking.
696 -- We attempt linking if either (a) one of the modules is
697 -- called Main, or (b) the user said -no-hs-main, indicating
698 -- that main() is going to come from somewhere else.
700 let ofile = outputFile dflags
701 let no_hs_main = dopt Opt_NoHsMain dflags
703 main_mod = mainModIs dflags
704 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
705 do_linking = a_root_is_Main || no_hs_main
707 when (ghcLink dflags == LinkBinary
708 && isJust ofile && not do_linking) $
709 debugTraceMsg dflags 1 $
710 text ("Warning: output was redirected with -o, " ++
711 "but no output will be generated\n" ++
712 "because there is no " ++
713 moduleNameString (moduleName main_mod) ++ " module.")
715 -- link everything together
716 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
718 loadFinish Succeeded linkresult ref hsc_env1
721 -- Tricky. We need to back out the effects of compiling any
722 -- half-done cycles, both so as to clean up the top level envs
723 -- and to avoid telling the interactive linker to link them.
724 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
727 = map ms_mod modsDone
728 let mods_to_zap_names
729 = findPartiallyCompletedCycles modsDone_names
732 = filter ((`notElem` mods_to_zap_names).ms_mod)
735 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
738 -- Clean up after ourselves
739 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
741 -- there should be no Nothings where linkables should be, now
742 ASSERT(all (isJust.hm_linkable)
743 (eltsUFM (hsc_HPT hsc_env))) do
745 -- Link everything together
746 linkresult <- link (ghcLink dflags) dflags False hpt4
748 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
749 loadFinish Failed linkresult ref hsc_env4
751 -- Finish up after a load.
753 -- If the link failed, unload everything and return.
754 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
755 loadFinish _all_ok Failed ref hsc_env
756 = do unload hsc_env []
757 writeIORef ref $! discardProg hsc_env
760 -- Empty the interactive context and set the module context to the topmost
761 -- newly loaded module, or the Prelude if none were loaded.
762 loadFinish all_ok Succeeded ref hsc_env
763 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
767 -- Forget the current program, but retain the persistent info in HscEnv
768 discardProg :: HscEnv -> HscEnv
770 = hsc_env { hsc_mod_graph = emptyMG,
771 hsc_IC = emptyInteractiveContext,
772 hsc_HPT = emptyHomePackageTable }
774 -- used to fish out the preprocess output files for the purposes of
775 -- cleaning up. The preprocessed file *might* be the same as the
776 -- source file, but that doesn't do any harm.
777 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
778 ppFilesFromSummaries summaries = map ms_hspp_file summaries
780 -- -----------------------------------------------------------------------------
784 CheckedModule { parsedSource :: ParsedSource,
785 renamedSource :: Maybe RenamedSource,
786 typecheckedSource :: Maybe TypecheckedSource,
787 checkedModuleInfo :: Maybe ModuleInfo,
788 coreModule :: Maybe ModGuts
790 -- ToDo: improvements that could be made here:
791 -- if the module succeeded renaming but not typechecking,
792 -- we can still get back the GlobalRdrEnv and exports, so
793 -- perhaps the ModuleInfo should be split up into separate
794 -- fields within CheckedModule.
796 type ParsedSource = Located (HsModule RdrName)
797 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
798 Maybe (HsDoc Name), HaddockModInfo Name)
799 type TypecheckedSource = LHsBinds Id
802 -- - things that aren't in the output of the typechecker right now:
806 -- - type/data/newtype declarations
807 -- - class declarations
809 -- - extra things in the typechecker's output:
810 -- - default methods are turned into top-level decls.
811 -- - dictionary bindings
814 -- | This is the way to get access to parsed and typechecked source code
815 -- for a module. 'checkModule' attempts to typecheck the module. If
816 -- successful, it returns the abstract syntax for the module.
817 -- If compileToCore is true, it also desugars the module and returns the
818 -- resulting Core bindings as a component of the CheckedModule.
819 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
820 checkModule (Session ref) mod compile_to_core
822 hsc_env <- readIORef ref
823 let mg = hsc_mod_graph hsc_env
824 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
826 (ms:_) -> checkModule_ ref ms compile_to_core False
828 -- | parses and typechecks a module, optionally generates Core, and also
829 -- loads the module into the 'Session' so that modules which depend on
830 -- this one may subsequently be typechecked using 'checkModule' or
831 -- 'checkAndLoadModule'. If you need to check more than one module,
832 -- you probably want to use 'checkAndLoadModule'. Constructing the
833 -- interface takes a little work, so it might be slightly slower than
835 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
836 checkAndLoadModule (Session ref) ms compile_to_core
837 = checkModule_ ref ms compile_to_core True
839 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
840 -> IO (Maybe CheckedModule)
841 checkModule_ ref ms compile_to_core load
843 let mod = ms_mod_name ms
844 hsc_env0 <- readIORef ref
845 let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
846 mb_parsed <- parseFile hsc_env ms
848 Nothing -> return Nothing
849 Just rdr_module -> do
850 mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
851 case mb_typechecked of
852 Nothing -> return (Just CheckedModule {
853 parsedSource = rdr_module,
854 renamedSource = Nothing,
855 typecheckedSource = Nothing,
856 checkedModuleInfo = Nothing,
857 coreModule = Nothing })
858 Just (tcg, rn_info) -> do
859 details <- makeSimpleDetails hsc_env tcg
861 let tc_binds = tcg_binds tcg
862 let rdr_env = tcg_rdr_env tcg
863 let minf = ModuleInfo {
864 minf_type_env = md_types details,
865 minf_exports = availsToNameSet $
867 minf_rdr_env = Just rdr_env,
868 minf_instances = md_insts details
870 ,minf_modBreaks = emptyModBreaks
874 mb_guts <- if compile_to_core
875 then deSugarModule hsc_env ms tcg
878 -- If we are loading this module so that we can typecheck
879 -- dependent modules, generate an interface and stuff it
880 -- all in the HomePackageTable.
882 (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
883 let mod_info = HomeModInfo {
885 hm_details = details,
886 hm_linkable = Nothing }
887 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
888 writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
890 return (Just (CheckedModule {
891 parsedSource = rdr_module,
892 renamedSource = rn_info,
893 typecheckedSource = Just tc_binds,
894 checkedModuleInfo = Just minf,
895 coreModule = mb_guts }))
897 -- | This is the way to get access to the Core bindings corresponding
898 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
899 -- desugar the module, then returns the resulting Core module (consisting of
900 -- the module name, type declarations, and function declarations) if
902 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
903 compileToCoreModule = compileCore False
905 -- | Like compileToCoreModule, but invokes the simplifier, so
906 -- as to return simplified and tidied Core.
907 compileToCoreSimplified :: Session -> FilePath -> IO (Maybe CoreModule)
908 compileToCoreSimplified = compileCore True
910 -- | Provided for backwards-compatibility: compileToCore returns just the Core
911 -- bindings, but for most purposes, you probably want to call
912 -- compileToCoreModule.
913 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
914 compileToCore session fn = do
915 maybeCoreModule <- compileToCoreModule session fn
916 return $ fmap cm_binds maybeCoreModule
918 -- | Takes a CoreModule and compiles the bindings therein
919 -- to object code. The first argument is a bool flag indicating
920 -- whether to run the simplifier.
921 -- The resulting .o, .hi, and executable files, if any, are stored in the
922 -- current directory, and named according to the module name.
923 -- Returns True iff compilation succeeded.
924 -- This has only so far been tested with a single self-contained module.
925 compileCoreToObj :: Bool -> Session -> CoreModule -> IO Bool
926 compileCoreToObj simplify session cm@(CoreModule{ cm_module = mName }) = do
927 hscEnv <- sessionHscEnv session
928 dflags <- getSessionDynFlags session
929 currentTime <- getClockTime
930 cwd <- getCurrentDirectory
931 modLocation <- mkHiOnlyModLocation dflags (hiSuf dflags) cwd
932 ((moduleNameSlashes . moduleName) mName)
934 let modSummary = ModSummary { ms_mod = mName,
935 ms_hsc_src = ExtCoreFile,
936 ms_location = modLocation,
937 -- By setting the object file timestamp to Nothing,
938 -- we always force recompilation, which is what we
939 -- want. (Thus it doesn't matter what the timestamp
940 -- for the (nonexistent) source file is.)
941 ms_hs_date = currentTime,
942 ms_obj_date = Nothing,
943 -- Only handling the single-module case for now, so no imports.
948 ms_hspp_opts = dflags,
949 ms_hspp_buf = Nothing
952 mbHscResult <- evalComp
953 ((if simplify then hscSimplify else return) (mkModGuts cm)
954 >>= hscNormalIface >>= hscWriteIface >>= hscOneShot)
955 (CompState{ compHscEnv=hscEnv,
956 compModSummary=modSummary,
957 compOldIface=Nothing})
958 return $ isJust mbHscResult
960 -- Makes a "vanilla" ModGuts.
961 mkModGuts :: CoreModule -> ModGuts
962 mkModGuts coreModule = ModGuts {
963 mg_module = cm_module coreModule,
966 mg_deps = noDependencies,
967 mg_dir_imps = emptyModuleEnv,
968 mg_used_names = emptyNameSet,
969 mg_rdr_env = emptyGlobalRdrEnv,
970 mg_fix_env = emptyFixityEnv,
971 mg_types = emptyTypeEnv,
975 mg_binds = cm_binds coreModule,
976 mg_foreign = NoStubs,
977 mg_deprecs = NoDeprecs,
978 mg_hpc_info = emptyHpcInfo False,
979 mg_modBreaks = emptyModBreaks,
980 mg_vect_info = noVectInfo,
981 mg_inst_env = emptyInstEnv,
982 mg_fam_inst_env = emptyFamInstEnv
985 compileCore :: Bool -> Session -> FilePath -> IO (Maybe CoreModule)
986 compileCore simplify session fn = do
987 -- First, set the target to the desired filename
988 target <- guessTarget fn Nothing
989 addTarget session target
990 load session LoadAllTargets
991 -- Then find dependencies
992 maybeModGraph <- depanal session [] True
993 case maybeModGraph of
994 Nothing -> return Nothing
996 case find ((== fn) . msHsFilePath) modGraph of
997 Just modSummary -> do
998 -- Now we have the module name;
999 -- parse, typecheck and desugar the module
1000 let mod = ms_mod_name modSummary
1001 maybeCheckedModule <- checkModule session mod True
1002 case maybeCheckedModule of
1003 Nothing -> return Nothing
1004 Just checkedMod -> (liftM $ fmap gutsToCoreModule) $
1005 case (coreModule checkedMod) of
1006 Just mg | simplify -> (sessionHscEnv session)
1007 -- If simplify is true: simplify (hscSimplify),
1008 -- then tidy (tidyProgram).
1009 >>= \ hscEnv -> evalComp (hscSimplify mg)
1010 (CompState{ compHscEnv=hscEnv,
1011 compModSummary=modSummary,
1012 compOldIface=Nothing})
1013 >>= (tidyProgram hscEnv)
1014 >>= (return . Just . Left)
1015 Just guts -> return $ Just $ Right guts
1016 Nothing -> return Nothing
1017 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1018 module dependency graph"
1019 where -- two versions, based on whether we simplify (thus run tidyProgram,
1020 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1021 -- we just have a ModGuts.
1022 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1023 gutsToCoreModule (Left (cg, md)) = CoreModule {
1024 cm_module = cg_module cg, cm_types = md_types md,
1025 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1027 gutsToCoreModule (Right mg) = CoreModule {
1028 cm_module = mg_module mg, cm_types = mg_types mg,
1029 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1032 -- ---------------------------------------------------------------------------
1035 unload :: HscEnv -> [Linkable] -> IO ()
1036 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1037 = case ghcLink (hsc_dflags hsc_env) of
1039 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1041 LinkInMemory -> panic "unload: no interpreter"
1042 -- urgh. avoid warnings:
1043 hsc_env stable_linkables
1047 -- -----------------------------------------------------------------------------
1051 Stability tells us which modules definitely do not need to be recompiled.
1052 There are two main reasons for having stability:
1054 - avoid doing a complete upsweep of the module graph in GHCi when
1055 modules near the bottom of the tree have not changed.
1057 - to tell GHCi when it can load object code: we can only load object code
1058 for a module when we also load object code fo all of the imports of the
1059 module. So we need to know that we will definitely not be recompiling
1060 any of these modules, and we can use the object code.
1062 The stability check is as follows. Both stableObject and
1063 stableBCO are used during the upsweep phase later.
1066 stable m = stableObject m || stableBCO m
1069 all stableObject (imports m)
1070 && old linkable does not exist, or is == on-disk .o
1071 && date(on-disk .o) > date(.hs)
1074 all stable (imports m)
1075 && date(BCO) > date(.hs)
1078 These properties embody the following ideas:
1080 - if a module is stable, then:
1081 - if it has been compiled in a previous pass (present in HPT)
1082 then it does not need to be compiled or re-linked.
1083 - if it has not been compiled in a previous pass,
1084 then we only need to read its .hi file from disk and
1085 link it to produce a ModDetails.
1087 - if a modules is not stable, we will definitely be at least
1088 re-linking, and possibly re-compiling it during the upsweep.
1089 All non-stable modules can (and should) therefore be unlinked
1092 - Note that objects are only considered stable if they only depend
1093 on other objects. We can't link object code against byte code.
1097 :: HomePackageTable -- HPT from last compilation
1098 -> [SCC ModSummary] -- current module graph (cyclic)
1099 -> [ModuleName] -- all home modules
1100 -> ([ModuleName], -- stableObject
1101 [ModuleName]) -- stableBCO
1103 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1105 checkSCC (stable_obj, stable_bco) scc0
1106 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1107 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1108 | otherwise = (stable_obj, stable_bco)
1110 scc = flattenSCC scc0
1111 scc_mods = map ms_mod_name scc
1112 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1114 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1115 -- all imports outside the current SCC, but in the home pkg
1117 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1118 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1122 && all object_ok scc
1125 and (zipWith (||) stable_obj_imps stable_bco_imps)
1129 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1133 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1134 Just hmi | Just l <- hm_linkable hmi
1135 -> isObjectLinkable l && t == linkableTime l
1137 -- why '>=' rather than '>' above? If the filesystem stores
1138 -- times to the nearset second, we may occasionally find that
1139 -- the object & source have the same modification time,
1140 -- especially if the source was automatically generated
1141 -- and compiled. Using >= is slightly unsafe, but it matches
1142 -- make's behaviour.
1145 = case lookupUFM hpt (ms_mod_name ms) of
1146 Just hmi | Just l <- hm_linkable hmi ->
1147 not (isObjectLinkable l) &&
1148 linkableTime l >= ms_hs_date ms
1151 ms_allimps :: ModSummary -> [ModuleName]
1152 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1154 -- -----------------------------------------------------------------------------
1155 -- Prune the HomePackageTable
1157 -- Before doing an upsweep, we can throw away:
1159 -- - For non-stable modules:
1160 -- - all ModDetails, all linked code
1161 -- - all unlinked code that is out of date with respect to
1164 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1165 -- space at the end of the upsweep, because the topmost ModDetails of the
1166 -- old HPT holds on to the entire type environment from the previous
1169 pruneHomePackageTable
1172 -> ([ModuleName],[ModuleName])
1175 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1178 | is_stable modl = hmi'
1179 | otherwise = hmi'{ hm_details = emptyModDetails }
1181 modl = moduleName (mi_module (hm_iface hmi))
1182 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1183 = hmi{ hm_linkable = Nothing }
1186 where ms = expectJust "prune" (lookupUFM ms_map modl)
1188 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1190 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1192 -- -----------------------------------------------------------------------------
1194 -- Return (names of) all those in modsDone who are part of a cycle
1195 -- as defined by theGraph.
1196 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1197 findPartiallyCompletedCycles modsDone theGraph
1201 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1202 chew ((CyclicSCC vs):rest)
1203 = let names_in_this_cycle = nub (map ms_mod vs)
1205 = nub ([done | done <- modsDone,
1206 done `elem` names_in_this_cycle])
1207 chewed_rest = chew rest
1209 if notNull mods_in_this_cycle
1210 && length mods_in_this_cycle < length names_in_this_cycle
1211 then mods_in_this_cycle ++ chewed_rest
1214 -- -----------------------------------------------------------------------------
1217 -- This is where we compile each module in the module graph, in a pass
1218 -- from the bottom to the top of the graph.
1220 -- There better had not be any cyclic groups here -- we check for them.
1223 :: HscEnv -- Includes initially-empty HPT
1224 -> HomePackageTable -- HPT from last time round (pruned)
1225 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1226 -> IO () -- How to clean up unwanted tmp files
1227 -> [SCC ModSummary] -- Mods to do (the worklist)
1229 HscEnv, -- With an updated HPT
1230 [ModSummary]) -- Mods which succeeded
1232 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1233 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1234 return (res, hsc_env, reverse done)
1237 upsweep' hsc_env _old_hpt done
1239 = return (Succeeded, hsc_env, done)
1241 upsweep' hsc_env _old_hpt done
1242 (CyclicSCC ms:_) _ _
1243 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1244 return (Failed, hsc_env, done)
1246 upsweep' hsc_env old_hpt done
1247 (AcyclicSCC mod:mods) mod_index nmods
1248 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1249 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1250 -- (moduleEnvElts (hsc_HPT hsc_env)))
1252 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1255 cleanup -- Remove unwanted tmp files between compilations
1258 Nothing -> return (Failed, hsc_env, done)
1260 let this_mod = ms_mod_name mod
1262 -- Add new info to hsc_env
1263 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1264 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1266 -- Space-saving: delete the old HPT entry
1267 -- for mod BUT if mod is a hs-boot
1268 -- node, don't delete it. For the
1269 -- interface, the HPT entry is probaby for the
1270 -- main Haskell source file. Deleting it
1271 -- would force the real module to be recompiled
1273 old_hpt1 | isBootSummary mod = old_hpt
1274 | otherwise = delFromUFM old_hpt this_mod
1278 -- fixup our HomePackageTable after we've finished compiling
1279 -- a mutually-recursive loop. See reTypecheckLoop, below.
1280 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1282 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1285 -- Compile a single module. Always produce a Linkable for it if
1286 -- successful. If no compilation happened, return the old Linkable.
1287 upsweep_mod :: HscEnv
1289 -> ([ModuleName],[ModuleName])
1291 -> Int -- index of module
1292 -> Int -- total number of modules
1293 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1295 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1297 this_mod_name = ms_mod_name summary
1298 this_mod = ms_mod summary
1299 mb_obj_date = ms_obj_date summary
1300 obj_fn = ml_obj_file (ms_location summary)
1301 hs_date = ms_hs_date summary
1303 is_stable_obj = this_mod_name `elem` stable_obj
1304 is_stable_bco = this_mod_name `elem` stable_bco
1306 old_hmi = lookupUFM old_hpt this_mod_name
1308 -- We're using the dflags for this module now, obtained by
1309 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1310 dflags = ms_hspp_opts summary
1311 prevailing_target = hscTarget (hsc_dflags hsc_env)
1312 local_target = hscTarget dflags
1314 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1315 -- we don't do anything dodgy: these should only work to change
1316 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1317 -- end up trying to link object code to byte code.
1318 target = if prevailing_target /= local_target
1319 && (not (isObjectTarget prevailing_target)
1320 || not (isObjectTarget local_target))
1321 then prevailing_target
1324 -- store the corrected hscTarget into the summary
1325 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1327 -- The old interface is ok if
1328 -- a) we're compiling a source file, and the old HPT
1329 -- entry is for a source file
1330 -- b) we're compiling a hs-boot file
1331 -- Case (b) allows an hs-boot file to get the interface of its
1332 -- real source file on the second iteration of the compilation
1333 -- manager, but that does no harm. Otherwise the hs-boot file
1334 -- will always be recompiled
1339 Just hm_info | isBootSummary summary -> Just iface
1340 | not (mi_boot iface) -> Just iface
1341 | otherwise -> Nothing
1343 iface = hm_iface hm_info
1345 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1346 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1348 compile_it_discard_iface
1349 = compile hsc_env summary' mod_index nmods Nothing
1355 -- Regardless of whether we're generating object code or
1356 -- byte code, we can always use an existing object file
1357 -- if it is *stable* (see checkStability).
1358 | is_stable_obj, isJust old_hmi ->
1360 -- object is stable, and we have an entry in the
1361 -- old HPT: nothing to do
1363 | is_stable_obj, isNothing old_hmi -> do
1364 linkable <- findObjectLinkable this_mod obj_fn
1365 (expectJust "upseep1" mb_obj_date)
1366 compile_it (Just linkable)
1367 -- object is stable, but we need to load the interface
1368 -- off disk to make a HMI.
1372 ASSERT(isJust old_hmi) -- must be in the old_hpt
1374 -- BCO is stable: nothing to do
1376 | Just hmi <- old_hmi,
1377 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1378 linkableTime l >= ms_hs_date summary ->
1380 -- we have an old BCO that is up to date with respect
1381 -- to the source: do a recompilation check as normal.
1385 -- no existing code at all: we must recompile.
1387 -- When generating object code, if there's an up-to-date
1388 -- object file on the disk, then we can use it.
1389 -- However, if the object file is new (compared to any
1390 -- linkable we had from a previous compilation), then we
1391 -- must discard any in-memory interface, because this
1392 -- means the user has compiled the source file
1393 -- separately and generated a new interface, that we must
1394 -- read from the disk.
1396 obj | isObjectTarget obj,
1397 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1400 | Just l <- hm_linkable hmi,
1401 isObjectLinkable l && linkableTime l == obj_date
1402 -> compile_it (Just l)
1404 linkable <- findObjectLinkable this_mod obj_fn obj_date
1405 compile_it_discard_iface (Just linkable)
1412 -- Filter modules in the HPT
1413 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1414 retainInTopLevelEnvs keep_these hpt
1415 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1417 , let mb_mod_info = lookupUFM hpt mod
1418 , isJust mb_mod_info ]
1420 -- ---------------------------------------------------------------------------
1421 -- Typecheck module loops
1424 See bug #930. This code fixes a long-standing bug in --make. The
1425 problem is that when compiling the modules *inside* a loop, a data
1426 type that is only defined at the top of the loop looks opaque; but
1427 after the loop is done, the structure of the data type becomes
1430 The difficulty is then that two different bits of code have
1431 different notions of what the data type looks like.
1433 The idea is that after we compile a module which also has an .hs-boot
1434 file, we re-generate the ModDetails for each of the modules that
1435 depends on the .hs-boot file, so that everyone points to the proper
1436 TyCons, Ids etc. defined by the real module, not the boot module.
1437 Fortunately re-generating a ModDetails from a ModIface is easy: the
1438 function TcIface.typecheckIface does exactly that.
1440 Picking the modules to re-typecheck is slightly tricky. Starting from
1441 the module graph consisting of the modules that have already been
1442 compiled, we reverse the edges (so they point from the imported module
1443 to the importing module), and depth-first-search from the .hs-boot
1444 node. This gives us all the modules that depend transitively on the
1445 .hs-boot module, and those are exactly the modules that we need to
1448 Following this fix, GHC can compile itself with --make -O2.
1451 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1452 reTypecheckLoop hsc_env ms graph
1453 | not (isBootSummary ms) &&
1454 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1456 let mss = reachableBackwards (ms_mod_name ms) graph
1457 non_boot = filter (not.isBootSummary) mss
1458 debugTraceMsg (hsc_dflags hsc_env) 2 $
1459 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1460 typecheckLoop hsc_env (map ms_mod_name non_boot)
1464 this_mod = ms_mod ms
1466 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1467 typecheckLoop hsc_env mods = do
1469 fixIO $ \new_hpt -> do
1470 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1471 mds <- initIfaceCheck new_hsc_env $
1472 mapM (typecheckIface . hm_iface) hmis
1473 let new_hpt = addListToUFM old_hpt
1474 (zip mods [ hmi{ hm_details = details }
1475 | (hmi,details) <- zip hmis mds ])
1477 return hsc_env{ hsc_HPT = new_hpt }
1479 old_hpt = hsc_HPT hsc_env
1480 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1482 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1483 reachableBackwards mod summaries
1484 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1486 -- all the nodes reachable by traversing the edges backwards
1487 -- from the root node:
1488 nodes_we_want = reachable (transposeG graph) root
1490 -- the rest just sets up the graph:
1491 (nodes, lookup_key) = moduleGraphNodes False summaries
1492 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1494 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1495 | otherwise = panic "reachableBackwards"
1497 -- ---------------------------------------------------------------------------
1498 -- Topological sort of the module graph
1501 :: Bool -- Drop hi-boot nodes? (see below)
1505 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1506 -- The resulting list of strongly-connected-components is in topologically
1507 -- sorted order, starting with the module(s) at the bottom of the
1508 -- dependency graph (ie compile them first) and ending with the ones at
1511 -- Drop hi-boot nodes (first boolean arg)?
1513 -- False: treat the hi-boot summaries as nodes of the graph,
1514 -- so the graph must be acyclic
1516 -- True: eliminate the hi-boot nodes, and instead pretend
1517 -- the a source-import of Foo is an import of Foo
1518 -- The resulting graph has no hi-boot nodes, but can by cyclic
1520 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1521 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1522 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1523 = stronglyConnComp (map vertex_fn (reachable graph root))
1525 -- restrict the graph to just those modules reachable from
1526 -- the specified module. We do this by building a graph with
1527 -- the full set of nodes, and determining the reachable set from
1528 -- the specified node.
1529 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1530 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1532 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1533 | otherwise = throwDyn (ProgramError "module does not exist")
1535 moduleGraphNodes :: Bool -> [ModSummary]
1536 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1537 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1539 -- Drop hs-boot nodes by using HsSrcFile as the key
1540 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1541 | otherwise = HsBootFile
1543 -- We use integers as the keys for the SCC algorithm
1544 nodes :: [(ModSummary, Int, [Int])]
1545 nodes = [(s, expectJust "topSort" $
1546 lookup_key (ms_hsc_src s) (ms_mod_name s),
1547 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1548 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1549 (-- see [boot-edges] below
1550 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1552 else case lookup_key HsBootFile (ms_mod_name s) of
1557 , not (isBootSummary s && drop_hs_boot_nodes) ]
1558 -- Drop the hi-boot ones if told to do so
1560 -- [boot-edges] if this is a .hs and there is an equivalent
1561 -- .hs-boot, add a link from the former to the latter. This
1562 -- has the effect of detecting bogus cases where the .hs-boot
1563 -- depends on the .hs, by introducing a cycle. Additionally,
1564 -- it ensures that we will always process the .hs-boot before
1565 -- the .hs, and so the HomePackageTable will always have the
1566 -- most up to date information.
1568 key_map :: NodeMap Int
1569 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1573 lookup_key :: HscSource -> ModuleName -> Maybe Int
1574 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1576 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1577 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1578 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1579 -- the IsBootInterface parameter True; else False
1582 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1583 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1585 msKey :: ModSummary -> NodeKey
1586 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1588 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1589 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1591 nodeMapElts :: NodeMap a -> [a]
1592 nodeMapElts = eltsFM
1594 -- If there are {-# SOURCE #-} imports between strongly connected
1595 -- components in the topological sort, then those imports can
1596 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1597 -- were necessary, then the edge would be part of a cycle.
1598 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1599 warnUnnecessarySourceImports dflags sccs =
1600 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1602 let mods_in_this_cycle = map ms_mod_name ms in
1603 [ warn i | m <- ms, i <- ms_srcimps m,
1604 unLoc i `notElem` mods_in_this_cycle ]
1606 warn :: Located ModuleName -> WarnMsg
1609 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1610 <+> quotes (ppr mod))
1612 -----------------------------------------------------------------------------
1613 -- Downsweep (dependency analysis)
1615 -- Chase downwards from the specified root set, returning summaries
1616 -- for all home modules encountered. Only follow source-import
1619 -- We pass in the previous collection of summaries, which is used as a
1620 -- cache to avoid recalculating a module summary if the source is
1623 -- The returned list of [ModSummary] nodes has one node for each home-package
1624 -- module, plus one for any hs-boot files. The imports of these nodes
1625 -- are all there, including the imports of non-home-package modules.
1628 -> [ModSummary] -- Old summaries
1629 -> [ModuleName] -- Ignore dependencies on these; treat
1630 -- them as if they were package modules
1631 -> Bool -- True <=> allow multiple targets to have
1632 -- the same module name; this is
1633 -- very useful for ghc -M
1634 -> IO (Maybe [ModSummary])
1635 -- The elts of [ModSummary] all have distinct
1636 -- (Modules, IsBoot) identifiers, unless the Bool is true
1637 -- in which case there can be repeats
1638 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1639 = -- catch error messages and return them
1640 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1641 rootSummaries <- mapM getRootSummary roots
1642 let root_map = mkRootMap rootSummaries
1643 checkDuplicates root_map
1644 summs <- loop (concatMap msDeps rootSummaries) root_map
1647 roots = hsc_targets hsc_env
1649 old_summary_map :: NodeMap ModSummary
1650 old_summary_map = mkNodeMap old_summaries
1652 getRootSummary :: Target -> IO ModSummary
1653 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1654 = do exists <- doesFileExist file
1656 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1657 else throwDyn $ mkPlainErrMsg noSrcSpan $
1658 text "can't find file:" <+> text file
1659 getRootSummary (Target (TargetModule modl) maybe_buf)
1660 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1661 (L rootLoc modl) maybe_buf excl_mods
1662 case maybe_summary of
1663 Nothing -> packageModErr modl
1666 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1668 -- In a root module, the filename is allowed to diverge from the module
1669 -- name, so we have to check that there aren't multiple root files
1670 -- defining the same module (otherwise the duplicates will be silently
1671 -- ignored, leading to confusing behaviour).
1672 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1673 checkDuplicates root_map
1674 | allow_dup_roots = return ()
1675 | null dup_roots = return ()
1676 | otherwise = multiRootsErr (head dup_roots)
1678 dup_roots :: [[ModSummary]] -- Each at least of length 2
1679 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1681 loop :: [(Located ModuleName,IsBootInterface)]
1682 -- Work list: process these modules
1683 -> NodeMap [ModSummary]
1684 -- Visited set; the range is a list because
1685 -- the roots can have the same module names
1686 -- if allow_dup_roots is True
1688 -- The result includes the worklist, except
1689 -- for those mentioned in the visited set
1690 loop [] done = return (concat (nodeMapElts done))
1691 loop ((wanted_mod, is_boot) : ss) done
1692 | Just summs <- lookupFM done key
1693 = if isSingleton summs then
1696 do { multiRootsErr summs; return [] }
1697 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1698 is_boot wanted_mod Nothing excl_mods
1700 Nothing -> loop ss done
1701 Just s -> loop (msDeps s ++ ss)
1702 (addToFM done key [s]) }
1704 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1706 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1707 mkRootMap summaries = addListToFM_C (++) emptyFM
1708 [ (msKey s, [s]) | s <- summaries ]
1710 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1711 -- (msDeps s) returns the dependencies of the ModSummary s.
1712 -- A wrinkle is that for a {-# SOURCE #-} import we return
1713 -- *both* the hs-boot file
1714 -- *and* the source file
1715 -- as "dependencies". That ensures that the list of all relevant
1716 -- modules always contains B.hs if it contains B.hs-boot.
1717 -- Remember, this pass isn't doing the topological sort. It's
1718 -- just gathering the list of all relevant ModSummaries
1720 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1721 ++ [ (m,False) | m <- ms_imps s ]
1723 -----------------------------------------------------------------------------
1724 -- Summarising modules
1726 -- We have two types of summarisation:
1728 -- * Summarise a file. This is used for the root module(s) passed to
1729 -- cmLoadModules. The file is read, and used to determine the root
1730 -- module name. The module name may differ from the filename.
1732 -- * Summarise a module. We are given a module name, and must provide
1733 -- a summary. The finder is used to locate the file in which the module
1738 -> [ModSummary] -- old summaries
1739 -> FilePath -- source file name
1740 -> Maybe Phase -- start phase
1741 -> Maybe (StringBuffer,ClockTime)
1744 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1745 -- we can use a cached summary if one is available and the
1746 -- source file hasn't changed, But we have to look up the summary
1747 -- by source file, rather than module name as we do in summarise.
1748 | Just old_summary <- findSummaryBySourceFile old_summaries file
1750 let location = ms_location old_summary
1752 -- return the cached summary if the source didn't change
1753 src_timestamp <- case maybe_buf of
1754 Just (_,t) -> return t
1755 Nothing -> getModificationTime file
1756 -- The file exists; we checked in getRootSummary above.
1757 -- If it gets removed subsequently, then this
1758 -- getModificationTime may fail, but that's the right
1761 if ms_hs_date old_summary == src_timestamp
1762 then do -- update the object-file timestamp
1763 obj_timestamp <- getObjTimestamp location False
1764 return old_summary{ ms_obj_date = obj_timestamp }
1772 let dflags = hsc_dflags hsc_env
1774 (dflags', hspp_fn, buf)
1775 <- preprocessFile dflags file mb_phase maybe_buf
1777 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1779 -- Make a ModLocation for this file
1780 location <- mkHomeModLocation dflags mod_name file
1782 -- Tell the Finder cache where it is, so that subsequent calls
1783 -- to findModule will find it, even if it's not on any search path
1784 mod <- addHomeModuleToFinder hsc_env mod_name location
1786 src_timestamp <- case maybe_buf of
1787 Just (_,t) -> return t
1788 Nothing -> getModificationTime file
1789 -- getMofificationTime may fail
1791 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1793 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1794 ms_location = location,
1795 ms_hspp_file = hspp_fn,
1796 ms_hspp_opts = dflags',
1797 ms_hspp_buf = Just buf,
1798 ms_srcimps = srcimps, ms_imps = the_imps,
1799 ms_hs_date = src_timestamp,
1800 ms_obj_date = obj_timestamp })
1802 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1803 findSummaryBySourceFile summaries file
1804 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1805 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1809 -- Summarise a module, and pick up source and timestamp.
1812 -> NodeMap ModSummary -- Map of old summaries
1813 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1814 -> Located ModuleName -- Imported module to be summarised
1815 -> Maybe (StringBuffer, ClockTime)
1816 -> [ModuleName] -- Modules to exclude
1817 -> IO (Maybe ModSummary) -- Its new summary
1819 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1820 | wanted_mod `elem` excl_mods
1823 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1824 = do -- Find its new timestamp; all the
1825 -- ModSummaries in the old map have valid ml_hs_files
1826 let location = ms_location old_summary
1827 src_fn = expectJust "summariseModule" (ml_hs_file location)
1829 -- check the modification time on the source file, and
1830 -- return the cached summary if it hasn't changed. If the
1831 -- file has disappeared, we need to call the Finder again.
1833 Just (_,t) -> check_timestamp old_summary location src_fn t
1835 m <- System.IO.Error.try (getModificationTime src_fn)
1837 Right t -> check_timestamp old_summary location src_fn t
1838 Left e | isDoesNotExistError e -> find_it
1839 | otherwise -> ioError e
1841 | otherwise = find_it
1843 dflags = hsc_dflags hsc_env
1845 hsc_src = if is_boot then HsBootFile else HsSrcFile
1847 check_timestamp old_summary location src_fn src_timestamp
1848 | ms_hs_date old_summary == src_timestamp = do
1849 -- update the object-file timestamp
1850 obj_timestamp <- getObjTimestamp location is_boot
1851 return (Just old_summary{ ms_obj_date = obj_timestamp })
1853 -- source changed: re-summarise.
1854 new_summary location (ms_mod old_summary) src_fn src_timestamp
1857 -- Don't use the Finder's cache this time. If the module was
1858 -- previously a package module, it may have now appeared on the
1859 -- search path, so we want to consider it to be a home module. If
1860 -- the module was previously a home module, it may have moved.
1861 uncacheModule hsc_env wanted_mod
1862 found <- findImportedModule hsc_env wanted_mod Nothing
1865 | isJust (ml_hs_file location) ->
1867 just_found location mod
1869 -- Drop external-pkg
1870 ASSERT(modulePackageId mod /= thisPackage dflags)
1874 err -> noModError dflags loc wanted_mod err
1877 just_found location mod = do
1878 -- Adjust location to point to the hs-boot source file,
1879 -- hi file, object file, when is_boot says so
1880 let location' | is_boot = addBootSuffixLocn location
1881 | otherwise = location
1882 src_fn = expectJust "summarise2" (ml_hs_file location')
1884 -- Check that it exists
1885 -- It might have been deleted since the Finder last found it
1886 maybe_t <- modificationTimeIfExists src_fn
1888 Nothing -> noHsFileErr loc src_fn
1889 Just t -> new_summary location' mod src_fn t
1892 new_summary location mod src_fn src_timestamp
1894 -- Preprocess the source file and get its imports
1895 -- The dflags' contains the OPTIONS pragmas
1896 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1897 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1899 when (mod_name /= wanted_mod) $
1900 throwDyn $ mkPlainErrMsg mod_loc $
1901 text "File name does not match module name:"
1902 $$ text "Saw:" <+> quotes (ppr mod_name)
1903 $$ text "Expected:" <+> quotes (ppr wanted_mod)
1905 -- Find the object timestamp, and return the summary
1906 obj_timestamp <- getObjTimestamp location is_boot
1908 return (Just ( ModSummary { ms_mod = mod,
1909 ms_hsc_src = hsc_src,
1910 ms_location = location,
1911 ms_hspp_file = hspp_fn,
1912 ms_hspp_opts = dflags',
1913 ms_hspp_buf = Just buf,
1914 ms_srcimps = srcimps,
1916 ms_hs_date = src_timestamp,
1917 ms_obj_date = obj_timestamp }))
1920 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1921 getObjTimestamp location is_boot
1922 = if is_boot then return Nothing
1923 else modificationTimeIfExists (ml_obj_file location)
1926 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1927 -> IO (DynFlags, FilePath, StringBuffer)
1928 preprocessFile dflags src_fn mb_phase Nothing
1930 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1931 buf <- hGetStringBuffer hspp_fn
1932 return (dflags', hspp_fn, buf)
1934 preprocessFile dflags src_fn mb_phase (Just (buf, _time))
1936 -- case we bypass the preprocessing stage?
1938 local_opts = getOptions buf src_fn
1940 (dflags', _errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1941 -- XXX: shouldn't we be reporting the errors?
1945 | Just (Unlit _) <- mb_phase = True
1946 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1947 -- note: local_opts is only required if there's no Unlit phase
1948 | dopt Opt_Cpp dflags' = True
1949 | dopt Opt_Pp dflags' = True
1952 when needs_preprocessing $
1953 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1955 return (dflags', src_fn, buf)
1958 -----------------------------------------------------------------------------
1960 -----------------------------------------------------------------------------
1962 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1963 -- ToDo: we don't have a proper line number for this error
1964 noModError dflags loc wanted_mod err
1965 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1967 noHsFileErr :: SrcSpan -> String -> a
1968 noHsFileErr loc path
1969 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1971 packageModErr :: ModuleName -> a
1973 = throwDyn $ mkPlainErrMsg noSrcSpan $
1974 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1976 multiRootsErr :: [ModSummary] -> IO ()
1977 multiRootsErr [] = panic "multiRootsErr"
1978 multiRootsErr summs@(summ1:_)
1979 = throwDyn $ mkPlainErrMsg noSrcSpan $
1980 text "module" <+> quotes (ppr mod) <+>
1981 text "is defined in multiple files:" <+>
1982 sep (map text files)
1985 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1987 cyclicModuleErr :: [ModSummary] -> SDoc
1989 = hang (ptext (sLit "Module imports form a cycle for modules:"))
1990 2 (vcat (map show_one ms))
1992 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1993 nest 2 $ ptext (sLit "imports:") <+>
1994 (pp_imps HsBootFile (ms_srcimps ms)
1995 $$ pp_imps HsSrcFile (ms_imps ms))]
1996 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1997 pp_imps src mods = fsep (map (show_mod src) mods)
2000 -- | Inform GHC that the working directory has changed. GHC will flush
2001 -- its cache of module locations, since it may no longer be valid.
2002 -- Note: if you change the working directory, you should also unload
2003 -- the current program (set targets to empty, followed by load).
2004 workingDirectoryChanged :: Session -> IO ()
2005 workingDirectoryChanged s = withSession s $ flushFinderCaches
2007 -- -----------------------------------------------------------------------------
2008 -- inspecting the session
2010 -- | Get the module dependency graph.
2011 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
2012 getModuleGraph s = withSession s (return . hsc_mod_graph)
2014 isLoaded :: Session -> ModuleName -> IO Bool
2015 isLoaded s m = withSession s $ \hsc_env ->
2016 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2018 getBindings :: Session -> IO [TyThing]
2019 getBindings s = withSession s $ \hsc_env ->
2020 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2021 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2023 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2024 filtered = foldr f (const []) tmp_ids emptyUniqSet
2026 | uniq `elementOfUniqSet` set = rest set
2027 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2028 where uniq = getUnique (nameOccName (idName id))
2032 getPrintUnqual :: Session -> IO PrintUnqualified
2033 getPrintUnqual s = withSession s $ \hsc_env ->
2034 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2036 -- | Container for information about a 'Module'.
2037 data ModuleInfo = ModuleInfo {
2038 minf_type_env :: TypeEnv,
2039 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2040 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2041 minf_instances :: [Instance]
2043 ,minf_modBreaks :: ModBreaks
2045 -- ToDo: this should really contain the ModIface too
2047 -- We don't want HomeModInfo here, because a ModuleInfo applies
2048 -- to package modules too.
2050 -- | Request information about a loaded 'Module'
2051 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
2052 getModuleInfo s mdl = withSession s $ \hsc_env -> do
2053 let mg = hsc_mod_graph hsc_env
2054 if mdl `elem` map ms_mod mg
2055 then getHomeModuleInfo hsc_env (moduleName mdl)
2057 {- if isHomeModule (hsc_dflags hsc_env) mdl
2059 else -} getPackageModuleInfo hsc_env mdl
2060 -- getPackageModuleInfo will attempt to find the interface, so
2061 -- we don't want to call it for a home module, just in case there
2062 -- was a problem loading the module and the interface doesn't
2063 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2065 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2067 getPackageModuleInfo hsc_env mdl = do
2068 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2070 Nothing -> return Nothing
2072 eps <- readIORef (hsc_EPS hsc_env)
2074 names = availsToNameSet avails
2076 tys = [ ty | name <- concatMap availNames avails,
2077 Just ty <- [lookupTypeEnv pte name] ]
2079 return (Just (ModuleInfo {
2080 minf_type_env = mkTypeEnv tys,
2081 minf_exports = names,
2082 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2083 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2084 minf_modBreaks = emptyModBreaks
2087 getPackageModuleInfo _hsc_env _mdl = do
2088 -- bogusly different for non-GHCI (ToDo)
2092 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2093 getHomeModuleInfo hsc_env mdl =
2094 case lookupUFM (hsc_HPT hsc_env) mdl of
2095 Nothing -> return Nothing
2097 let details = hm_details hmi
2098 return (Just (ModuleInfo {
2099 minf_type_env = md_types details,
2100 minf_exports = availsToNameSet (md_exports details),
2101 minf_rdr_env = mi_globals $! hm_iface hmi,
2102 minf_instances = md_insts details
2104 ,minf_modBreaks = getModBreaks hmi
2108 -- | The list of top-level entities defined in a module
2109 modInfoTyThings :: ModuleInfo -> [TyThing]
2110 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2112 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2113 modInfoTopLevelScope minf
2114 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2116 modInfoExports :: ModuleInfo -> [Name]
2117 modInfoExports minf = nameSetToList $! minf_exports minf
2119 -- | Returns the instances defined by the specified module.
2120 -- Warning: currently unimplemented for package modules.
2121 modInfoInstances :: ModuleInfo -> [Instance]
2122 modInfoInstances = minf_instances
2124 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2125 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2127 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2128 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2129 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2131 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2132 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2133 case lookupTypeEnv (minf_type_env minf) name of
2134 Just tyThing -> return (Just tyThing)
2136 eps <- readIORef (hsc_EPS hsc_env)
2137 return $! lookupType (hsc_dflags hsc_env)
2138 (hsc_HPT hsc_env) (eps_PTE eps) name
2141 modInfoModBreaks :: ModuleInfo -> ModBreaks
2142 modInfoModBreaks = minf_modBreaks
2145 isDictonaryId :: Id -> Bool
2147 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2149 -- | Looks up a global name: that is, any top-level name in any
2150 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2151 -- the interactive context, and therefore does not require a preceding
2153 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2154 lookupGlobalName s name = withSession s $ \hsc_env -> do
2155 eps <- readIORef (hsc_EPS hsc_env)
2156 return $! lookupType (hsc_dflags hsc_env)
2157 (hsc_HPT hsc_env) (eps_PTE eps) name
2160 -- | get the GlobalRdrEnv for a session
2161 getGRE :: Session -> IO GlobalRdrEnv
2162 getGRE s = withSession s $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2165 -- -----------------------------------------------------------------------------
2166 -- Misc exported utils
2168 dataConType :: DataCon -> Type
2169 dataConType dc = idType (dataConWrapId dc)
2171 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2172 pprParenSymName :: NamedThing a => a -> SDoc
2173 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2175 -- ----------------------------------------------------------------------------
2180 -- - Data and Typeable instances for HsSyn.
2182 -- ToDo: check for small transformations that happen to the syntax in
2183 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2185 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2186 -- to get from TyCons, Ids etc. to TH syntax (reify).
2188 -- :browse will use either lm_toplev or inspect lm_interface, depending
2189 -- on whether the module is interpreted or not.
2191 -- This is for reconstructing refactored source code
2192 -- Calls the lexer repeatedly.
2193 -- ToDo: add comment tokens to token stream
2194 getTokenStream :: Session -> Module -> IO [Located Token]
2197 -- -----------------------------------------------------------------------------
2198 -- Interactive evaluation
2200 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2201 -- filesystem and package database to find the corresponding 'Module',
2202 -- using the algorithm that is used for an @import@ declaration.
2203 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2204 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2206 dflags = hsc_dflags hsc_env
2207 hpt = hsc_HPT hsc_env
2208 this_pkg = thisPackage dflags
2210 case lookupUFM hpt mod_name of
2211 Just mod_info -> return (mi_module (hm_iface mod_info))
2212 _not_a_home_module -> do
2213 res <- findImportedModule hsc_env mod_name maybe_pkg
2215 Found _ m | modulePackageId m /= this_pkg -> return m
2216 | otherwise -> throwDyn (CmdLineError (showSDoc $
2217 text "module" <+> pprModule m <+>
2218 text "is not loaded"))
2219 err -> let msg = cannotFindModule dflags mod_name err in
2220 throwDyn (CmdLineError (showSDoc msg))
2223 getHistorySpan :: Session -> History -> IO SrcSpan
2224 getHistorySpan sess h = withSession sess $ \hsc_env ->
2225 return$ InteractiveEval.getHistorySpan hsc_env h
2227 obtainTerm :: Session -> Bool -> Id -> IO Term
2228 obtainTerm sess force id = withSession sess $ \hsc_env ->
2229 InteractiveEval.obtainTerm hsc_env force id
2231 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2232 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2233 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2235 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2236 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2237 InteractiveEval.obtainTermB hsc_env bound force id