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 )
277 import Control.Exception as Exception hiding (handle)
279 import System.FilePath
281 import System.IO.Error ( try, isDoesNotExistError )
282 import Prelude hiding (init)
285 -- -----------------------------------------------------------------------------
286 -- Exception handlers
288 -- | Install some default exception handlers and run the inner computation.
289 -- Unless you want to handle exceptions yourself, you should wrap this around
290 -- the top level of your program. The default handlers output the error
291 -- message(s) to stderr and exit cleanly.
292 defaultErrorHandler :: DynFlags -> IO a -> IO a
293 defaultErrorHandler dflags inner =
294 -- top-level exception handler: any unrecognised exception is a compiler bug.
295 handle (\exception -> do
298 -- an IO exception probably isn't our fault, so don't panic
300 fatalErrorMsg dflags (text (show exception))
301 AsyncException StackOverflow ->
302 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
304 fatalErrorMsg dflags (text (show (Panic (show exception))))
305 exitWith (ExitFailure 1)
308 -- program errors: messages with locations attached. Sometimes it is
309 -- convenient to just throw these as exceptions.
310 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
311 exitWith (ExitFailure 1)) $
313 -- error messages propagated as exceptions
314 handleDyn (\dyn -> do
317 PhaseFailed _ code -> exitWith code
318 Interrupted -> exitWith (ExitFailure 1)
319 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
320 exitWith (ExitFailure 1)
324 -- | Install a default cleanup handler to remove temporary files
325 -- deposited by a GHC run. This is seperate from
326 -- 'defaultErrorHandler', because you might want to override the error
327 -- handling, but still get the ordinary cleanup behaviour.
328 defaultCleanupHandler :: DynFlags -> IO a -> IO a
329 defaultCleanupHandler dflags inner =
330 -- make sure we clean up after ourselves
331 later (do cleanTempFiles dflags
334 -- exceptions will be blocked while we clean the temporary files,
335 -- so there shouldn't be any difficulty if we receive further
340 -- | Starts a new session. A session consists of a set of loaded
341 -- modules, a set of options (DynFlags), and an interactive context.
342 -- ToDo: explain argument [[mb_top_dir]]
343 newSession :: Maybe FilePath -> IO Session
344 newSession mb_top_dir = do
346 main_thread <- myThreadId
347 modifyMVar_ interruptTargetThread (return . (main_thread :))
348 installSignalHandlers
351 dflags0 <- initDynFlags defaultDynFlags
352 dflags <- initSysTools mb_top_dir dflags0
353 env <- newHscEnv dflags
357 -- tmp: this breaks the abstraction, but required because DriverMkDepend
358 -- needs to call the Finder. ToDo: untangle this.
359 sessionHscEnv :: Session -> IO HscEnv
360 sessionHscEnv (Session ref) = readIORef ref
362 -- -----------------------------------------------------------------------------
365 -- | Grabs the DynFlags from the Session
366 getSessionDynFlags :: Session -> IO DynFlags
367 getSessionDynFlags s = withSession s (return . hsc_dflags)
369 -- | Updates the DynFlags in a Session. This also reads
370 -- the package database (unless it has already been read),
371 -- and prepares the compilers knowledge about packages. It
372 -- can be called again to load new packages: just add new
373 -- package flags to (packageFlags dflags).
375 -- Returns a list of new packages that may need to be linked in using
376 -- the dynamic linker (see 'linkPackages') as a result of new package
377 -- flags. If you are not doing linking or doing static linking, you
378 -- can ignore the list of packages returned.
380 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
381 setSessionDynFlags (Session ref) dflags = do
382 hsc_env <- readIORef ref
383 (dflags', preload) <- initPackages dflags
384 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
387 -- | If there is no -o option, guess the name of target executable
388 -- by using top-level source file name as a base.
389 guessOutputFile :: Session -> IO ()
390 guessOutputFile s = modifySession s $ \env ->
391 let dflags = hsc_dflags env
392 mod_graph = hsc_mod_graph env
393 mainModuleSrcPath :: Maybe String
394 mainModuleSrcPath = do
395 let isMain = (== mainModIs dflags) . ms_mod
396 [ms] <- return (filter isMain mod_graph)
397 ml_hs_file (ms_location ms)
398 name = fmap dropExtension mainModuleSrcPath
400 #if defined(mingw32_HOST_OS)
401 -- we must add the .exe extention unconditionally here, otherwise
402 -- when name has an extension of its own, the .exe extension will
403 -- not be added by DriverPipeline.exeFileName. See #2248
404 name_exe = fmap (<.> "exe") name
409 case outputFile dflags of
411 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
413 -- -----------------------------------------------------------------------------
416 -- ToDo: think about relative vs. absolute file paths. And what
417 -- happens when the current directory changes.
419 -- | Sets the targets for this session. Each target may be a module name
420 -- or a filename. The targets correspond to the set of root modules for
421 -- the program\/library. Unloading the current program is achieved by
422 -- setting the current set of targets to be empty, followed by load.
423 setTargets :: Session -> [Target] -> IO ()
424 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
426 -- | returns the current set of targets
427 getTargets :: Session -> IO [Target]
428 getTargets s = withSession s (return . hsc_targets)
430 -- | Add another target
431 addTarget :: Session -> Target -> IO ()
433 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
436 removeTarget :: Session -> TargetId -> IO ()
437 removeTarget s target_id
438 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
440 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
442 -- Attempts to guess what Target a string refers to. This function implements
443 -- the --make/GHCi command-line syntax for filenames:
445 -- - if the string looks like a Haskell source filename, then interpret
447 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
449 -- - otherwise interpret the string as a module name
451 guessTarget :: String -> Maybe Phase -> IO Target
452 guessTarget file (Just phase)
453 = return (Target (TargetFile file (Just phase)) Nothing)
454 guessTarget file Nothing
455 | isHaskellSrcFilename file
456 = return (Target (TargetFile file Nothing) Nothing)
458 = do exists <- doesFileExist hs_file
460 then return (Target (TargetFile hs_file Nothing) Nothing)
462 exists <- doesFileExist lhs_file
464 then return (Target (TargetFile lhs_file Nothing) Nothing)
466 return (Target (TargetModule (mkModuleName file)) Nothing)
468 hs_file = file <.> "hs"
469 lhs_file = file <.> "lhs"
471 -- -----------------------------------------------------------------------------
472 -- Extending the program scope
474 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
475 extendGlobalRdrScope session rdrElts
476 = modifySession session $ \hscEnv ->
477 let global_rdr = hsc_global_rdr_env hscEnv
478 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
480 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
481 setGlobalRdrScope session rdrElts
482 = modifySession session $ \hscEnv ->
483 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
485 extendGlobalTypeScope :: Session -> [Id] -> IO ()
486 extendGlobalTypeScope session ids
487 = modifySession session $ \hscEnv ->
488 let global_type = hsc_global_type_env hscEnv
489 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
491 setGlobalTypeScope :: Session -> [Id] -> IO ()
492 setGlobalTypeScope session ids
493 = modifySession session $ \hscEnv ->
494 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
496 -- -----------------------------------------------------------------------------
497 -- Parsing Haddock comments
499 parseHaddockComment :: String -> Either String (HsDoc RdrName)
500 parseHaddockComment string =
501 case parseHaddockParagraphs (tokenise string) of
505 -- -----------------------------------------------------------------------------
506 -- Loading the program
508 -- Perform a dependency analysis starting from the current targets
509 -- and update the session with the new module graph.
510 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
511 depanal (Session ref) excluded_mods allow_dup_roots = do
512 hsc_env <- readIORef ref
514 dflags = hsc_dflags hsc_env
515 targets = hsc_targets hsc_env
516 old_graph = hsc_mod_graph hsc_env
518 showPass dflags "Chasing dependencies"
519 debugTraceMsg dflags 2 (hcat [
520 text "Chasing modules from: ",
521 hcat (punctuate comma (map pprTarget targets))])
523 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
525 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
530 -- | The result of load.
532 = LoadOk Errors -- ^ all specified targets were loaded successfully.
533 | LoadFailed Errors -- ^ not all modules were loaded.
535 type Errors = [String]
537 data ErrMsg = ErrMsg {
538 errMsgSeverity :: Severity, -- warning, error, etc.
539 errMsgSpans :: [SrcSpan],
540 errMsgShortDoc :: Doc,
541 errMsgExtraInfo :: Doc
547 | LoadUpTo ModuleName
548 | LoadDependenciesOf ModuleName
550 -- | Try to load the program. If a Module is supplied, then just
551 -- attempt to load up to this target. If no Module is supplied,
552 -- then try to load all targets.
553 load :: Session -> LoadHowMuch -> IO SuccessFlag
556 -- Dependency analysis first. Note that this fixes the module graph:
557 -- even if we don't get a fully successful upsweep, the full module
558 -- graph is still retained in the Session. We can tell which modules
559 -- were successfully loaded by inspecting the Session's HPT.
560 mb_graph <- depanal s [] False
562 Just mod_graph -> load2 s how_much mod_graph
563 Nothing -> return Failed
565 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
566 load2 s@(Session ref) how_much mod_graph = do
568 hsc_env <- readIORef ref
570 let hpt1 = hsc_HPT hsc_env
571 let dflags = hsc_dflags hsc_env
573 -- The "bad" boot modules are the ones for which we have
574 -- B.hs-boot in the module graph, but no B.hs
575 -- The downsweep should have ensured this does not happen
577 let all_home_mods = [ms_mod_name s
578 | s <- mod_graph, not (isBootSummary s)]
579 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
580 not (ms_mod_name s `elem` all_home_mods)]
581 ASSERT( null bad_boot_mods ) return ()
583 -- check that the module given in HowMuch actually exists, otherwise
584 -- topSortModuleGraph will bomb later.
585 let checkHowMuch (LoadUpTo m) = checkMod m
586 checkHowMuch (LoadDependenciesOf m) = checkMod m
590 | m `elem` all_home_mods = and_then
592 errorMsg dflags (text "no such module:" <+>
596 checkHowMuch how_much $ do
598 -- mg2_with_srcimps drops the hi-boot nodes, returning a
599 -- graph with cycles. Among other things, it is used for
600 -- backing out partially complete cycles following a failed
601 -- upsweep, and for removing from hpt all the modules
602 -- not in strict downwards closure, during calls to compile.
603 let mg2_with_srcimps :: [SCC ModSummary]
604 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
606 -- If we can determine that any of the {-# SOURCE #-} imports
607 -- are definitely unnecessary, then emit a warning.
608 warnUnnecessarySourceImports dflags mg2_with_srcimps
611 -- check the stability property for each module.
612 stable_mods@(stable_obj,stable_bco)
613 = checkStability hpt1 mg2_with_srcimps all_home_mods
615 -- prune bits of the HPT which are definitely redundant now,
617 pruned_hpt = pruneHomePackageTable hpt1
618 (flattenSCCs mg2_with_srcimps)
623 -- before we unload anything, make sure we don't leave an old
624 -- interactive context around pointing to dead bindings. Also,
625 -- write the pruned HPT to allow the old HPT to be GC'd.
626 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext,
627 hsc_HPT = pruned_hpt }
629 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
630 text "Stable BCO:" <+> ppr stable_bco)
632 -- Unload any modules which are going to be re-linked this time around.
633 let stable_linkables = [ linkable
634 | m <- stable_obj++stable_bco,
635 Just hmi <- [lookupUFM pruned_hpt m],
636 Just linkable <- [hm_linkable hmi] ]
637 unload hsc_env stable_linkables
639 -- We could at this point detect cycles which aren't broken by
640 -- a source-import, and complain immediately, but it seems better
641 -- to let upsweep_mods do this, so at least some useful work gets
642 -- done before the upsweep is abandoned.
643 --hPutStrLn stderr "after tsort:\n"
644 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
646 -- Now do the upsweep, calling compile for each module in
647 -- turn. Final result is version 3 of everything.
649 -- Topologically sort the module graph, this time including hi-boot
650 -- nodes, and possibly just including the portion of the graph
651 -- reachable from the module specified in the 2nd argument to load.
652 -- This graph should be cycle-free.
653 -- If we're restricting the upsweep to a portion of the graph, we
654 -- also want to retain everything that is still stable.
655 let full_mg :: [SCC ModSummary]
656 full_mg = topSortModuleGraph False mod_graph Nothing
658 maybe_top_mod = case how_much of
660 LoadDependenciesOf m -> Just m
663 partial_mg0 :: [SCC ModSummary]
664 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
666 -- LoadDependenciesOf m: we want the upsweep to stop just
667 -- short of the specified module (unless the specified module
670 | LoadDependenciesOf _mod <- how_much
671 = ASSERT( case last partial_mg0 of
672 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
673 List.init partial_mg0
679 | AcyclicSCC ms <- full_mg,
680 ms_mod_name ms `elem` stable_obj++stable_bco,
681 ms_mod_name ms `notElem` [ ms_mod_name ms' |
682 AcyclicSCC ms' <- partial_mg ] ]
684 mg = stable_mg ++ partial_mg
686 -- clean up between compilations
687 let cleanup = cleanTempFilesExcept dflags
688 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
690 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
692 (upsweep_ok, hsc_env1, modsUpswept)
693 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
694 pruned_hpt stable_mods cleanup mg
696 -- Make modsDone be the summaries for each home module now
697 -- available; this should equal the domain of hpt3.
698 -- Get in in a roughly top .. bottom order (hence reverse).
700 let modsDone = reverse modsUpswept
702 -- Try and do linking in some form, depending on whether the
703 -- upsweep was completely or only partially successful.
705 if succeeded upsweep_ok
708 -- Easy; just relink it all.
709 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
711 -- Clean up after ourselves
712 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
714 -- Issue a warning for the confusing case where the user
715 -- said '-o foo' but we're not going to do any linking.
716 -- We attempt linking if either (a) one of the modules is
717 -- called Main, or (b) the user said -no-hs-main, indicating
718 -- that main() is going to come from somewhere else.
720 let ofile = outputFile dflags
721 let no_hs_main = dopt Opt_NoHsMain dflags
723 main_mod = mainModIs dflags
724 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
725 do_linking = a_root_is_Main || no_hs_main
727 when (ghcLink dflags == LinkBinary
728 && isJust ofile && not do_linking) $
729 debugTraceMsg dflags 1 $
730 text ("Warning: output was redirected with -o, " ++
731 "but no output will be generated\n" ++
732 "because there is no " ++
733 moduleNameString (moduleName main_mod) ++ " module.")
735 -- link everything together
736 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
738 loadFinish Succeeded linkresult ref hsc_env1
741 -- Tricky. We need to back out the effects of compiling any
742 -- half-done cycles, both so as to clean up the top level envs
743 -- and to avoid telling the interactive linker to link them.
744 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
747 = map ms_mod modsDone
748 let mods_to_zap_names
749 = findPartiallyCompletedCycles modsDone_names
752 = filter ((`notElem` mods_to_zap_names).ms_mod)
755 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
758 -- Clean up after ourselves
759 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
761 -- there should be no Nothings where linkables should be, now
762 ASSERT(all (isJust.hm_linkable)
763 (eltsUFM (hsc_HPT hsc_env))) do
765 -- Link everything together
766 linkresult <- link (ghcLink dflags) dflags False hpt4
768 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
769 loadFinish Failed linkresult ref hsc_env4
771 -- Finish up after a load.
773 -- If the link failed, unload everything and return.
774 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
775 loadFinish _all_ok Failed ref hsc_env
776 = do unload hsc_env []
777 writeIORef ref $! discardProg hsc_env
780 -- Empty the interactive context and set the module context to the topmost
781 -- newly loaded module, or the Prelude if none were loaded.
782 loadFinish all_ok Succeeded ref hsc_env
783 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
787 -- Forget the current program, but retain the persistent info in HscEnv
788 discardProg :: HscEnv -> HscEnv
790 = hsc_env { hsc_mod_graph = emptyMG,
791 hsc_IC = emptyInteractiveContext,
792 hsc_HPT = emptyHomePackageTable }
794 -- used to fish out the preprocess output files for the purposes of
795 -- cleaning up. The preprocessed file *might* be the same as the
796 -- source file, but that doesn't do any harm.
797 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
798 ppFilesFromSummaries summaries = map ms_hspp_file summaries
800 -- -----------------------------------------------------------------------------
804 CheckedModule { parsedSource :: ParsedSource,
805 renamedSource :: Maybe RenamedSource,
806 typecheckedSource :: Maybe TypecheckedSource,
807 checkedModuleInfo :: Maybe ModuleInfo,
808 coreModule :: Maybe ModGuts
810 -- ToDo: improvements that could be made here:
811 -- if the module succeeded renaming but not typechecking,
812 -- we can still get back the GlobalRdrEnv and exports, so
813 -- perhaps the ModuleInfo should be split up into separate
814 -- fields within CheckedModule.
816 type ParsedSource = Located (HsModule RdrName)
817 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
818 Maybe (HsDoc Name), HaddockModInfo Name)
819 type TypecheckedSource = LHsBinds Id
822 -- - things that aren't in the output of the typechecker right now:
826 -- - type/data/newtype declarations
827 -- - class declarations
829 -- - extra things in the typechecker's output:
830 -- - default methods are turned into top-level decls.
831 -- - dictionary bindings
834 -- | This is the way to get access to parsed and typechecked source code
835 -- for a module. 'checkModule' attempts to typecheck the module. If
836 -- successful, it returns the abstract syntax for the module.
837 -- If compileToCore is true, it also desugars the module and returns the
838 -- resulting Core bindings as a component of the CheckedModule.
839 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
840 checkModule (Session ref) mod compile_to_core
842 hsc_env <- readIORef ref
843 let mg = hsc_mod_graph hsc_env
844 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
846 (ms:_) -> checkModule_ ref ms compile_to_core False
848 -- | parses and typechecks a module, optionally generates Core, and also
849 -- loads the module into the 'Session' so that modules which depend on
850 -- this one may subsequently be typechecked using 'checkModule' or
851 -- 'checkAndLoadModule'. If you need to check more than one module,
852 -- you probably want to use 'checkAndLoadModule'. Constructing the
853 -- interface takes a little work, so it might be slightly slower than
855 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
856 checkAndLoadModule (Session ref) ms compile_to_core
857 = checkModule_ ref ms compile_to_core True
859 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
860 -> IO (Maybe CheckedModule)
861 checkModule_ ref ms compile_to_core load
863 let mod = ms_mod_name ms
864 hsc_env0 <- readIORef ref
865 let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
866 mb_parsed <- parseFile hsc_env ms
868 Nothing -> return Nothing
869 Just rdr_module -> do
870 mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
871 case mb_typechecked of
872 Nothing -> return (Just CheckedModule {
873 parsedSource = rdr_module,
874 renamedSource = Nothing,
875 typecheckedSource = Nothing,
876 checkedModuleInfo = Nothing,
877 coreModule = Nothing })
878 Just (tcg, rn_info) -> do
879 details <- makeSimpleDetails hsc_env tcg
881 let tc_binds = tcg_binds tcg
882 let rdr_env = tcg_rdr_env tcg
883 let minf = ModuleInfo {
884 minf_type_env = md_types details,
885 minf_exports = availsToNameSet $
887 minf_rdr_env = Just rdr_env,
888 minf_instances = md_insts details
890 ,minf_modBreaks = emptyModBreaks
894 mb_guts <- if compile_to_core
895 then deSugarModule hsc_env ms tcg
898 -- If we are loading this module so that we can typecheck
899 -- dependent modules, generate an interface and stuff it
900 -- all in the HomePackageTable.
902 (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
903 let mod_info = HomeModInfo {
905 hm_details = details,
906 hm_linkable = Nothing }
907 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
908 writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
910 return (Just (CheckedModule {
911 parsedSource = rdr_module,
912 renamedSource = rn_info,
913 typecheckedSource = Just tc_binds,
914 checkedModuleInfo = Just minf,
915 coreModule = mb_guts }))
917 -- | This is the way to get access to the Core bindings corresponding
918 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
919 -- desugar the module, then returns the resulting Core module (consisting of
920 -- the module name, type declarations, and function declarations) if
922 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
923 compileToCoreModule = compileCore False
925 -- | Like compileToCoreModule, but invokes the simplifier, so
926 -- as to return simplified and tidied Core.
927 compileToCoreSimplified :: Session -> FilePath -> IO (Maybe CoreModule)
928 compileToCoreSimplified = compileCore True
930 -- | Provided for backwards-compatibility: compileToCore returns just the Core
931 -- bindings, but for most purposes, you probably want to call
932 -- compileToCoreModule.
933 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
934 compileToCore session fn = do
935 maybeCoreModule <- compileToCoreModule session fn
936 return $ fmap cm_binds maybeCoreModule
938 -- | Takes a CoreModule and compiles the bindings therein
939 -- to object code. The first argument is a bool flag indicating
940 -- whether to run the simplifier.
941 -- The resulting .o, .hi, and executable files, if any, are stored in the
942 -- current directory, and named according to the module name.
943 -- Returns True iff compilation succeeded.
944 -- This has only so far been tested with a single self-contained module.
945 compileCoreToObj :: Bool -> Session -> CoreModule -> IO Bool
946 compileCoreToObj simplify session cm@(CoreModule{ cm_module = mName }) = do
947 hscEnv <- sessionHscEnv session
948 dflags <- getSessionDynFlags session
949 currentTime <- getClockTime
950 cwd <- getCurrentDirectory
951 modLocation <- mkHiOnlyModLocation dflags (hiSuf dflags) cwd
952 ((moduleNameSlashes . moduleName) mName)
954 let modSummary = ModSummary { ms_mod = mName,
955 ms_hsc_src = ExtCoreFile,
956 ms_location = modLocation,
957 -- By setting the object file timestamp to Nothing,
958 -- we always force recompilation, which is what we
959 -- want. (Thus it doesn't matter what the timestamp
960 -- for the (nonexistent) source file is.)
961 ms_hs_date = currentTime,
962 ms_obj_date = Nothing,
963 -- Only handling the single-module case for now, so no imports.
968 ms_hspp_opts = dflags,
969 ms_hspp_buf = Nothing
972 mbHscResult <- evalComp
973 ((if simplify then hscSimplify else return) (mkModGuts cm)
974 >>= hscNormalIface >>= hscWriteIface >>= hscOneShot)
975 (CompState{ compHscEnv=hscEnv,
976 compModSummary=modSummary,
977 compOldIface=Nothing})
978 return $ isJust mbHscResult
980 -- Makes a "vanilla" ModGuts.
981 mkModGuts :: CoreModule -> ModGuts
982 mkModGuts coreModule = ModGuts {
983 mg_module = cm_module coreModule,
986 mg_deps = noDependencies,
987 mg_dir_imps = emptyModuleEnv,
988 mg_used_names = emptyNameSet,
989 mg_rdr_env = emptyGlobalRdrEnv,
990 mg_fix_env = emptyFixityEnv,
991 mg_types = emptyTypeEnv,
995 mg_binds = cm_binds coreModule,
996 mg_foreign = NoStubs,
997 mg_deprecs = NoDeprecs,
998 mg_hpc_info = emptyHpcInfo False,
999 mg_modBreaks = emptyModBreaks,
1000 mg_vect_info = noVectInfo,
1001 mg_inst_env = emptyInstEnv,
1002 mg_fam_inst_env = emptyFamInstEnv
1005 compileCore :: Bool -> Session -> FilePath -> IO (Maybe CoreModule)
1006 compileCore simplify session fn = do
1007 -- First, set the target to the desired filename
1008 target <- guessTarget fn Nothing
1009 addTarget session target
1010 load session LoadAllTargets
1011 -- Then find dependencies
1012 maybeModGraph <- depanal session [] True
1013 case maybeModGraph of
1014 Nothing -> return Nothing
1016 case find ((== fn) . msHsFilePath) modGraph of
1017 Just modSummary -> do
1018 -- Now we have the module name;
1019 -- parse, typecheck and desugar the module
1020 let mod = ms_mod_name modSummary
1021 maybeCheckedModule <- checkModule session mod True
1022 case maybeCheckedModule of
1023 Nothing -> return Nothing
1024 Just checkedMod -> (liftM $ fmap gutsToCoreModule) $
1025 case (coreModule checkedMod) of
1026 Just mg | simplify -> (sessionHscEnv session)
1027 -- If simplify is true: simplify (hscSimplify),
1028 -- then tidy (tidyProgram).
1029 >>= \ hscEnv -> evalComp (hscSimplify mg)
1030 (CompState{ compHscEnv=hscEnv,
1031 compModSummary=modSummary,
1032 compOldIface=Nothing})
1033 >>= (tidyProgram hscEnv)
1034 >>= (return . Just . Left)
1035 Just guts -> return $ Just $ Right guts
1036 Nothing -> return Nothing
1037 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1038 module dependency graph"
1039 where -- two versions, based on whether we simplify (thus run tidyProgram,
1040 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1041 -- we just have a ModGuts.
1042 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1043 gutsToCoreModule (Left (cg, md)) = CoreModule {
1044 cm_module = cg_module cg, cm_types = md_types md,
1045 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1047 gutsToCoreModule (Right mg) = CoreModule {
1048 cm_module = mg_module mg, cm_types = mg_types mg,
1049 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1052 -- ---------------------------------------------------------------------------
1055 unload :: HscEnv -> [Linkable] -> IO ()
1056 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1057 = case ghcLink (hsc_dflags hsc_env) of
1059 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1061 LinkInMemory -> panic "unload: no interpreter"
1062 -- urgh. avoid warnings:
1063 hsc_env stable_linkables
1067 -- -----------------------------------------------------------------------------
1071 Stability tells us which modules definitely do not need to be recompiled.
1072 There are two main reasons for having stability:
1074 - avoid doing a complete upsweep of the module graph in GHCi when
1075 modules near the bottom of the tree have not changed.
1077 - to tell GHCi when it can load object code: we can only load object code
1078 for a module when we also load object code fo all of the imports of the
1079 module. So we need to know that we will definitely not be recompiling
1080 any of these modules, and we can use the object code.
1082 The stability check is as follows. Both stableObject and
1083 stableBCO are used during the upsweep phase later.
1086 stable m = stableObject m || stableBCO m
1089 all stableObject (imports m)
1090 && old linkable does not exist, or is == on-disk .o
1091 && date(on-disk .o) > date(.hs)
1094 all stable (imports m)
1095 && date(BCO) > date(.hs)
1098 These properties embody the following ideas:
1100 - if a module is stable, then:
1101 - if it has been compiled in a previous pass (present in HPT)
1102 then it does not need to be compiled or re-linked.
1103 - if it has not been compiled in a previous pass,
1104 then we only need to read its .hi file from disk and
1105 link it to produce a ModDetails.
1107 - if a modules is not stable, we will definitely be at least
1108 re-linking, and possibly re-compiling it during the upsweep.
1109 All non-stable modules can (and should) therefore be unlinked
1112 - Note that objects are only considered stable if they only depend
1113 on other objects. We can't link object code against byte code.
1117 :: HomePackageTable -- HPT from last compilation
1118 -> [SCC ModSummary] -- current module graph (cyclic)
1119 -> [ModuleName] -- all home modules
1120 -> ([ModuleName], -- stableObject
1121 [ModuleName]) -- stableBCO
1123 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1125 checkSCC (stable_obj, stable_bco) scc0
1126 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1127 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1128 | otherwise = (stable_obj, stable_bco)
1130 scc = flattenSCC scc0
1131 scc_mods = map ms_mod_name scc
1132 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1134 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1135 -- all imports outside the current SCC, but in the home pkg
1137 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1138 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1142 && all object_ok scc
1145 and (zipWith (||) stable_obj_imps stable_bco_imps)
1149 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1153 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1154 Just hmi | Just l <- hm_linkable hmi
1155 -> isObjectLinkable l && t == linkableTime l
1157 -- why '>=' rather than '>' above? If the filesystem stores
1158 -- times to the nearset second, we may occasionally find that
1159 -- the object & source have the same modification time,
1160 -- especially if the source was automatically generated
1161 -- and compiled. Using >= is slightly unsafe, but it matches
1162 -- make's behaviour.
1165 = case lookupUFM hpt (ms_mod_name ms) of
1166 Just hmi | Just l <- hm_linkable hmi ->
1167 not (isObjectLinkable l) &&
1168 linkableTime l >= ms_hs_date ms
1171 ms_allimps :: ModSummary -> [ModuleName]
1172 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1174 -- -----------------------------------------------------------------------------
1175 -- Prune the HomePackageTable
1177 -- Before doing an upsweep, we can throw away:
1179 -- - For non-stable modules:
1180 -- - all ModDetails, all linked code
1181 -- - all unlinked code that is out of date with respect to
1184 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1185 -- space at the end of the upsweep, because the topmost ModDetails of the
1186 -- old HPT holds on to the entire type environment from the previous
1189 pruneHomePackageTable
1192 -> ([ModuleName],[ModuleName])
1195 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1198 | is_stable modl = hmi'
1199 | otherwise = hmi'{ hm_details = emptyModDetails }
1201 modl = moduleName (mi_module (hm_iface hmi))
1202 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1203 = hmi{ hm_linkable = Nothing }
1206 where ms = expectJust "prune" (lookupUFM ms_map modl)
1208 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1210 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1212 -- -----------------------------------------------------------------------------
1214 -- Return (names of) all those in modsDone who are part of a cycle
1215 -- as defined by theGraph.
1216 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1217 findPartiallyCompletedCycles modsDone theGraph
1221 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1222 chew ((CyclicSCC vs):rest)
1223 = let names_in_this_cycle = nub (map ms_mod vs)
1225 = nub ([done | done <- modsDone,
1226 done `elem` names_in_this_cycle])
1227 chewed_rest = chew rest
1229 if notNull mods_in_this_cycle
1230 && length mods_in_this_cycle < length names_in_this_cycle
1231 then mods_in_this_cycle ++ chewed_rest
1234 -- -----------------------------------------------------------------------------
1237 -- This is where we compile each module in the module graph, in a pass
1238 -- from the bottom to the top of the graph.
1240 -- There better had not be any cyclic groups here -- we check for them.
1243 :: HscEnv -- Includes initially-empty HPT
1244 -> HomePackageTable -- HPT from last time round (pruned)
1245 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1246 -> IO () -- How to clean up unwanted tmp files
1247 -> [SCC ModSummary] -- Mods to do (the worklist)
1249 HscEnv, -- With an updated HPT
1250 [ModSummary]) -- Mods which succeeded
1252 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1253 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1254 return (res, hsc_env, reverse done)
1257 upsweep' hsc_env _old_hpt done
1259 = return (Succeeded, hsc_env, done)
1261 upsweep' hsc_env _old_hpt done
1262 (CyclicSCC ms:_) _ _
1263 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1264 return (Failed, hsc_env, done)
1266 upsweep' hsc_env old_hpt done
1267 (AcyclicSCC mod:mods) mod_index nmods
1268 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1269 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1270 -- (moduleEnvElts (hsc_HPT hsc_env)))
1272 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1275 cleanup -- Remove unwanted tmp files between compilations
1278 Nothing -> return (Failed, hsc_env, done)
1280 let this_mod = ms_mod_name mod
1282 -- Add new info to hsc_env
1283 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1284 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1286 -- Space-saving: delete the old HPT entry
1287 -- for mod BUT if mod is a hs-boot
1288 -- node, don't delete it. For the
1289 -- interface, the HPT entry is probaby for the
1290 -- main Haskell source file. Deleting it
1291 -- would force the real module to be recompiled
1293 old_hpt1 | isBootSummary mod = old_hpt
1294 | otherwise = delFromUFM old_hpt this_mod
1298 -- fixup our HomePackageTable after we've finished compiling
1299 -- a mutually-recursive loop. See reTypecheckLoop, below.
1300 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1302 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1305 -- Compile a single module. Always produce a Linkable for it if
1306 -- successful. If no compilation happened, return the old Linkable.
1307 upsweep_mod :: HscEnv
1309 -> ([ModuleName],[ModuleName])
1311 -> Int -- index of module
1312 -> Int -- total number of modules
1313 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1315 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1317 this_mod_name = ms_mod_name summary
1318 this_mod = ms_mod summary
1319 mb_obj_date = ms_obj_date summary
1320 obj_fn = ml_obj_file (ms_location summary)
1321 hs_date = ms_hs_date summary
1323 is_stable_obj = this_mod_name `elem` stable_obj
1324 is_stable_bco = this_mod_name `elem` stable_bco
1326 old_hmi = lookupUFM old_hpt this_mod_name
1328 -- We're using the dflags for this module now, obtained by
1329 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1330 dflags = ms_hspp_opts summary
1331 prevailing_target = hscTarget (hsc_dflags hsc_env)
1332 local_target = hscTarget dflags
1334 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1335 -- we don't do anything dodgy: these should only work to change
1336 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1337 -- end up trying to link object code to byte code.
1338 target = if prevailing_target /= local_target
1339 && (not (isObjectTarget prevailing_target)
1340 || not (isObjectTarget local_target))
1341 then prevailing_target
1344 -- store the corrected hscTarget into the summary
1345 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1347 -- The old interface is ok if
1348 -- a) we're compiling a source file, and the old HPT
1349 -- entry is for a source file
1350 -- b) we're compiling a hs-boot file
1351 -- Case (b) allows an hs-boot file to get the interface of its
1352 -- real source file on the second iteration of the compilation
1353 -- manager, but that does no harm. Otherwise the hs-boot file
1354 -- will always be recompiled
1359 Just hm_info | isBootSummary summary -> Just iface
1360 | not (mi_boot iface) -> Just iface
1361 | otherwise -> Nothing
1363 iface = hm_iface hm_info
1365 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1366 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1368 compile_it_discard_iface
1369 = compile hsc_env summary' mod_index nmods Nothing
1375 -- Regardless of whether we're generating object code or
1376 -- byte code, we can always use an existing object file
1377 -- if it is *stable* (see checkStability).
1378 | is_stable_obj, isJust old_hmi ->
1380 -- object is stable, and we have an entry in the
1381 -- old HPT: nothing to do
1383 | is_stable_obj, isNothing old_hmi -> do
1384 linkable <- findObjectLinkable this_mod obj_fn
1385 (expectJust "upseep1" mb_obj_date)
1386 compile_it (Just linkable)
1387 -- object is stable, but we need to load the interface
1388 -- off disk to make a HMI.
1392 ASSERT(isJust old_hmi) -- must be in the old_hpt
1394 -- BCO is stable: nothing to do
1396 | Just hmi <- old_hmi,
1397 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1398 linkableTime l >= ms_hs_date summary ->
1400 -- we have an old BCO that is up to date with respect
1401 -- to the source: do a recompilation check as normal.
1405 -- no existing code at all: we must recompile.
1407 -- When generating object code, if there's an up-to-date
1408 -- object file on the disk, then we can use it.
1409 -- However, if the object file is new (compared to any
1410 -- linkable we had from a previous compilation), then we
1411 -- must discard any in-memory interface, because this
1412 -- means the user has compiled the source file
1413 -- separately and generated a new interface, that we must
1414 -- read from the disk.
1416 obj | isObjectTarget obj,
1417 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1420 | Just l <- hm_linkable hmi,
1421 isObjectLinkable l && linkableTime l == obj_date
1422 -> compile_it (Just l)
1424 linkable <- findObjectLinkable this_mod obj_fn obj_date
1425 compile_it_discard_iface (Just linkable)
1432 -- Filter modules in the HPT
1433 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1434 retainInTopLevelEnvs keep_these hpt
1435 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1437 , let mb_mod_info = lookupUFM hpt mod
1438 , isJust mb_mod_info ]
1440 -- ---------------------------------------------------------------------------
1441 -- Typecheck module loops
1444 See bug #930. This code fixes a long-standing bug in --make. The
1445 problem is that when compiling the modules *inside* a loop, a data
1446 type that is only defined at the top of the loop looks opaque; but
1447 after the loop is done, the structure of the data type becomes
1450 The difficulty is then that two different bits of code have
1451 different notions of what the data type looks like.
1453 The idea is that after we compile a module which also has an .hs-boot
1454 file, we re-generate the ModDetails for each of the modules that
1455 depends on the .hs-boot file, so that everyone points to the proper
1456 TyCons, Ids etc. defined by the real module, not the boot module.
1457 Fortunately re-generating a ModDetails from a ModIface is easy: the
1458 function TcIface.typecheckIface does exactly that.
1460 Picking the modules to re-typecheck is slightly tricky. Starting from
1461 the module graph consisting of the modules that have already been
1462 compiled, we reverse the edges (so they point from the imported module
1463 to the importing module), and depth-first-search from the .hs-boot
1464 node. This gives us all the modules that depend transitively on the
1465 .hs-boot module, and those are exactly the modules that we need to
1468 Following this fix, GHC can compile itself with --make -O2.
1471 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1472 reTypecheckLoop hsc_env ms graph
1473 | not (isBootSummary ms) &&
1474 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1476 let mss = reachableBackwards (ms_mod_name ms) graph
1477 non_boot = filter (not.isBootSummary) mss
1478 debugTraceMsg (hsc_dflags hsc_env) 2 $
1479 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1480 typecheckLoop hsc_env (map ms_mod_name non_boot)
1484 this_mod = ms_mod ms
1486 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1487 typecheckLoop hsc_env mods = do
1489 fixIO $ \new_hpt -> do
1490 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1491 mds <- initIfaceCheck new_hsc_env $
1492 mapM (typecheckIface . hm_iface) hmis
1493 let new_hpt = addListToUFM old_hpt
1494 (zip mods [ hmi{ hm_details = details }
1495 | (hmi,details) <- zip hmis mds ])
1497 return hsc_env{ hsc_HPT = new_hpt }
1499 old_hpt = hsc_HPT hsc_env
1500 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1502 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1503 reachableBackwards mod summaries
1504 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1506 -- all the nodes reachable by traversing the edges backwards
1507 -- from the root node:
1508 nodes_we_want = reachable (transposeG graph) root
1510 -- the rest just sets up the graph:
1511 (nodes, lookup_key) = moduleGraphNodes False summaries
1512 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1514 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1515 | otherwise = panic "reachableBackwards"
1517 -- ---------------------------------------------------------------------------
1518 -- Topological sort of the module graph
1521 :: Bool -- Drop hi-boot nodes? (see below)
1525 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1526 -- The resulting list of strongly-connected-components is in topologically
1527 -- sorted order, starting with the module(s) at the bottom of the
1528 -- dependency graph (ie compile them first) and ending with the ones at
1531 -- Drop hi-boot nodes (first boolean arg)?
1533 -- False: treat the hi-boot summaries as nodes of the graph,
1534 -- so the graph must be acyclic
1536 -- True: eliminate the hi-boot nodes, and instead pretend
1537 -- the a source-import of Foo is an import of Foo
1538 -- The resulting graph has no hi-boot nodes, but can by cyclic
1540 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1541 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1542 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1543 = stronglyConnComp (map vertex_fn (reachable graph root))
1545 -- restrict the graph to just those modules reachable from
1546 -- the specified module. We do this by building a graph with
1547 -- the full set of nodes, and determining the reachable set from
1548 -- the specified node.
1549 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1550 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1552 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1553 | otherwise = throwDyn (ProgramError "module does not exist")
1555 moduleGraphNodes :: Bool -> [ModSummary]
1556 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1557 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1559 -- Drop hs-boot nodes by using HsSrcFile as the key
1560 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1561 | otherwise = HsBootFile
1563 -- We use integers as the keys for the SCC algorithm
1564 nodes :: [(ModSummary, Int, [Int])]
1565 nodes = [(s, expectJust "topSort" $
1566 lookup_key (ms_hsc_src s) (ms_mod_name s),
1567 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1568 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1569 (-- see [boot-edges] below
1570 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1572 else case lookup_key HsBootFile (ms_mod_name s) of
1577 , not (isBootSummary s && drop_hs_boot_nodes) ]
1578 -- Drop the hi-boot ones if told to do so
1580 -- [boot-edges] if this is a .hs and there is an equivalent
1581 -- .hs-boot, add a link from the former to the latter. This
1582 -- has the effect of detecting bogus cases where the .hs-boot
1583 -- depends on the .hs, by introducing a cycle. Additionally,
1584 -- it ensures that we will always process the .hs-boot before
1585 -- the .hs, and so the HomePackageTable will always have the
1586 -- most up to date information.
1588 key_map :: NodeMap Int
1589 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1593 lookup_key :: HscSource -> ModuleName -> Maybe Int
1594 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1596 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1597 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1598 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1599 -- the IsBootInterface parameter True; else False
1602 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1603 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1605 msKey :: ModSummary -> NodeKey
1606 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1608 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1609 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1611 nodeMapElts :: NodeMap a -> [a]
1612 nodeMapElts = eltsFM
1614 -- If there are {-# SOURCE #-} imports between strongly connected
1615 -- components in the topological sort, then those imports can
1616 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1617 -- were necessary, then the edge would be part of a cycle.
1618 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1619 warnUnnecessarySourceImports dflags sccs =
1620 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1622 let mods_in_this_cycle = map ms_mod_name ms in
1623 [ warn i | m <- ms, i <- ms_srcimps m,
1624 unLoc i `notElem` mods_in_this_cycle ]
1626 warn :: Located ModuleName -> WarnMsg
1629 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1630 <+> quotes (ppr mod))
1632 -----------------------------------------------------------------------------
1633 -- Downsweep (dependency analysis)
1635 -- Chase downwards from the specified root set, returning summaries
1636 -- for all home modules encountered. Only follow source-import
1639 -- We pass in the previous collection of summaries, which is used as a
1640 -- cache to avoid recalculating a module summary if the source is
1643 -- The returned list of [ModSummary] nodes has one node for each home-package
1644 -- module, plus one for any hs-boot files. The imports of these nodes
1645 -- are all there, including the imports of non-home-package modules.
1648 -> [ModSummary] -- Old summaries
1649 -> [ModuleName] -- Ignore dependencies on these; treat
1650 -- them as if they were package modules
1651 -> Bool -- True <=> allow multiple targets to have
1652 -- the same module name; this is
1653 -- very useful for ghc -M
1654 -> IO (Maybe [ModSummary])
1655 -- The elts of [ModSummary] all have distinct
1656 -- (Modules, IsBoot) identifiers, unless the Bool is true
1657 -- in which case there can be repeats
1658 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1659 = -- catch error messages and return them
1660 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1661 rootSummaries <- mapM getRootSummary roots
1662 let root_map = mkRootMap rootSummaries
1663 checkDuplicates root_map
1664 summs <- loop (concatMap msDeps rootSummaries) root_map
1667 roots = hsc_targets hsc_env
1669 old_summary_map :: NodeMap ModSummary
1670 old_summary_map = mkNodeMap old_summaries
1672 getRootSummary :: Target -> IO ModSummary
1673 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1674 = do exists <- doesFileExist file
1676 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1677 else throwDyn $ mkPlainErrMsg noSrcSpan $
1678 text "can't find file:" <+> text file
1679 getRootSummary (Target (TargetModule modl) maybe_buf)
1680 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1681 (L rootLoc modl) maybe_buf excl_mods
1682 case maybe_summary of
1683 Nothing -> packageModErr modl
1686 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1688 -- In a root module, the filename is allowed to diverge from the module
1689 -- name, so we have to check that there aren't multiple root files
1690 -- defining the same module (otherwise the duplicates will be silently
1691 -- ignored, leading to confusing behaviour).
1692 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1693 checkDuplicates root_map
1694 | allow_dup_roots = return ()
1695 | null dup_roots = return ()
1696 | otherwise = multiRootsErr (head dup_roots)
1698 dup_roots :: [[ModSummary]] -- Each at least of length 2
1699 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1701 loop :: [(Located ModuleName,IsBootInterface)]
1702 -- Work list: process these modules
1703 -> NodeMap [ModSummary]
1704 -- Visited set; the range is a list because
1705 -- the roots can have the same module names
1706 -- if allow_dup_roots is True
1708 -- The result includes the worklist, except
1709 -- for those mentioned in the visited set
1710 loop [] done = return (concat (nodeMapElts done))
1711 loop ((wanted_mod, is_boot) : ss) done
1712 | Just summs <- lookupFM done key
1713 = if isSingleton summs then
1716 do { multiRootsErr summs; return [] }
1717 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1718 is_boot wanted_mod Nothing excl_mods
1720 Nothing -> loop ss done
1721 Just s -> loop (msDeps s ++ ss)
1722 (addToFM done key [s]) }
1724 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1726 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1727 mkRootMap summaries = addListToFM_C (++) emptyFM
1728 [ (msKey s, [s]) | s <- summaries ]
1730 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1731 -- (msDeps s) returns the dependencies of the ModSummary s.
1732 -- A wrinkle is that for a {-# SOURCE #-} import we return
1733 -- *both* the hs-boot file
1734 -- *and* the source file
1735 -- as "dependencies". That ensures that the list of all relevant
1736 -- modules always contains B.hs if it contains B.hs-boot.
1737 -- Remember, this pass isn't doing the topological sort. It's
1738 -- just gathering the list of all relevant ModSummaries
1740 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1741 ++ [ (m,False) | m <- ms_imps s ]
1743 -----------------------------------------------------------------------------
1744 -- Summarising modules
1746 -- We have two types of summarisation:
1748 -- * Summarise a file. This is used for the root module(s) passed to
1749 -- cmLoadModules. The file is read, and used to determine the root
1750 -- module name. The module name may differ from the filename.
1752 -- * Summarise a module. We are given a module name, and must provide
1753 -- a summary. The finder is used to locate the file in which the module
1758 -> [ModSummary] -- old summaries
1759 -> FilePath -- source file name
1760 -> Maybe Phase -- start phase
1761 -> Maybe (StringBuffer,ClockTime)
1764 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1765 -- we can use a cached summary if one is available and the
1766 -- source file hasn't changed, But we have to look up the summary
1767 -- by source file, rather than module name as we do in summarise.
1768 | Just old_summary <- findSummaryBySourceFile old_summaries file
1770 let location = ms_location old_summary
1772 -- return the cached summary if the source didn't change
1773 src_timestamp <- case maybe_buf of
1774 Just (_,t) -> return t
1775 Nothing -> getModificationTime file
1776 -- The file exists; we checked in getRootSummary above.
1777 -- If it gets removed subsequently, then this
1778 -- getModificationTime may fail, but that's the right
1781 if ms_hs_date old_summary == src_timestamp
1782 then do -- update the object-file timestamp
1784 if isObjectTarget (hscTarget (hsc_dflags hsc_env)) -- #1205
1785 then getObjTimestamp location False
1787 return old_summary{ ms_obj_date = obj_timestamp }
1795 let dflags = hsc_dflags hsc_env
1797 (dflags', hspp_fn, buf)
1798 <- preprocessFile hsc_env file mb_phase maybe_buf
1800 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1802 -- Make a ModLocation for this file
1803 location <- mkHomeModLocation dflags mod_name file
1805 -- Tell the Finder cache where it is, so that subsequent calls
1806 -- to findModule will find it, even if it's not on any search path
1807 mod <- addHomeModuleToFinder hsc_env mod_name location
1809 src_timestamp <- case maybe_buf of
1810 Just (_,t) -> return t
1811 Nothing -> getModificationTime file
1812 -- getMofificationTime may fail
1814 -- when the user asks to load a source file by name, we only
1815 -- use an object file if -fobject-code is on. See #1205.
1817 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1818 then modificationTimeIfExists (ml_obj_file location)
1821 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1822 ms_location = location,
1823 ms_hspp_file = hspp_fn,
1824 ms_hspp_opts = dflags',
1825 ms_hspp_buf = Just buf,
1826 ms_srcimps = srcimps, ms_imps = the_imps,
1827 ms_hs_date = src_timestamp,
1828 ms_obj_date = obj_timestamp })
1830 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1831 findSummaryBySourceFile summaries file
1832 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1833 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1837 -- Summarise a module, and pick up source and timestamp.
1840 -> NodeMap ModSummary -- Map of old summaries
1841 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1842 -> Located ModuleName -- Imported module to be summarised
1843 -> Maybe (StringBuffer, ClockTime)
1844 -> [ModuleName] -- Modules to exclude
1845 -> IO (Maybe ModSummary) -- Its new summary
1847 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1848 | wanted_mod `elem` excl_mods
1851 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1852 = do -- Find its new timestamp; all the
1853 -- ModSummaries in the old map have valid ml_hs_files
1854 let location = ms_location old_summary
1855 src_fn = expectJust "summariseModule" (ml_hs_file location)
1857 -- check the modification time on the source file, and
1858 -- return the cached summary if it hasn't changed. If the
1859 -- file has disappeared, we need to call the Finder again.
1861 Just (_,t) -> check_timestamp old_summary location src_fn t
1863 m <- System.IO.Error.try (getModificationTime src_fn)
1865 Right t -> check_timestamp old_summary location src_fn t
1866 Left e | isDoesNotExistError e -> find_it
1867 | otherwise -> ioError e
1869 | otherwise = find_it
1871 dflags = hsc_dflags hsc_env
1873 hsc_src = if is_boot then HsBootFile else HsSrcFile
1875 check_timestamp old_summary location src_fn src_timestamp
1876 | ms_hs_date old_summary == src_timestamp = do
1877 -- update the object-file timestamp
1878 obj_timestamp <- getObjTimestamp location is_boot
1879 return (Just old_summary{ ms_obj_date = obj_timestamp })
1881 -- source changed: re-summarise.
1882 new_summary location (ms_mod old_summary) src_fn src_timestamp
1885 -- Don't use the Finder's cache this time. If the module was
1886 -- previously a package module, it may have now appeared on the
1887 -- search path, so we want to consider it to be a home module. If
1888 -- the module was previously a home module, it may have moved.
1889 uncacheModule hsc_env wanted_mod
1890 found <- findImportedModule hsc_env wanted_mod Nothing
1893 | isJust (ml_hs_file location) ->
1895 just_found location mod
1897 -- Drop external-pkg
1898 ASSERT(modulePackageId mod /= thisPackage dflags)
1902 err -> noModError dflags loc wanted_mod err
1905 just_found location mod = do
1906 -- Adjust location to point to the hs-boot source file,
1907 -- hi file, object file, when is_boot says so
1908 let location' | is_boot = addBootSuffixLocn location
1909 | otherwise = location
1910 src_fn = expectJust "summarise2" (ml_hs_file location')
1912 -- Check that it exists
1913 -- It might have been deleted since the Finder last found it
1914 maybe_t <- modificationTimeIfExists src_fn
1916 Nothing -> noHsFileErr loc src_fn
1917 Just t -> new_summary location' mod src_fn t
1920 new_summary location mod src_fn src_timestamp
1922 -- Preprocess the source file and get its imports
1923 -- The dflags' contains the OPTIONS pragmas
1924 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
1925 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1927 when (mod_name /= wanted_mod) $
1928 throwDyn $ mkPlainErrMsg mod_loc $
1929 text "File name does not match module name:"
1930 $$ text "Saw:" <+> quotes (ppr mod_name)
1931 $$ text "Expected:" <+> quotes (ppr wanted_mod)
1933 -- Find the object timestamp, and return the summary
1934 obj_timestamp <- getObjTimestamp location is_boot
1936 return (Just ( ModSummary { ms_mod = mod,
1937 ms_hsc_src = hsc_src,
1938 ms_location = location,
1939 ms_hspp_file = hspp_fn,
1940 ms_hspp_opts = dflags',
1941 ms_hspp_buf = Just buf,
1942 ms_srcimps = srcimps,
1944 ms_hs_date = src_timestamp,
1945 ms_obj_date = obj_timestamp }))
1948 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1949 getObjTimestamp location is_boot
1950 = if is_boot then return Nothing
1951 else modificationTimeIfExists (ml_obj_file location)
1954 preprocessFile :: HscEnv -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1955 -> IO (DynFlags, FilePath, StringBuffer)
1956 preprocessFile hsc_env src_fn mb_phase Nothing
1958 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
1959 buf <- hGetStringBuffer hspp_fn
1960 return (dflags', hspp_fn, buf)
1962 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
1964 let dflags = hsc_dflags hsc_env
1965 -- case we bypass the preprocessing stage?
1967 local_opts = getOptions dflags buf src_fn
1969 (dflags', leftovers, warns) <- parseDynamicFlags dflags (map unLoc local_opts)
1970 checkProcessArgsResult leftovers src_fn
1971 handleFlagWarnings dflags' warns
1975 | Just (Unlit _) <- mb_phase = True
1976 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1977 -- note: local_opts is only required if there's no Unlit phase
1978 | dopt Opt_Cpp dflags' = True
1979 | dopt Opt_Pp dflags' = True
1982 when needs_preprocessing $
1983 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1985 return (dflags', src_fn, buf)
1988 -----------------------------------------------------------------------------
1990 -----------------------------------------------------------------------------
1992 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1993 -- ToDo: we don't have a proper line number for this error
1994 noModError dflags loc wanted_mod err
1995 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1997 noHsFileErr :: SrcSpan -> String -> a
1998 noHsFileErr loc path
1999 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2001 packageModErr :: ModuleName -> a
2003 = throwDyn $ mkPlainErrMsg noSrcSpan $
2004 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2006 multiRootsErr :: [ModSummary] -> IO ()
2007 multiRootsErr [] = panic "multiRootsErr"
2008 multiRootsErr summs@(summ1:_)
2009 = throwDyn $ mkPlainErrMsg noSrcSpan $
2010 text "module" <+> quotes (ppr mod) <+>
2011 text "is defined in multiple files:" <+>
2012 sep (map text files)
2015 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2017 cyclicModuleErr :: [ModSummary] -> SDoc
2019 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2020 2 (vcat (map show_one ms))
2022 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2023 nest 2 $ ptext (sLit "imports:") <+>
2024 (pp_imps HsBootFile (ms_srcimps ms)
2025 $$ pp_imps HsSrcFile (ms_imps ms))]
2026 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2027 pp_imps src mods = fsep (map (show_mod src) mods)
2030 -- | Inform GHC that the working directory has changed. GHC will flush
2031 -- its cache of module locations, since it may no longer be valid.
2032 -- Note: if you change the working directory, you should also unload
2033 -- the current program (set targets to empty, followed by load).
2034 workingDirectoryChanged :: Session -> IO ()
2035 workingDirectoryChanged s = withSession s $ flushFinderCaches
2037 -- -----------------------------------------------------------------------------
2038 -- inspecting the session
2040 -- | Get the module dependency graph.
2041 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
2042 getModuleGraph s = withSession s (return . hsc_mod_graph)
2044 isLoaded :: Session -> ModuleName -> IO Bool
2045 isLoaded s m = withSession s $ \hsc_env ->
2046 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2048 getBindings :: Session -> IO [TyThing]
2049 getBindings s = withSession s $ \hsc_env ->
2050 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2051 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2053 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2054 filtered = foldr f (const []) tmp_ids emptyUniqSet
2056 | uniq `elementOfUniqSet` set = rest set
2057 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2058 where uniq = getUnique (nameOccName (idName id))
2062 getPrintUnqual :: Session -> IO PrintUnqualified
2063 getPrintUnqual s = withSession s $ \hsc_env ->
2064 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2066 -- | Container for information about a 'Module'.
2067 data ModuleInfo = ModuleInfo {
2068 minf_type_env :: TypeEnv,
2069 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2070 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2071 minf_instances :: [Instance]
2073 ,minf_modBreaks :: ModBreaks
2075 -- ToDo: this should really contain the ModIface too
2077 -- We don't want HomeModInfo here, because a ModuleInfo applies
2078 -- to package modules too.
2080 -- | Request information about a loaded 'Module'
2081 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
2082 getModuleInfo s mdl = withSession s $ \hsc_env -> do
2083 let mg = hsc_mod_graph hsc_env
2084 if mdl `elem` map ms_mod mg
2085 then getHomeModuleInfo hsc_env (moduleName mdl)
2087 {- if isHomeModule (hsc_dflags hsc_env) mdl
2089 else -} getPackageModuleInfo hsc_env mdl
2090 -- getPackageModuleInfo will attempt to find the interface, so
2091 -- we don't want to call it for a home module, just in case there
2092 -- was a problem loading the module and the interface doesn't
2093 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2095 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2097 getPackageModuleInfo hsc_env mdl = do
2098 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2100 Nothing -> return Nothing
2102 eps <- readIORef (hsc_EPS hsc_env)
2104 names = availsToNameSet avails
2106 tys = [ ty | name <- concatMap availNames avails,
2107 Just ty <- [lookupTypeEnv pte name] ]
2109 return (Just (ModuleInfo {
2110 minf_type_env = mkTypeEnv tys,
2111 minf_exports = names,
2112 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2113 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2114 minf_modBreaks = emptyModBreaks
2117 getPackageModuleInfo _hsc_env _mdl = do
2118 -- bogusly different for non-GHCI (ToDo)
2122 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2123 getHomeModuleInfo hsc_env mdl =
2124 case lookupUFM (hsc_HPT hsc_env) mdl of
2125 Nothing -> return Nothing
2127 let details = hm_details hmi
2128 return (Just (ModuleInfo {
2129 minf_type_env = md_types details,
2130 minf_exports = availsToNameSet (md_exports details),
2131 minf_rdr_env = mi_globals $! hm_iface hmi,
2132 minf_instances = md_insts details
2134 ,minf_modBreaks = getModBreaks hmi
2138 -- | The list of top-level entities defined in a module
2139 modInfoTyThings :: ModuleInfo -> [TyThing]
2140 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2142 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2143 modInfoTopLevelScope minf
2144 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2146 modInfoExports :: ModuleInfo -> [Name]
2147 modInfoExports minf = nameSetToList $! minf_exports minf
2149 -- | Returns the instances defined by the specified module.
2150 -- Warning: currently unimplemented for package modules.
2151 modInfoInstances :: ModuleInfo -> [Instance]
2152 modInfoInstances = minf_instances
2154 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2155 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2157 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2158 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2159 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2161 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2162 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2163 case lookupTypeEnv (minf_type_env minf) name of
2164 Just tyThing -> return (Just tyThing)
2166 eps <- readIORef (hsc_EPS hsc_env)
2167 return $! lookupType (hsc_dflags hsc_env)
2168 (hsc_HPT hsc_env) (eps_PTE eps) name
2171 modInfoModBreaks :: ModuleInfo -> ModBreaks
2172 modInfoModBreaks = minf_modBreaks
2175 isDictonaryId :: Id -> Bool
2177 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2179 -- | Looks up a global name: that is, any top-level name in any
2180 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2181 -- the interactive context, and therefore does not require a preceding
2183 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2184 lookupGlobalName s name = withSession s $ \hsc_env -> do
2185 eps <- readIORef (hsc_EPS hsc_env)
2186 return $! lookupType (hsc_dflags hsc_env)
2187 (hsc_HPT hsc_env) (eps_PTE eps) name
2190 -- | get the GlobalRdrEnv for a session
2191 getGRE :: Session -> IO GlobalRdrEnv
2192 getGRE s = withSession s $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2195 -- -----------------------------------------------------------------------------
2196 -- Misc exported utils
2198 dataConType :: DataCon -> Type
2199 dataConType dc = idType (dataConWrapId dc)
2201 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2202 pprParenSymName :: NamedThing a => a -> SDoc
2203 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2205 -- ----------------------------------------------------------------------------
2210 -- - Data and Typeable instances for HsSyn.
2212 -- ToDo: check for small transformations that happen to the syntax in
2213 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2215 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2216 -- to get from TyCons, Ids etc. to TH syntax (reify).
2218 -- :browse will use either lm_toplev or inspect lm_interface, depending
2219 -- on whether the module is interpreted or not.
2221 -- This is for reconstructing refactored source code
2222 -- Calls the lexer repeatedly.
2223 -- ToDo: add comment tokens to token stream
2224 getTokenStream :: Session -> Module -> IO [Located Token]
2227 -- -----------------------------------------------------------------------------
2228 -- Interactive evaluation
2230 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2231 -- filesystem and package database to find the corresponding 'Module',
2232 -- using the algorithm that is used for an @import@ declaration.
2233 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2234 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2236 dflags = hsc_dflags hsc_env
2237 hpt = hsc_HPT hsc_env
2238 this_pkg = thisPackage dflags
2240 case lookupUFM hpt mod_name of
2241 Just mod_info -> return (mi_module (hm_iface mod_info))
2242 _not_a_home_module -> do
2243 res <- findImportedModule hsc_env mod_name maybe_pkg
2245 Found _ m | modulePackageId m /= this_pkg -> return m
2246 | otherwise -> throwDyn (CmdLineError (showSDoc $
2247 text "module" <+> quotes (ppr (moduleName m)) <+>
2248 text "is not loaded"))
2249 err -> let msg = cannotFindModule dflags mod_name err in
2250 throwDyn (CmdLineError (showSDoc msg))
2253 getHistorySpan :: Session -> History -> IO SrcSpan
2254 getHistorySpan sess h = withSession sess $ \hsc_env ->
2255 return$ InteractiveEval.getHistorySpan hsc_env h
2257 obtainTerm :: Session -> Bool -> Id -> IO Term
2258 obtainTerm sess force id = withSession sess $ \hsc_env ->
2259 InteractiveEval.obtainTerm hsc_env force id
2261 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2262 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2263 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2265 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2266 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2267 InteractiveEval.obtainTermB hsc_env bound force id