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, CheckedModule(..),
43 TypecheckedSource, ParsedSource, RenamedSource,
46 -- * Parsing Haddock comments
49 -- * Inspecting the module structure of the program
50 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
55 -- * Inspecting modules
62 modInfoIsExportedName,
65 mkPrintUnqualifiedForModule,
68 PrintUnqualified, alwaysQualify,
70 -- * Interactive evaluation
71 getBindings, getPrintUnqual,
74 setContext, getContext,
83 runStmt, SingleStep(..),
85 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
86 resumeHistory, resumeHistoryIx),
87 History(historyBreakInfo, historyEnclosingDecl),
88 GHC.getHistorySpan, getHistoryModule,
92 InteractiveEval.forward,
95 compileExpr, HValue, dynCompileExpr,
97 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
99 ModBreaks(..), BreakIndex,
100 BreakInfo(breakInfo_number, breakInfo_module),
101 BreakArray, setBreakOn, setBreakOff, getBreak,
104 -- * Abstract syntax elements
110 Module, mkModule, pprModule, moduleName, modulePackageId,
111 ModuleName, mkModuleName, moduleNameString,
115 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
117 RdrName(Qual,Unqual),
121 isImplicitId, isDeadBinder,
122 isExportedId, isLocalId, isGlobalId,
124 isPrimOpId, isFCallId, isClassOpId_maybe,
125 isDataConWorkId, idDataCon,
126 isBottomingId, isDictonaryId,
127 recordSelectorFieldLabel,
129 -- ** Type constructors
131 tyConTyVars, tyConDataCons, tyConArity,
132 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
134 synTyConDefn, synTyConType, synTyConResKind,
140 -- ** Data constructors
142 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
143 dataConIsInfix, isVanillaDataCon,
145 StrictnessMark(..), isMarkedStrict,
149 classMethods, classSCTheta, classTvsFds,
154 instanceDFunId, pprInstance, pprInstanceHdr,
156 -- ** Types and Kinds
157 Type, splitForAllTys, funResultTy,
158 pprParendType, pprTypeApp,
161 ThetaType, pprThetaArrow,
167 module HsSyn, -- ToDo: remove extraneous bits
171 defaultFixity, maxPrecedence,
175 -- ** Source locations
177 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
178 srcLocFile, srcLocLine, srcLocCol,
180 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
181 srcSpanStart, srcSpanEnd,
183 srcSpanStartLine, srcSpanEndLine,
184 srcSpanStartCol, srcSpanEndCol,
187 GhcException(..), showGhcException,
197 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
198 * what StaticFlags should we expose, if any?
201 #include "HsVersions.h"
204 import qualified Linker
205 import Linker ( HValue )
209 import InteractiveEval
214 import TcRnMonad ( initIfaceCheck )
219 import Type hiding (typeKind)
220 import TcType hiding (typeKind)
222 import Var hiding (setIdType)
223 import TysPrim ( alphaTyVars )
228 import Name hiding ( varName )
229 import OccName ( parenSymOcc )
230 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
233 import DriverPipeline
234 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
235 import HeaderInfo ( getImports, getOptions )
237 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
241 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
250 import Bag ( unitBag, listToBag )
251 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
252 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
254 import qualified ErrUtils
256 import StringBuffer ( StringBuffer, hGetStringBuffer )
259 import Maybes ( expectJust, mapCatMaybes )
261 import HaddockLex ( tokenise )
263 import Control.Concurrent
264 import System.Directory ( getModificationTime, doesFileExist )
267 import qualified Data.List as List
269 import System.Exit ( exitWith, ExitCode(..) )
270 import System.Time ( ClockTime )
271 import Control.Exception as Exception hiding (handle)
274 import System.IO.Error ( try, isDoesNotExistError )
275 import Prelude hiding (init)
278 -- -----------------------------------------------------------------------------
279 -- Exception handlers
281 -- | Install some default exception handlers and run the inner computation.
282 -- Unless you want to handle exceptions yourself, you should wrap this around
283 -- the top level of your program. The default handlers output the error
284 -- message(s) to stderr and exit cleanly.
285 defaultErrorHandler :: DynFlags -> IO a -> IO a
286 defaultErrorHandler dflags inner =
287 -- top-level exception handler: any unrecognised exception is a compiler bug.
288 handle (\exception -> do
291 -- an IO exception probably isn't our fault, so don't panic
293 fatalErrorMsg dflags (text (show exception))
294 AsyncException StackOverflow ->
295 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
297 fatalErrorMsg dflags (text (show (Panic (show exception))))
298 exitWith (ExitFailure 1)
301 -- program errors: messages with locations attached. Sometimes it is
302 -- convenient to just throw these as exceptions.
303 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
304 exitWith (ExitFailure 1)) $
306 -- error messages propagated as exceptions
307 handleDyn (\dyn -> do
310 PhaseFailed _ code -> exitWith code
311 Interrupted -> exitWith (ExitFailure 1)
312 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
313 exitWith (ExitFailure 1)
317 -- | Install a default cleanup handler to remove temporary files
318 -- deposited by a GHC run. This is seperate from
319 -- 'defaultErrorHandler', because you might want to override the error
320 -- handling, but still get the ordinary cleanup behaviour.
321 defaultCleanupHandler :: DynFlags -> IO a -> IO a
322 defaultCleanupHandler dflags inner =
323 -- make sure we clean up after ourselves
324 later (do cleanTempFiles dflags
327 -- exceptions will be blocked while we clean the temporary files,
328 -- so there shouldn't be any difficulty if we receive further
333 -- | Starts a new session. A session consists of a set of loaded
334 -- modules, a set of options (DynFlags), and an interactive context.
335 newSession :: Maybe FilePath -> IO Session
336 newSession mb_top_dir = do
338 main_thread <- myThreadId
339 modifyMVar_ interruptTargetThread (return . (main_thread :))
340 installSignalHandlers
343 dflags0 <- initSysTools mb_top_dir defaultDynFlags
344 dflags <- initDynFlags dflags0
345 env <- newHscEnv dflags
349 -- tmp: this breaks the abstraction, but required because DriverMkDepend
350 -- needs to call the Finder. ToDo: untangle this.
351 sessionHscEnv :: Session -> IO HscEnv
352 sessionHscEnv (Session ref) = readIORef ref
354 -- -----------------------------------------------------------------------------
357 -- | Grabs the DynFlags from the Session
358 getSessionDynFlags :: Session -> IO DynFlags
359 getSessionDynFlags s = withSession s (return . hsc_dflags)
361 -- | Updates the DynFlags in a Session. This also reads
362 -- the package database (unless it has already been read),
363 -- and prepares the compilers knowledge about packages. It
364 -- can be called again to load new packages: just add new
365 -- package flags to (packageFlags dflags).
367 -- Returns a list of new packages that may need to be linked in using
368 -- the dynamic linker (see 'linkPackages') as a result of new package
369 -- flags. If you are not doing linking or doing static linking, you
370 -- can ignore the list of packages returned.
372 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
373 setSessionDynFlags (Session ref) dflags = do
374 hsc_env <- readIORef ref
375 (dflags', preload) <- initPackages dflags
376 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
379 -- | If there is no -o option, guess the name of target executable
380 -- by using top-level source file name as a base.
381 guessOutputFile :: Session -> IO ()
382 guessOutputFile s = modifySession s $ \env ->
383 let dflags = hsc_dflags env
384 mod_graph = hsc_mod_graph env
385 mainModuleSrcPath, guessedName :: Maybe String
386 mainModuleSrcPath = do
387 let isMain = (== mainModIs dflags) . ms_mod
388 [ms] <- return (filter isMain mod_graph)
389 ml_hs_file (ms_location ms)
390 guessedName = fmap basenameOf mainModuleSrcPath
392 case outputFile dflags of
394 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
396 -- -----------------------------------------------------------------------------
399 -- ToDo: think about relative vs. absolute file paths. And what
400 -- happens when the current directory changes.
402 -- | Sets the targets for this session. Each target may be a module name
403 -- or a filename. The targets correspond to the set of root modules for
404 -- the program\/library. Unloading the current program is achieved by
405 -- setting the current set of targets to be empty, followed by load.
406 setTargets :: Session -> [Target] -> IO ()
407 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
409 -- | returns the current set of targets
410 getTargets :: Session -> IO [Target]
411 getTargets s = withSession s (return . hsc_targets)
413 -- | Add another target
414 addTarget :: Session -> Target -> IO ()
416 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
419 removeTarget :: Session -> TargetId -> IO ()
420 removeTarget s target_id
421 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
423 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
425 -- Attempts to guess what Target a string refers to. This function implements
426 -- the --make/GHCi command-line syntax for filenames:
428 -- - if the string looks like a Haskell source filename, then interpret
430 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
432 -- - otherwise interpret the string as a module name
434 guessTarget :: String -> Maybe Phase -> IO Target
435 guessTarget file (Just phase)
436 = return (Target (TargetFile file (Just phase)) Nothing)
437 guessTarget file Nothing
438 | isHaskellSrcFilename file
439 = return (Target (TargetFile file Nothing) Nothing)
441 = do exists <- doesFileExist hs_file
443 then return (Target (TargetFile hs_file Nothing) Nothing)
445 exists <- doesFileExist lhs_file
447 then return (Target (TargetFile lhs_file Nothing) Nothing)
449 return (Target (TargetModule (mkModuleName file)) Nothing)
451 hs_file = file `joinFileExt` "hs"
452 lhs_file = file `joinFileExt` "lhs"
454 -- -----------------------------------------------------------------------------
455 -- Extending the program scope
457 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
458 extendGlobalRdrScope session rdrElts
459 = modifySession session $ \hscEnv ->
460 let global_rdr = hsc_global_rdr_env hscEnv
461 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
463 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
464 setGlobalRdrScope session rdrElts
465 = modifySession session $ \hscEnv ->
466 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
468 extendGlobalTypeScope :: Session -> [Id] -> IO ()
469 extendGlobalTypeScope session ids
470 = modifySession session $ \hscEnv ->
471 let global_type = hsc_global_type_env hscEnv
472 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
474 setGlobalTypeScope :: Session -> [Id] -> IO ()
475 setGlobalTypeScope session ids
476 = modifySession session $ \hscEnv ->
477 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
479 -- -----------------------------------------------------------------------------
480 -- Parsing Haddock comments
482 parseHaddockComment :: String -> Either String (HsDoc RdrName)
483 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
485 -- -----------------------------------------------------------------------------
486 -- Loading the program
488 -- Perform a dependency analysis starting from the current targets
489 -- and update the session with the new module graph.
490 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
491 depanal (Session ref) excluded_mods allow_dup_roots = do
492 hsc_env <- readIORef ref
494 dflags = hsc_dflags hsc_env
495 targets = hsc_targets hsc_env
496 old_graph = hsc_mod_graph hsc_env
498 showPass dflags "Chasing dependencies"
499 debugTraceMsg dflags 2 (hcat [
500 text "Chasing modules from: ",
501 hcat (punctuate comma (map pprTarget targets))])
503 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
505 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
510 -- | The result of load.
512 = LoadOk Errors -- ^ all specified targets were loaded successfully.
513 | LoadFailed Errors -- ^ not all modules were loaded.
515 type Errors = [String]
517 data ErrMsg = ErrMsg {
518 errMsgSeverity :: Severity, -- warning, error, etc.
519 errMsgSpans :: [SrcSpan],
520 errMsgShortDoc :: Doc,
521 errMsgExtraInfo :: Doc
527 | LoadUpTo ModuleName
528 | LoadDependenciesOf ModuleName
530 -- | Try to load the program. If a Module is supplied, then just
531 -- attempt to load up to this target. If no Module is supplied,
532 -- then try to load all targets.
533 load :: Session -> LoadHowMuch -> IO SuccessFlag
534 load s@(Session ref) how_much
536 -- Dependency analysis first. Note that this fixes the module graph:
537 -- even if we don't get a fully successful upsweep, the full module
538 -- graph is still retained in the Session. We can tell which modules
539 -- were successfully loaded by inspecting the Session's HPT.
540 mb_graph <- depanal s [] False
542 Just mod_graph -> catchingFailure $ load2 s how_much mod_graph
543 Nothing -> return Failed
544 where catchingFailure f = f `Exception.catch` \e -> do
545 hsc_env <- readIORef ref
546 -- trac #1565 / test ghci021:
547 -- let bindings may explode if we try to use them after
549 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
552 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
553 load2 s@(Session ref) how_much mod_graph = do
555 hsc_env <- readIORef ref
557 let hpt1 = hsc_HPT hsc_env
558 let dflags = hsc_dflags hsc_env
560 -- The "bad" boot modules are the ones for which we have
561 -- B.hs-boot in the module graph, but no B.hs
562 -- The downsweep should have ensured this does not happen
564 let all_home_mods = [ms_mod_name s
565 | s <- mod_graph, not (isBootSummary s)]
566 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
567 not (ms_mod_name s `elem` all_home_mods)]
568 ASSERT( null bad_boot_mods ) return ()
570 -- mg2_with_srcimps drops the hi-boot nodes, returning a
571 -- graph with cycles. Among other things, it is used for
572 -- backing out partially complete cycles following a failed
573 -- upsweep, and for removing from hpt all the modules
574 -- not in strict downwards closure, during calls to compile.
575 let mg2_with_srcimps :: [SCC ModSummary]
576 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
578 -- If we can determine that any of the {-# SOURCE #-} imports
579 -- are definitely unnecessary, then emit a warning.
580 warnUnnecessarySourceImports dflags mg2_with_srcimps
583 -- check the stability property for each module.
584 stable_mods@(stable_obj,stable_bco)
585 = checkStability hpt1 mg2_with_srcimps all_home_mods
587 -- prune bits of the HPT which are definitely redundant now,
589 pruned_hpt = pruneHomePackageTable hpt1
590 (flattenSCCs mg2_with_srcimps)
595 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
596 text "Stable BCO:" <+> ppr stable_bco)
598 -- Unload any modules which are going to be re-linked this time around.
599 let stable_linkables = [ linkable
600 | m <- stable_obj++stable_bco,
601 Just hmi <- [lookupUFM pruned_hpt m],
602 Just linkable <- [hm_linkable hmi] ]
603 unload hsc_env stable_linkables
605 -- We could at this point detect cycles which aren't broken by
606 -- a source-import, and complain immediately, but it seems better
607 -- to let upsweep_mods do this, so at least some useful work gets
608 -- done before the upsweep is abandoned.
609 --hPutStrLn stderr "after tsort:\n"
610 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
612 -- Now do the upsweep, calling compile for each module in
613 -- turn. Final result is version 3 of everything.
615 -- Topologically sort the module graph, this time including hi-boot
616 -- nodes, and possibly just including the portion of the graph
617 -- reachable from the module specified in the 2nd argument to load.
618 -- This graph should be cycle-free.
619 -- If we're restricting the upsweep to a portion of the graph, we
620 -- also want to retain everything that is still stable.
621 let full_mg :: [SCC ModSummary]
622 full_mg = topSortModuleGraph False mod_graph Nothing
624 maybe_top_mod = case how_much of
626 LoadDependenciesOf m -> Just m
629 partial_mg0 :: [SCC ModSummary]
630 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
632 -- LoadDependenciesOf m: we want the upsweep to stop just
633 -- short of the specified module (unless the specified module
636 | LoadDependenciesOf _mod <- how_much
637 = ASSERT( case last partial_mg0 of
638 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
639 List.init partial_mg0
645 | AcyclicSCC ms <- full_mg,
646 ms_mod_name ms `elem` stable_obj++stable_bco,
647 ms_mod_name ms `notElem` [ ms_mod_name ms' |
648 AcyclicSCC ms' <- partial_mg ] ]
650 mg = stable_mg ++ partial_mg
652 -- clean up between compilations
653 let cleanup = cleanTempFilesExcept dflags
654 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
656 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
658 (upsweep_ok, hsc_env1, modsUpswept)
659 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
660 pruned_hpt stable_mods cleanup mg
662 -- Make modsDone be the summaries for each home module now
663 -- available; this should equal the domain of hpt3.
664 -- Get in in a roughly top .. bottom order (hence reverse).
666 let modsDone = reverse modsUpswept
668 -- Try and do linking in some form, depending on whether the
669 -- upsweep was completely or only partially successful.
671 if succeeded upsweep_ok
674 -- Easy; just relink it all.
675 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
677 -- Clean up after ourselves
678 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
680 -- Issue a warning for the confusing case where the user
681 -- said '-o foo' but we're not going to do any linking.
682 -- We attempt linking if either (a) one of the modules is
683 -- called Main, or (b) the user said -no-hs-main, indicating
684 -- that main() is going to come from somewhere else.
686 let ofile = outputFile dflags
687 let no_hs_main = dopt Opt_NoHsMain dflags
689 main_mod = mainModIs dflags
690 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
691 do_linking = a_root_is_Main || no_hs_main
693 when (ghcLink dflags == LinkBinary
694 && isJust ofile && not do_linking) $
695 debugTraceMsg dflags 1 $
696 text ("Warning: output was redirected with -o, " ++
697 "but no output will be generated\n" ++
698 "because there is no " ++
699 moduleNameString (moduleName main_mod) ++ " module.")
701 -- link everything together
702 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
704 loadFinish Succeeded linkresult ref hsc_env1
707 -- Tricky. We need to back out the effects of compiling any
708 -- half-done cycles, both so as to clean up the top level envs
709 -- and to avoid telling the interactive linker to link them.
710 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
713 = map ms_mod modsDone
714 let mods_to_zap_names
715 = findPartiallyCompletedCycles modsDone_names
718 = filter ((`notElem` mods_to_zap_names).ms_mod)
721 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
724 -- Clean up after ourselves
725 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
727 -- there should be no Nothings where linkables should be, now
728 ASSERT(all (isJust.hm_linkable)
729 (eltsUFM (hsc_HPT hsc_env))) do
731 -- Link everything together
732 linkresult <- link (ghcLink dflags) dflags False hpt4
734 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
735 loadFinish Failed linkresult ref hsc_env4
737 -- Finish up after a load.
739 -- If the link failed, unload everything and return.
740 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
741 loadFinish _all_ok Failed ref hsc_env
742 = do unload hsc_env []
743 writeIORef ref $! discardProg hsc_env
746 -- Empty the interactive context and set the module context to the topmost
747 -- newly loaded module, or the Prelude if none were loaded.
748 loadFinish all_ok Succeeded ref hsc_env
749 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
753 -- Forget the current program, but retain the persistent info in HscEnv
754 discardProg :: HscEnv -> HscEnv
756 = hsc_env { hsc_mod_graph = emptyMG,
757 hsc_IC = emptyInteractiveContext,
758 hsc_HPT = emptyHomePackageTable }
760 -- used to fish out the preprocess output files for the purposes of
761 -- cleaning up. The preprocessed file *might* be the same as the
762 -- source file, but that doesn't do any harm.
763 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
764 ppFilesFromSummaries summaries = map ms_hspp_file summaries
766 -- -----------------------------------------------------------------------------
770 CheckedModule { parsedSource :: ParsedSource,
771 renamedSource :: Maybe RenamedSource,
772 typecheckedSource :: Maybe TypecheckedSource,
773 checkedModuleInfo :: Maybe ModuleInfo,
774 coreBinds :: Maybe [CoreBind]
776 -- ToDo: improvements that could be made here:
777 -- if the module succeeded renaming but not typechecking,
778 -- we can still get back the GlobalRdrEnv and exports, so
779 -- perhaps the ModuleInfo should be split up into separate
780 -- fields within CheckedModule.
782 type ParsedSource = Located (HsModule RdrName)
783 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
784 Maybe (HsDoc Name), HaddockModInfo Name)
785 type TypecheckedSource = LHsBinds Id
788 -- - things that aren't in the output of the typechecker right now:
792 -- - type/data/newtype declarations
793 -- - class declarations
795 -- - extra things in the typechecker's output:
796 -- - default methods are turned into top-level decls.
797 -- - dictionary bindings
800 -- | This is the way to get access to parsed and typechecked source code
801 -- for a module. 'checkModule' attempts to typecheck the module. If
802 -- successful, it returns the abstract syntax for the module.
803 -- If compileToCore is true, it also desugars the module and returns the
804 -- resulting Core bindings as a component of the CheckedModule.
805 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
806 checkModule (Session ref) mod compileToCore = do
807 -- parse & typecheck the module
808 hsc_env <- readIORef ref
809 let mg = hsc_mod_graph hsc_env
810 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
813 mbChecked <- hscFileCheck
814 hsc_env{hsc_dflags=ms_hspp_opts ms}
817 Nothing -> return Nothing
818 Just (HscChecked parsed renamed Nothing _) ->
819 return (Just (CheckedModule {
820 parsedSource = parsed,
821 renamedSource = renamed,
822 typecheckedSource = Nothing,
823 checkedModuleInfo = Nothing,
824 coreBinds = Nothing }))
825 Just (HscChecked parsed renamed
826 (Just (tc_binds, rdr_env, details))
827 maybeCoreBinds) -> do
828 let minf = ModuleInfo {
829 minf_type_env = md_types details,
830 minf_exports = availsToNameSet $
832 minf_rdr_env = Just rdr_env,
833 minf_instances = md_insts details
835 ,minf_modBreaks = emptyModBreaks
838 return (Just (CheckedModule {
839 parsedSource = parsed,
840 renamedSource = renamed,
841 typecheckedSource = Just tc_binds,
842 checkedModuleInfo = Just minf,
843 coreBinds = maybeCoreBinds}))
845 -- | This is the way to get access to the Core bindings corresponding
846 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
847 -- desugar the module, then returns the resulting list of Core bindings if
849 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
850 compileToCore session fn = do
851 -- First, set the target to the desired filename
852 target <- guessTarget fn Nothing
853 addTarget session target
854 load session LoadAllTargets
855 -- Then find dependencies
856 maybeModGraph <- depanal session [] True
857 case maybeModGraph of
858 Nothing -> return Nothing
860 let modSummary = expectJust "compileToCore" $
861 find ((== fn) . msHsFilePath) modGraph
862 -- Now we have the module name;
863 -- parse, typecheck and desugar the module
864 let mod = ms_mod_name modSummary
865 maybeCheckedModule <- checkModule session mod True
866 case maybeCheckedModule of
867 Nothing -> return Nothing
868 Just checkedMod -> return $ coreBinds checkedMod
869 -- ---------------------------------------------------------------------------
872 unload :: HscEnv -> [Linkable] -> IO ()
873 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
874 = case ghcLink (hsc_dflags hsc_env) of
876 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
878 LinkInMemory -> panic "unload: no interpreter"
879 -- urgh. avoid warnings:
880 hsc_env stable_linkables
884 -- -----------------------------------------------------------------------------
888 Stability tells us which modules definitely do not need to be recompiled.
889 There are two main reasons for having stability:
891 - avoid doing a complete upsweep of the module graph in GHCi when
892 modules near the bottom of the tree have not changed.
894 - to tell GHCi when it can load object code: we can only load object code
895 for a module when we also load object code fo all of the imports of the
896 module. So we need to know that we will definitely not be recompiling
897 any of these modules, and we can use the object code.
899 The stability check is as follows. Both stableObject and
900 stableBCO are used during the upsweep phase later.
903 stable m = stableObject m || stableBCO m
906 all stableObject (imports m)
907 && old linkable does not exist, or is == on-disk .o
908 && date(on-disk .o) > date(.hs)
911 all stable (imports m)
912 && date(BCO) > date(.hs)
915 These properties embody the following ideas:
917 - if a module is stable, then:
918 - if it has been compiled in a previous pass (present in HPT)
919 then it does not need to be compiled or re-linked.
920 - if it has not been compiled in a previous pass,
921 then we only need to read its .hi file from disk and
922 link it to produce a ModDetails.
924 - if a modules is not stable, we will definitely be at least
925 re-linking, and possibly re-compiling it during the upsweep.
926 All non-stable modules can (and should) therefore be unlinked
929 - Note that objects are only considered stable if they only depend
930 on other objects. We can't link object code against byte code.
934 :: HomePackageTable -- HPT from last compilation
935 -> [SCC ModSummary] -- current module graph (cyclic)
936 -> [ModuleName] -- all home modules
937 -> ([ModuleName], -- stableObject
938 [ModuleName]) -- stableBCO
940 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
942 checkSCC (stable_obj, stable_bco) scc0
943 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
944 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
945 | otherwise = (stable_obj, stable_bco)
947 scc = flattenSCC scc0
948 scc_mods = map ms_mod_name scc
949 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
951 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
952 -- all imports outside the current SCC, but in the home pkg
954 stable_obj_imps = map (`elem` stable_obj) scc_allimps
955 stable_bco_imps = map (`elem` stable_bco) scc_allimps
962 and (zipWith (||) stable_obj_imps stable_bco_imps)
966 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
970 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
971 Just hmi | Just l <- hm_linkable hmi
972 -> isObjectLinkable l && t == linkableTime l
974 -- why '>=' rather than '>' above? If the filesystem stores
975 -- times to the nearset second, we may occasionally find that
976 -- the object & source have the same modification time,
977 -- especially if the source was automatically generated
978 -- and compiled. Using >= is slightly unsafe, but it matches
982 = case lookupUFM hpt (ms_mod_name ms) of
983 Just hmi | Just l <- hm_linkable hmi ->
984 not (isObjectLinkable l) &&
985 linkableTime l >= ms_hs_date ms
988 ms_allimps :: ModSummary -> [ModuleName]
989 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
991 -- -----------------------------------------------------------------------------
992 -- Prune the HomePackageTable
994 -- Before doing an upsweep, we can throw away:
996 -- - For non-stable modules:
997 -- - all ModDetails, all linked code
998 -- - all unlinked code that is out of date with respect to
1001 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1002 -- space at the end of the upsweep, because the topmost ModDetails of the
1003 -- old HPT holds on to the entire type environment from the previous
1006 pruneHomePackageTable
1009 -> ([ModuleName],[ModuleName])
1012 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1015 | is_stable modl = hmi'
1016 | otherwise = hmi'{ hm_details = emptyModDetails }
1018 modl = moduleName (mi_module (hm_iface hmi))
1019 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1020 = hmi{ hm_linkable = Nothing }
1023 where ms = expectJust "prune" (lookupUFM ms_map modl)
1025 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1027 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1029 -- -----------------------------------------------------------------------------
1031 -- Return (names of) all those in modsDone who are part of a cycle
1032 -- as defined by theGraph.
1033 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1034 findPartiallyCompletedCycles modsDone theGraph
1038 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1039 chew ((CyclicSCC vs):rest)
1040 = let names_in_this_cycle = nub (map ms_mod vs)
1042 = nub ([done | done <- modsDone,
1043 done `elem` names_in_this_cycle])
1044 chewed_rest = chew rest
1046 if notNull mods_in_this_cycle
1047 && length mods_in_this_cycle < length names_in_this_cycle
1048 then mods_in_this_cycle ++ chewed_rest
1051 -- -----------------------------------------------------------------------------
1054 -- This is where we compile each module in the module graph, in a pass
1055 -- from the bottom to the top of the graph.
1057 -- There better had not be any cyclic groups here -- we check for them.
1060 :: HscEnv -- Includes initially-empty HPT
1061 -> HomePackageTable -- HPT from last time round (pruned)
1062 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1063 -> IO () -- How to clean up unwanted tmp files
1064 -> [SCC ModSummary] -- Mods to do (the worklist)
1066 HscEnv, -- With an updated HPT
1067 [ModSummary]) -- Mods which succeeded
1069 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1070 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1071 return (res, hsc_env, reverse done)
1074 upsweep' hsc_env _old_hpt done
1076 = return (Succeeded, hsc_env, done)
1078 upsweep' hsc_env _old_hpt done
1079 (CyclicSCC ms:_) _ _
1080 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1081 return (Failed, hsc_env, done)
1083 upsweep' hsc_env old_hpt done
1084 (AcyclicSCC mod:mods) mod_index nmods
1085 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1086 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1087 -- (moduleEnvElts (hsc_HPT hsc_env)))
1089 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1092 cleanup -- Remove unwanted tmp files between compilations
1095 Nothing -> return (Failed, hsc_env, [])
1097 let this_mod = ms_mod_name mod
1099 -- Add new info to hsc_env
1100 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1101 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1103 -- Space-saving: delete the old HPT entry
1104 -- for mod BUT if mod is a hs-boot
1105 -- node, don't delete it. For the
1106 -- interface, the HPT entry is probaby for the
1107 -- main Haskell source file. Deleting it
1108 -- would force the real module to be recompiled
1110 old_hpt1 | isBootSummary mod = old_hpt
1111 | otherwise = delFromUFM old_hpt this_mod
1115 -- fixup our HomePackageTable after we've finished compiling
1116 -- a mutually-recursive loop. See reTypecheckLoop, below.
1117 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1119 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1122 -- Compile a single module. Always produce a Linkable for it if
1123 -- successful. If no compilation happened, return the old Linkable.
1124 upsweep_mod :: HscEnv
1126 -> ([ModuleName],[ModuleName])
1128 -> Int -- index of module
1129 -> Int -- total number of modules
1130 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1132 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1134 this_mod_name = ms_mod_name summary
1135 this_mod = ms_mod summary
1136 mb_obj_date = ms_obj_date summary
1137 obj_fn = ml_obj_file (ms_location summary)
1138 hs_date = ms_hs_date summary
1140 is_stable_obj = this_mod_name `elem` stable_obj
1141 is_stable_bco = this_mod_name `elem` stable_bco
1143 old_hmi = lookupUFM old_hpt this_mod_name
1145 -- We're using the dflags for this module now, obtained by
1146 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1147 dflags = ms_hspp_opts summary
1148 prevailing_target = hscTarget (hsc_dflags hsc_env)
1149 local_target = hscTarget dflags
1151 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1152 -- we don't do anything dodgy: these should only work to change
1153 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1154 -- end up trying to link object code to byte code.
1155 target = if prevailing_target /= local_target
1156 && (not (isObjectTarget prevailing_target)
1157 || not (isObjectTarget local_target))
1158 then prevailing_target
1161 -- store the corrected hscTarget into the summary
1162 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1164 -- The old interface is ok if
1165 -- a) we're compiling a source file, and the old HPT
1166 -- entry is for a source file
1167 -- b) we're compiling a hs-boot file
1168 -- Case (b) allows an hs-boot file to get the interface of its
1169 -- real source file on the second iteration of the compilation
1170 -- manager, but that does no harm. Otherwise the hs-boot file
1171 -- will always be recompiled
1176 Just hm_info | isBootSummary summary -> Just iface
1177 | not (mi_boot iface) -> Just iface
1178 | otherwise -> Nothing
1180 iface = hm_iface hm_info
1182 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1183 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1185 compile_it_discard_iface
1186 = compile hsc_env summary' mod_index nmods Nothing
1192 -- Regardless of whether we're generating object code or
1193 -- byte code, we can always use an existing object file
1194 -- if it is *stable* (see checkStability).
1195 | is_stable_obj, isJust old_hmi ->
1197 -- object is stable, and we have an entry in the
1198 -- old HPT: nothing to do
1200 | is_stable_obj, isNothing old_hmi -> do
1201 linkable <- findObjectLinkable this_mod obj_fn
1202 (expectJust "upseep1" mb_obj_date)
1203 compile_it (Just linkable)
1204 -- object is stable, but we need to load the interface
1205 -- off disk to make a HMI.
1209 ASSERT(isJust old_hmi) -- must be in the old_hpt
1211 -- BCO is stable: nothing to do
1213 | Just hmi <- old_hmi,
1214 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1215 linkableTime l >= ms_hs_date summary ->
1217 -- we have an old BCO that is up to date with respect
1218 -- to the source: do a recompilation check as normal.
1222 -- no existing code at all: we must recompile.
1224 -- When generating object code, if there's an up-to-date
1225 -- object file on the disk, then we can use it.
1226 -- However, if the object file is new (compared to any
1227 -- linkable we had from a previous compilation), then we
1228 -- must discard any in-memory interface, because this
1229 -- means the user has compiled the source file
1230 -- separately and generated a new interface, that we must
1231 -- read from the disk.
1233 obj | isObjectTarget obj,
1234 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1237 | Just l <- hm_linkable hmi,
1238 isObjectLinkable l && linkableTime l == obj_date
1239 -> compile_it (Just l)
1241 linkable <- findObjectLinkable this_mod obj_fn obj_date
1242 compile_it_discard_iface (Just linkable)
1249 -- Filter modules in the HPT
1250 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1251 retainInTopLevelEnvs keep_these hpt
1252 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1254 , let mb_mod_info = lookupUFM hpt mod
1255 , isJust mb_mod_info ]
1257 -- ---------------------------------------------------------------------------
1258 -- Typecheck module loops
1261 See bug #930. This code fixes a long-standing bug in --make. The
1262 problem is that when compiling the modules *inside* a loop, a data
1263 type that is only defined at the top of the loop looks opaque; but
1264 after the loop is done, the structure of the data type becomes
1267 The difficulty is then that two different bits of code have
1268 different notions of what the data type looks like.
1270 The idea is that after we compile a module which also has an .hs-boot
1271 file, we re-generate the ModDetails for each of the modules that
1272 depends on the .hs-boot file, so that everyone points to the proper
1273 TyCons, Ids etc. defined by the real module, not the boot module.
1274 Fortunately re-generating a ModDetails from a ModIface is easy: the
1275 function TcIface.typecheckIface does exactly that.
1277 Picking the modules to re-typecheck is slightly tricky. Starting from
1278 the module graph consisting of the modules that have already been
1279 compiled, we reverse the edges (so they point from the imported module
1280 to the importing module), and depth-first-search from the .hs-boot
1281 node. This gives us all the modules that depend transitively on the
1282 .hs-boot module, and those are exactly the modules that we need to
1285 Following this fix, GHC can compile itself with --make -O2.
1288 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1289 reTypecheckLoop hsc_env ms graph
1290 | not (isBootSummary ms) &&
1291 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1293 let mss = reachableBackwards (ms_mod_name ms) graph
1294 non_boot = filter (not.isBootSummary) mss
1295 debugTraceMsg (hsc_dflags hsc_env) 2 $
1296 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1297 typecheckLoop hsc_env (map ms_mod_name non_boot)
1301 this_mod = ms_mod ms
1303 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1304 typecheckLoop hsc_env mods = do
1306 fixIO $ \new_hpt -> do
1307 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1308 mds <- initIfaceCheck new_hsc_env $
1309 mapM (typecheckIface . hm_iface) hmis
1310 let new_hpt = addListToUFM old_hpt
1311 (zip mods [ hmi{ hm_details = details }
1312 | (hmi,details) <- zip hmis mds ])
1314 return hsc_env{ hsc_HPT = new_hpt }
1316 old_hpt = hsc_HPT hsc_env
1317 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1319 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1320 reachableBackwards mod summaries
1321 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1323 -- all the nodes reachable by traversing the edges backwards
1324 -- from the root node:
1325 nodes_we_want = reachable (transposeG graph) root
1327 -- the rest just sets up the graph:
1328 (nodes, lookup_key) = moduleGraphNodes False summaries
1329 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1331 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1332 | otherwise = panic "reachableBackwards"
1334 -- ---------------------------------------------------------------------------
1335 -- Topological sort of the module graph
1338 :: Bool -- Drop hi-boot nodes? (see below)
1342 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1343 -- The resulting list of strongly-connected-components is in topologically
1344 -- sorted order, starting with the module(s) at the bottom of the
1345 -- dependency graph (ie compile them first) and ending with the ones at
1348 -- Drop hi-boot nodes (first boolean arg)?
1350 -- False: treat the hi-boot summaries as nodes of the graph,
1351 -- so the graph must be acyclic
1353 -- True: eliminate the hi-boot nodes, and instead pretend
1354 -- the a source-import of Foo is an import of Foo
1355 -- The resulting graph has no hi-boot nodes, but can by cyclic
1357 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1358 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1359 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1360 = stronglyConnComp (map vertex_fn (reachable graph root))
1362 -- restrict the graph to just those modules reachable from
1363 -- the specified module. We do this by building a graph with
1364 -- the full set of nodes, and determining the reachable set from
1365 -- the specified node.
1366 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1367 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1369 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1370 | otherwise = throwDyn (ProgramError "module does not exist")
1372 moduleGraphNodes :: Bool -> [ModSummary]
1373 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1374 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1376 -- Drop hs-boot nodes by using HsSrcFile as the key
1377 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1378 | otherwise = HsBootFile
1380 -- We use integers as the keys for the SCC algorithm
1381 nodes :: [(ModSummary, Int, [Int])]
1382 nodes = [(s, expectJust "topSort" $
1383 lookup_key (ms_hsc_src s) (ms_mod_name s),
1384 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1385 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1386 (-- see [boot-edges] below
1387 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1389 else case lookup_key HsBootFile (ms_mod_name s) of
1394 , not (isBootSummary s && drop_hs_boot_nodes) ]
1395 -- Drop the hi-boot ones if told to do so
1397 -- [boot-edges] if this is a .hs and there is an equivalent
1398 -- .hs-boot, add a link from the former to the latter. This
1399 -- has the effect of detecting bogus cases where the .hs-boot
1400 -- depends on the .hs, by introducing a cycle. Additionally,
1401 -- it ensures that we will always process the .hs-boot before
1402 -- the .hs, and so the HomePackageTable will always have the
1403 -- most up to date information.
1405 key_map :: NodeMap Int
1406 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1410 lookup_key :: HscSource -> ModuleName -> Maybe Int
1411 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1413 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1414 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1415 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1416 -- the IsBootInterface parameter True; else False
1419 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1420 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1422 msKey :: ModSummary -> NodeKey
1423 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1425 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1426 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1428 nodeMapElts :: NodeMap a -> [a]
1429 nodeMapElts = eltsFM
1431 -- If there are {-# SOURCE #-} imports between strongly connected
1432 -- components in the topological sort, then those imports can
1433 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1434 -- were necessary, then the edge would be part of a cycle.
1435 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1436 warnUnnecessarySourceImports dflags sccs =
1437 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1439 let mods_in_this_cycle = map ms_mod_name ms in
1440 [ warn i | m <- ms, i <- ms_srcimps m,
1441 unLoc i `notElem` mods_in_this_cycle ]
1443 warn :: Located ModuleName -> WarnMsg
1446 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1447 <+> quotes (ppr mod))
1449 -----------------------------------------------------------------------------
1450 -- Downsweep (dependency analysis)
1452 -- Chase downwards from the specified root set, returning summaries
1453 -- for all home modules encountered. Only follow source-import
1456 -- We pass in the previous collection of summaries, which is used as a
1457 -- cache to avoid recalculating a module summary if the source is
1460 -- The returned list of [ModSummary] nodes has one node for each home-package
1461 -- module, plus one for any hs-boot files. The imports of these nodes
1462 -- are all there, including the imports of non-home-package modules.
1465 -> [ModSummary] -- Old summaries
1466 -> [ModuleName] -- Ignore dependencies on these; treat
1467 -- them as if they were package modules
1468 -> Bool -- True <=> allow multiple targets to have
1469 -- the same module name; this is
1470 -- very useful for ghc -M
1471 -> IO (Maybe [ModSummary])
1472 -- The elts of [ModSummary] all have distinct
1473 -- (Modules, IsBoot) identifiers, unless the Bool is true
1474 -- in which case there can be repeats
1475 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1476 = -- catch error messages and return them
1477 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1478 rootSummaries <- mapM getRootSummary roots
1479 let root_map = mkRootMap rootSummaries
1480 checkDuplicates root_map
1481 summs <- loop (concatMap msDeps rootSummaries) root_map
1484 roots = hsc_targets hsc_env
1486 old_summary_map :: NodeMap ModSummary
1487 old_summary_map = mkNodeMap old_summaries
1489 getRootSummary :: Target -> IO ModSummary
1490 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1491 = do exists <- doesFileExist file
1493 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1494 else throwDyn $ mkPlainErrMsg noSrcSpan $
1495 text "can't find file:" <+> text file
1496 getRootSummary (Target (TargetModule modl) maybe_buf)
1497 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1498 (L rootLoc modl) maybe_buf excl_mods
1499 case maybe_summary of
1500 Nothing -> packageModErr modl
1503 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1505 -- In a root module, the filename is allowed to diverge from the module
1506 -- name, so we have to check that there aren't multiple root files
1507 -- defining the same module (otherwise the duplicates will be silently
1508 -- ignored, leading to confusing behaviour).
1509 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1510 checkDuplicates root_map
1511 | allow_dup_roots = return ()
1512 | null dup_roots = return ()
1513 | otherwise = multiRootsErr (head dup_roots)
1515 dup_roots :: [[ModSummary]] -- Each at least of length 2
1516 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1518 loop :: [(Located ModuleName,IsBootInterface)]
1519 -- Work list: process these modules
1520 -> NodeMap [ModSummary]
1521 -- Visited set; the range is a list because
1522 -- the roots can have the same module names
1523 -- if allow_dup_roots is True
1525 -- The result includes the worklist, except
1526 -- for those mentioned in the visited set
1527 loop [] done = return (concat (nodeMapElts done))
1528 loop ((wanted_mod, is_boot) : ss) done
1529 | Just summs <- lookupFM done key
1530 = if isSingleton summs then
1533 do { multiRootsErr summs; return [] }
1534 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1535 is_boot wanted_mod Nothing excl_mods
1537 Nothing -> loop ss done
1538 Just s -> loop (msDeps s ++ ss)
1539 (addToFM done key [s]) }
1541 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1543 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1544 mkRootMap summaries = addListToFM_C (++) emptyFM
1545 [ (msKey s, [s]) | s <- summaries ]
1547 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1548 -- (msDeps s) returns the dependencies of the ModSummary s.
1549 -- A wrinkle is that for a {-# SOURCE #-} import we return
1550 -- *both* the hs-boot file
1551 -- *and* the source file
1552 -- as "dependencies". That ensures that the list of all relevant
1553 -- modules always contains B.hs if it contains B.hs-boot.
1554 -- Remember, this pass isn't doing the topological sort. It's
1555 -- just gathering the list of all relevant ModSummaries
1557 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1558 ++ [ (m,False) | m <- ms_imps s ]
1560 -----------------------------------------------------------------------------
1561 -- Summarising modules
1563 -- We have two types of summarisation:
1565 -- * Summarise a file. This is used for the root module(s) passed to
1566 -- cmLoadModules. The file is read, and used to determine the root
1567 -- module name. The module name may differ from the filename.
1569 -- * Summarise a module. We are given a module name, and must provide
1570 -- a summary. The finder is used to locate the file in which the module
1575 -> [ModSummary] -- old summaries
1576 -> FilePath -- source file name
1577 -> Maybe Phase -- start phase
1578 -> Maybe (StringBuffer,ClockTime)
1581 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1582 -- we can use a cached summary if one is available and the
1583 -- source file hasn't changed, But we have to look up the summary
1584 -- by source file, rather than module name as we do in summarise.
1585 | Just old_summary <- findSummaryBySourceFile old_summaries file
1587 let location = ms_location old_summary
1589 -- return the cached summary if the source didn't change
1590 src_timestamp <- case maybe_buf of
1591 Just (_,t) -> return t
1592 Nothing -> getModificationTime file
1593 -- The file exists; we checked in getRootSummary above.
1594 -- If it gets removed subsequently, then this
1595 -- getModificationTime may fail, but that's the right
1598 if ms_hs_date old_summary == src_timestamp
1599 then do -- update the object-file timestamp
1600 obj_timestamp <- getObjTimestamp location False
1601 return old_summary{ ms_obj_date = obj_timestamp }
1609 let dflags = hsc_dflags hsc_env
1611 (dflags', hspp_fn, buf)
1612 <- preprocessFile dflags file mb_phase maybe_buf
1614 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1616 -- Make a ModLocation for this file
1617 location <- mkHomeModLocation dflags mod_name file
1619 -- Tell the Finder cache where it is, so that subsequent calls
1620 -- to findModule will find it, even if it's not on any search path
1621 mod <- addHomeModuleToFinder hsc_env mod_name location
1623 src_timestamp <- case maybe_buf of
1624 Just (_,t) -> return t
1625 Nothing -> getModificationTime file
1626 -- getMofificationTime may fail
1628 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1630 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1631 ms_location = location,
1632 ms_hspp_file = hspp_fn,
1633 ms_hspp_opts = dflags',
1634 ms_hspp_buf = Just buf,
1635 ms_srcimps = srcimps, ms_imps = the_imps,
1636 ms_hs_date = src_timestamp,
1637 ms_obj_date = obj_timestamp })
1639 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1640 findSummaryBySourceFile summaries file
1641 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1642 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1646 -- Summarise a module, and pick up source and timestamp.
1649 -> NodeMap ModSummary -- Map of old summaries
1650 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1651 -> Located ModuleName -- Imported module to be summarised
1652 -> Maybe (StringBuffer, ClockTime)
1653 -> [ModuleName] -- Modules to exclude
1654 -> IO (Maybe ModSummary) -- Its new summary
1656 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1657 | wanted_mod `elem` excl_mods
1660 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1661 = do -- Find its new timestamp; all the
1662 -- ModSummaries in the old map have valid ml_hs_files
1663 let location = ms_location old_summary
1664 src_fn = expectJust "summariseModule" (ml_hs_file location)
1666 -- check the modification time on the source file, and
1667 -- return the cached summary if it hasn't changed. If the
1668 -- file has disappeared, we need to call the Finder again.
1670 Just (_,t) -> check_timestamp old_summary location src_fn t
1672 m <- System.IO.Error.try (getModificationTime src_fn)
1674 Right t -> check_timestamp old_summary location src_fn t
1675 Left e | isDoesNotExistError e -> find_it
1676 | otherwise -> ioError e
1678 | otherwise = find_it
1680 dflags = hsc_dflags hsc_env
1682 hsc_src = if is_boot then HsBootFile else HsSrcFile
1684 check_timestamp old_summary location src_fn src_timestamp
1685 | ms_hs_date old_summary == src_timestamp = do
1686 -- update the object-file timestamp
1687 obj_timestamp <- getObjTimestamp location is_boot
1688 return (Just old_summary{ ms_obj_date = obj_timestamp })
1690 -- source changed: re-summarise.
1691 new_summary location (ms_mod old_summary) src_fn src_timestamp
1694 -- Don't use the Finder's cache this time. If the module was
1695 -- previously a package module, it may have now appeared on the
1696 -- search path, so we want to consider it to be a home module. If
1697 -- the module was previously a home module, it may have moved.
1698 uncacheModule hsc_env wanted_mod
1699 found <- findImportedModule hsc_env wanted_mod Nothing
1702 | isJust (ml_hs_file location) ->
1704 just_found location mod
1706 -- Drop external-pkg
1707 ASSERT(modulePackageId mod /= thisPackage dflags)
1711 err -> noModError dflags loc wanted_mod err
1714 just_found location mod = do
1715 -- Adjust location to point to the hs-boot source file,
1716 -- hi file, object file, when is_boot says so
1717 let location' | is_boot = addBootSuffixLocn location
1718 | otherwise = location
1719 src_fn = expectJust "summarise2" (ml_hs_file location')
1721 -- Check that it exists
1722 -- It might have been deleted since the Finder last found it
1723 maybe_t <- modificationTimeIfExists src_fn
1725 Nothing -> noHsFileErr loc src_fn
1726 Just t -> new_summary location' mod src_fn t
1729 new_summary location mod src_fn src_timestamp
1731 -- Preprocess the source file and get its imports
1732 -- The dflags' contains the OPTIONS pragmas
1733 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1734 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1736 when (mod_name /= wanted_mod) $
1737 throwDyn $ mkPlainErrMsg mod_loc $
1738 text "file name does not match module name"
1739 <+> quotes (ppr mod_name)
1741 -- Find the object timestamp, and return the summary
1742 obj_timestamp <- getObjTimestamp location is_boot
1744 return (Just ( ModSummary { ms_mod = mod,
1745 ms_hsc_src = hsc_src,
1746 ms_location = location,
1747 ms_hspp_file = hspp_fn,
1748 ms_hspp_opts = dflags',
1749 ms_hspp_buf = Just buf,
1750 ms_srcimps = srcimps,
1752 ms_hs_date = src_timestamp,
1753 ms_obj_date = obj_timestamp }))
1756 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1757 getObjTimestamp location is_boot
1758 = if is_boot then return Nothing
1759 else modificationTimeIfExists (ml_obj_file location)
1762 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1763 -> IO (DynFlags, FilePath, StringBuffer)
1764 preprocessFile dflags src_fn mb_phase Nothing
1766 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1767 buf <- hGetStringBuffer hspp_fn
1768 return (dflags', hspp_fn, buf)
1770 preprocessFile dflags src_fn mb_phase (Just (buf, _time))
1772 -- case we bypass the preprocessing stage?
1774 local_opts = getOptions buf src_fn
1776 (dflags', _errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1777 -- XXX: shouldn't we be reporting the errors?
1781 | Just (Unlit _) <- mb_phase = True
1782 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1783 -- note: local_opts is only required if there's no Unlit phase
1784 | dopt Opt_Cpp dflags' = True
1785 | dopt Opt_Pp dflags' = True
1788 when needs_preprocessing $
1789 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1791 return (dflags', src_fn, buf)
1794 -----------------------------------------------------------------------------
1796 -----------------------------------------------------------------------------
1798 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1799 -- ToDo: we don't have a proper line number for this error
1800 noModError dflags loc wanted_mod err
1801 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1803 noHsFileErr :: SrcSpan -> String -> a
1804 noHsFileErr loc path
1805 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1807 packageModErr :: ModuleName -> a
1809 = throwDyn $ mkPlainErrMsg noSrcSpan $
1810 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1812 multiRootsErr :: [ModSummary] -> IO ()
1813 multiRootsErr [] = panic "multiRootsErr"
1814 multiRootsErr summs@(summ1:_)
1815 = throwDyn $ mkPlainErrMsg noSrcSpan $
1816 text "module" <+> quotes (ppr mod) <+>
1817 text "is defined in multiple files:" <+>
1818 sep (map text files)
1821 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1823 cyclicModuleErr :: [ModSummary] -> SDoc
1825 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1826 2 (vcat (map show_one ms))
1828 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1829 nest 2 $ ptext SLIT("imports:") <+>
1830 (pp_imps HsBootFile (ms_srcimps ms)
1831 $$ pp_imps HsSrcFile (ms_imps ms))]
1832 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1833 pp_imps src mods = fsep (map (show_mod src) mods)
1836 -- | Inform GHC that the working directory has changed. GHC will flush
1837 -- its cache of module locations, since it may no longer be valid.
1838 -- Note: if you change the working directory, you should also unload
1839 -- the current program (set targets to empty, followed by load).
1840 workingDirectoryChanged :: Session -> IO ()
1841 workingDirectoryChanged s = withSession s $ flushFinderCaches
1843 -- -----------------------------------------------------------------------------
1844 -- inspecting the session
1846 -- | Get the module dependency graph.
1847 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1848 getModuleGraph s = withSession s (return . hsc_mod_graph)
1850 isLoaded :: Session -> ModuleName -> IO Bool
1851 isLoaded s m = withSession s $ \hsc_env ->
1852 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1854 getBindings :: Session -> IO [TyThing]
1855 getBindings s = withSession s $ \hsc_env ->
1856 -- we have to implement the shadowing behaviour of ic_tmp_ids here
1857 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
1859 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
1860 filtered = foldr f (const []) tmp_ids emptyUniqSet
1862 | uniq `elementOfUniqSet` set = rest set
1863 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
1864 where uniq = getUnique (nameOccName (idName id))
1868 getPrintUnqual :: Session -> IO PrintUnqualified
1869 getPrintUnqual s = withSession s $ \hsc_env ->
1870 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
1872 -- | Container for information about a 'Module'.
1873 data ModuleInfo = ModuleInfo {
1874 minf_type_env :: TypeEnv,
1875 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1876 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1877 minf_instances :: [Instance]
1879 ,minf_modBreaks :: ModBreaks
1881 -- ToDo: this should really contain the ModIface too
1883 -- We don't want HomeModInfo here, because a ModuleInfo applies
1884 -- to package modules too.
1886 -- | Request information about a loaded 'Module'
1887 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1888 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1889 let mg = hsc_mod_graph hsc_env
1890 if mdl `elem` map ms_mod mg
1891 then getHomeModuleInfo hsc_env (moduleName mdl)
1893 {- if isHomeModule (hsc_dflags hsc_env) mdl
1895 else -} getPackageModuleInfo hsc_env mdl
1896 -- getPackageModuleInfo will attempt to find the interface, so
1897 -- we don't want to call it for a home module, just in case there
1898 -- was a problem loading the module and the interface doesn't
1899 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1901 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1903 getPackageModuleInfo hsc_env mdl = do
1904 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1906 Nothing -> return Nothing
1908 eps <- readIORef (hsc_EPS hsc_env)
1910 names = availsToNameSet avails
1912 tys = [ ty | name <- concatMap availNames avails,
1913 Just ty <- [lookupTypeEnv pte name] ]
1915 return (Just (ModuleInfo {
1916 minf_type_env = mkTypeEnv tys,
1917 minf_exports = names,
1918 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1919 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1920 minf_modBreaks = emptyModBreaks
1923 getPackageModuleInfo _hsc_env _mdl = do
1924 -- bogusly different for non-GHCI (ToDo)
1928 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
1929 getHomeModuleInfo hsc_env mdl =
1930 case lookupUFM (hsc_HPT hsc_env) mdl of
1931 Nothing -> return Nothing
1933 let details = hm_details hmi
1934 return (Just (ModuleInfo {
1935 minf_type_env = md_types details,
1936 minf_exports = availsToNameSet (md_exports details),
1937 minf_rdr_env = mi_globals $! hm_iface hmi,
1938 minf_instances = md_insts details
1940 ,minf_modBreaks = getModBreaks hmi
1944 -- | The list of top-level entities defined in a module
1945 modInfoTyThings :: ModuleInfo -> [TyThing]
1946 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1948 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1949 modInfoTopLevelScope minf
1950 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1952 modInfoExports :: ModuleInfo -> [Name]
1953 modInfoExports minf = nameSetToList $! minf_exports minf
1955 -- | Returns the instances defined by the specified module.
1956 -- Warning: currently unimplemented for package modules.
1957 modInfoInstances :: ModuleInfo -> [Instance]
1958 modInfoInstances = minf_instances
1960 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1961 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1963 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
1964 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
1965 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1967 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1968 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1969 case lookupTypeEnv (minf_type_env minf) name of
1970 Just tyThing -> return (Just tyThing)
1972 eps <- readIORef (hsc_EPS hsc_env)
1973 return $! lookupType (hsc_dflags hsc_env)
1974 (hsc_HPT hsc_env) (eps_PTE eps) name
1977 modInfoModBreaks :: ModuleInfo -> ModBreaks
1978 modInfoModBreaks = minf_modBreaks
1981 isDictonaryId :: Id -> Bool
1983 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1985 -- | Looks up a global name: that is, any top-level name in any
1986 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1987 -- the interactive context, and therefore does not require a preceding
1989 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1990 lookupGlobalName s name = withSession s $ \hsc_env -> do
1991 eps <- readIORef (hsc_EPS hsc_env)
1992 return $! lookupType (hsc_dflags hsc_env)
1993 (hsc_HPT hsc_env) (eps_PTE eps) name
1995 -- -----------------------------------------------------------------------------
1996 -- Misc exported utils
1998 dataConType :: DataCon -> Type
1999 dataConType dc = idType (dataConWrapId dc)
2001 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2002 pprParenSymName :: NamedThing a => a -> SDoc
2003 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2005 -- ----------------------------------------------------------------------------
2010 -- - Data and Typeable instances for HsSyn.
2012 -- ToDo: check for small transformations that happen to the syntax in
2013 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2015 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2016 -- to get from TyCons, Ids etc. to TH syntax (reify).
2018 -- :browse will use either lm_toplev or inspect lm_interface, depending
2019 -- on whether the module is interpreted or not.
2021 -- This is for reconstructing refactored source code
2022 -- Calls the lexer repeatedly.
2023 -- ToDo: add comment tokens to token stream
2024 getTokenStream :: Session -> Module -> IO [Located Token]
2027 -- -----------------------------------------------------------------------------
2028 -- Interactive evaluation
2030 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2031 -- filesystem and package database to find the corresponding 'Module',
2032 -- using the algorithm that is used for an @import@ declaration.
2033 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2034 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2036 dflags = hsc_dflags hsc_env
2037 hpt = hsc_HPT hsc_env
2038 this_pkg = thisPackage dflags
2040 case lookupUFM hpt mod_name of
2041 Just mod_info -> return (mi_module (hm_iface mod_info))
2042 _not_a_home_module -> do
2043 res <- findImportedModule hsc_env mod_name maybe_pkg
2045 Found _ m | modulePackageId m /= this_pkg -> return m
2046 | otherwise -> throwDyn (CmdLineError (showSDoc $
2047 text "module" <+> pprModule m <+>
2048 text "is not loaded"))
2049 err -> let msg = cannotFindModule dflags mod_name err in
2050 throwDyn (CmdLineError (showSDoc msg))
2053 getHistorySpan :: Session -> History -> IO SrcSpan
2054 getHistorySpan sess h = withSession sess $ \hsc_env ->
2055 return$ InteractiveEval.getHistorySpan hsc_env h
2057 obtainTerm :: Session -> Bool -> Id -> IO Term
2058 obtainTerm sess force id = withSession sess $ \hsc_env ->
2059 InteractiveEval.obtainTerm hsc_env force id
2061 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2062 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2063 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2065 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2066 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2067 InteractiveEval.obtainTermB hsc_env bound force id