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,
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 TcRnTypes hiding (LIE)
215 import TcRnMonad ( initIfaceCheck )
220 import Type hiding (typeKind)
221 import TcType hiding (typeKind)
223 import Var hiding (setIdType)
224 import TysPrim ( alphaTyVars )
229 import Name hiding ( varName )
230 import OccName ( parenSymOcc )
231 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
234 import DriverPipeline
235 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
236 import HeaderInfo ( getImports, getOptions )
238 import HscMain hiding (compileExpr)
242 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
251 import Bag ( unitBag, listToBag )
252 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
253 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
255 import qualified ErrUtils
257 import StringBuffer ( StringBuffer, hGetStringBuffer )
260 import Maybes ( expectJust, mapCatMaybes )
262 import HaddockLex ( tokenise )
264 import Control.Concurrent
265 import System.Directory ( getModificationTime, doesFileExist )
268 import qualified Data.List as List
270 import System.Exit ( exitWith, ExitCode(..) )
271 import System.Time ( ClockTime )
272 import Control.Exception as Exception hiding (handle)
275 import System.IO.Error ( try, isDoesNotExistError )
276 import Prelude hiding (init)
279 -- -----------------------------------------------------------------------------
280 -- Exception handlers
282 -- | Install some default exception handlers and run the inner computation.
283 -- Unless you want to handle exceptions yourself, you should wrap this around
284 -- the top level of your program. The default handlers output the error
285 -- message(s) to stderr and exit cleanly.
286 defaultErrorHandler :: DynFlags -> IO a -> IO a
287 defaultErrorHandler dflags inner =
288 -- top-level exception handler: any unrecognised exception is a compiler bug.
289 handle (\exception -> do
292 -- an IO exception probably isn't our fault, so don't panic
294 fatalErrorMsg dflags (text (show exception))
295 AsyncException StackOverflow ->
296 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
298 fatalErrorMsg dflags (text (show (Panic (show exception))))
299 exitWith (ExitFailure 1)
302 -- program errors: messages with locations attached. Sometimes it is
303 -- convenient to just throw these as exceptions.
304 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
305 exitWith (ExitFailure 1)) $
307 -- error messages propagated as exceptions
308 handleDyn (\dyn -> do
311 PhaseFailed _ code -> exitWith code
312 Interrupted -> exitWith (ExitFailure 1)
313 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
314 exitWith (ExitFailure 1)
318 -- | Install a default cleanup handler to remove temporary files
319 -- deposited by a GHC run. This is seperate from
320 -- 'defaultErrorHandler', because you might want to override the error
321 -- handling, but still get the ordinary cleanup behaviour.
322 defaultCleanupHandler :: DynFlags -> IO a -> IO a
323 defaultCleanupHandler dflags inner =
324 -- make sure we clean up after ourselves
325 later (do cleanTempFiles dflags
328 -- exceptions will be blocked while we clean the temporary files,
329 -- so there shouldn't be any difficulty if we receive further
334 -- | Starts a new session. A session consists of a set of loaded
335 -- modules, a set of options (DynFlags), and an interactive context.
336 -- ToDo: explain argument [[mb_top_dir]]
337 newSession :: Maybe FilePath -> IO Session
338 newSession mb_top_dir = do
340 main_thread <- myThreadId
341 modifyMVar_ interruptTargetThread (return . (main_thread :))
342 installSignalHandlers
345 dflags0 <- initSysTools mb_top_dir defaultDynFlags
346 dflags <- initDynFlags dflags0
347 env <- newHscEnv dflags
351 -- tmp: this breaks the abstraction, but required because DriverMkDepend
352 -- needs to call the Finder. ToDo: untangle this.
353 sessionHscEnv :: Session -> IO HscEnv
354 sessionHscEnv (Session ref) = readIORef ref
356 -- -----------------------------------------------------------------------------
359 -- | Grabs the DynFlags from the Session
360 getSessionDynFlags :: Session -> IO DynFlags
361 getSessionDynFlags s = withSession s (return . hsc_dflags)
363 -- | Updates the DynFlags in a Session. This also reads
364 -- the package database (unless it has already been read),
365 -- and prepares the compilers knowledge about packages. It
366 -- can be called again to load new packages: just add new
367 -- package flags to (packageFlags dflags).
369 -- Returns a list of new packages that may need to be linked in using
370 -- the dynamic linker (see 'linkPackages') as a result of new package
371 -- flags. If you are not doing linking or doing static linking, you
372 -- can ignore the list of packages returned.
374 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
375 setSessionDynFlags (Session ref) dflags = do
376 hsc_env <- readIORef ref
377 (dflags', preload) <- initPackages dflags
378 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
381 -- | If there is no -o option, guess the name of target executable
382 -- by using top-level source file name as a base.
383 guessOutputFile :: Session -> IO ()
384 guessOutputFile s = modifySession s $ \env ->
385 let dflags = hsc_dflags env
386 mod_graph = hsc_mod_graph env
387 mainModuleSrcPath, guessedName :: Maybe String
388 mainModuleSrcPath = do
389 let isMain = (== mainModIs dflags) . ms_mod
390 [ms] <- return (filter isMain mod_graph)
391 ml_hs_file (ms_location ms)
392 guessedName = fmap basenameOf mainModuleSrcPath
394 case outputFile dflags of
396 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
398 -- -----------------------------------------------------------------------------
401 -- ToDo: think about relative vs. absolute file paths. And what
402 -- happens when the current directory changes.
404 -- | Sets the targets for this session. Each target may be a module name
405 -- or a filename. The targets correspond to the set of root modules for
406 -- the program\/library. Unloading the current program is achieved by
407 -- setting the current set of targets to be empty, followed by load.
408 setTargets :: Session -> [Target] -> IO ()
409 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
411 -- | returns the current set of targets
412 getTargets :: Session -> IO [Target]
413 getTargets s = withSession s (return . hsc_targets)
415 -- | Add another target
416 addTarget :: Session -> Target -> IO ()
418 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
421 removeTarget :: Session -> TargetId -> IO ()
422 removeTarget s target_id
423 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
425 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
427 -- Attempts to guess what Target a string refers to. This function implements
428 -- the --make/GHCi command-line syntax for filenames:
430 -- - if the string looks like a Haskell source filename, then interpret
432 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
434 -- - otherwise interpret the string as a module name
436 guessTarget :: String -> Maybe Phase -> IO Target
437 guessTarget file (Just phase)
438 = return (Target (TargetFile file (Just phase)) Nothing)
439 guessTarget file Nothing
440 | isHaskellSrcFilename file
441 = return (Target (TargetFile file Nothing) Nothing)
443 = do exists <- doesFileExist hs_file
445 then return (Target (TargetFile hs_file Nothing) Nothing)
447 exists <- doesFileExist lhs_file
449 then return (Target (TargetFile lhs_file Nothing) Nothing)
451 return (Target (TargetModule (mkModuleName file)) Nothing)
453 hs_file = file `joinFileExt` "hs"
454 lhs_file = file `joinFileExt` "lhs"
456 -- -----------------------------------------------------------------------------
457 -- Extending the program scope
459 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
460 extendGlobalRdrScope session rdrElts
461 = modifySession session $ \hscEnv ->
462 let global_rdr = hsc_global_rdr_env hscEnv
463 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
465 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
466 setGlobalRdrScope session rdrElts
467 = modifySession session $ \hscEnv ->
468 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
470 extendGlobalTypeScope :: Session -> [Id] -> IO ()
471 extendGlobalTypeScope session ids
472 = modifySession session $ \hscEnv ->
473 let global_type = hsc_global_type_env hscEnv
474 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
476 setGlobalTypeScope :: Session -> [Id] -> IO ()
477 setGlobalTypeScope session ids
478 = modifySession session $ \hscEnv ->
479 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
481 -- -----------------------------------------------------------------------------
482 -- Parsing Haddock comments
484 parseHaddockComment :: String -> Either String (HsDoc RdrName)
485 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
487 -- -----------------------------------------------------------------------------
488 -- Loading the program
490 -- Perform a dependency analysis starting from the current targets
491 -- and update the session with the new module graph.
492 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
493 depanal (Session ref) excluded_mods allow_dup_roots = do
494 hsc_env <- readIORef ref
496 dflags = hsc_dflags hsc_env
497 targets = hsc_targets hsc_env
498 old_graph = hsc_mod_graph hsc_env
500 showPass dflags "Chasing dependencies"
501 debugTraceMsg dflags 2 (hcat [
502 text "Chasing modules from: ",
503 hcat (punctuate comma (map pprTarget targets))])
505 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
507 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
512 -- | The result of load.
514 = LoadOk Errors -- ^ all specified targets were loaded successfully.
515 | LoadFailed Errors -- ^ not all modules were loaded.
517 type Errors = [String]
519 data ErrMsg = ErrMsg {
520 errMsgSeverity :: Severity, -- warning, error, etc.
521 errMsgSpans :: [SrcSpan],
522 errMsgShortDoc :: Doc,
523 errMsgExtraInfo :: Doc
529 | LoadUpTo ModuleName
530 | LoadDependenciesOf ModuleName
532 -- | Try to load the program. If a Module is supplied, then just
533 -- attempt to load up to this target. If no Module is supplied,
534 -- then try to load all targets.
535 load :: Session -> LoadHowMuch -> IO SuccessFlag
536 load s@(Session ref) how_much
538 -- Dependency analysis first. Note that this fixes the module graph:
539 -- even if we don't get a fully successful upsweep, the full module
540 -- graph is still retained in the Session. We can tell which modules
541 -- were successfully loaded by inspecting the Session's HPT.
542 mb_graph <- depanal s [] False
544 Just mod_graph -> catchingFailure $ load2 s how_much mod_graph
545 Nothing -> return Failed
546 where catchingFailure f = f `Exception.catch` \e -> do
547 hsc_env <- readIORef ref
548 -- trac #1565 / test ghci021:
549 -- let bindings may explode if we try to use them after
551 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
554 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
555 load2 s@(Session ref) how_much mod_graph = do
557 hsc_env <- readIORef ref
559 let hpt1 = hsc_HPT hsc_env
560 let dflags = hsc_dflags hsc_env
562 -- The "bad" boot modules are the ones for which we have
563 -- B.hs-boot in the module graph, but no B.hs
564 -- The downsweep should have ensured this does not happen
566 let all_home_mods = [ms_mod_name s
567 | s <- mod_graph, not (isBootSummary s)]
568 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
569 not (ms_mod_name s `elem` all_home_mods)]
570 ASSERT( null bad_boot_mods ) return ()
572 -- mg2_with_srcimps drops the hi-boot nodes, returning a
573 -- graph with cycles. Among other things, it is used for
574 -- backing out partially complete cycles following a failed
575 -- upsweep, and for removing from hpt all the modules
576 -- not in strict downwards closure, during calls to compile.
577 let mg2_with_srcimps :: [SCC ModSummary]
578 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
580 -- If we can determine that any of the {-# SOURCE #-} imports
581 -- are definitely unnecessary, then emit a warning.
582 warnUnnecessarySourceImports dflags mg2_with_srcimps
585 -- check the stability property for each module.
586 stable_mods@(stable_obj,stable_bco)
587 = checkStability hpt1 mg2_with_srcimps all_home_mods
589 -- prune bits of the HPT which are definitely redundant now,
591 pruned_hpt = pruneHomePackageTable hpt1
592 (flattenSCCs mg2_with_srcimps)
597 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
598 text "Stable BCO:" <+> ppr stable_bco)
600 -- Unload any modules which are going to be re-linked this time around.
601 let stable_linkables = [ linkable
602 | m <- stable_obj++stable_bco,
603 Just hmi <- [lookupUFM pruned_hpt m],
604 Just linkable <- [hm_linkable hmi] ]
605 unload hsc_env stable_linkables
607 -- We could at this point detect cycles which aren't broken by
608 -- a source-import, and complain immediately, but it seems better
609 -- to let upsweep_mods do this, so at least some useful work gets
610 -- done before the upsweep is abandoned.
611 --hPutStrLn stderr "after tsort:\n"
612 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
614 -- Now do the upsweep, calling compile for each module in
615 -- turn. Final result is version 3 of everything.
617 -- Topologically sort the module graph, this time including hi-boot
618 -- nodes, and possibly just including the portion of the graph
619 -- reachable from the module specified in the 2nd argument to load.
620 -- This graph should be cycle-free.
621 -- If we're restricting the upsweep to a portion of the graph, we
622 -- also want to retain everything that is still stable.
623 let full_mg :: [SCC ModSummary]
624 full_mg = topSortModuleGraph False mod_graph Nothing
626 maybe_top_mod = case how_much of
628 LoadDependenciesOf m -> Just m
631 partial_mg0 :: [SCC ModSummary]
632 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
634 -- LoadDependenciesOf m: we want the upsweep to stop just
635 -- short of the specified module (unless the specified module
638 | LoadDependenciesOf _mod <- how_much
639 = ASSERT( case last partial_mg0 of
640 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
641 List.init partial_mg0
647 | AcyclicSCC ms <- full_mg,
648 ms_mod_name ms `elem` stable_obj++stable_bco,
649 ms_mod_name ms `notElem` [ ms_mod_name ms' |
650 AcyclicSCC ms' <- partial_mg ] ]
652 mg = stable_mg ++ partial_mg
654 -- clean up between compilations
655 let cleanup = cleanTempFilesExcept dflags
656 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
658 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
660 (upsweep_ok, hsc_env1, modsUpswept)
661 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
662 pruned_hpt stable_mods cleanup mg
664 -- Make modsDone be the summaries for each home module now
665 -- available; this should equal the domain of hpt3.
666 -- Get in in a roughly top .. bottom order (hence reverse).
668 let modsDone = reverse modsUpswept
670 -- Try and do linking in some form, depending on whether the
671 -- upsweep was completely or only partially successful.
673 if succeeded upsweep_ok
676 -- Easy; just relink it all.
677 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
679 -- Clean up after ourselves
680 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
682 -- Issue a warning for the confusing case where the user
683 -- said '-o foo' but we're not going to do any linking.
684 -- We attempt linking if either (a) one of the modules is
685 -- called Main, or (b) the user said -no-hs-main, indicating
686 -- that main() is going to come from somewhere else.
688 let ofile = outputFile dflags
689 let no_hs_main = dopt Opt_NoHsMain dflags
691 main_mod = mainModIs dflags
692 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
693 do_linking = a_root_is_Main || no_hs_main
695 when (ghcLink dflags == LinkBinary
696 && isJust ofile && not do_linking) $
697 debugTraceMsg dflags 1 $
698 text ("Warning: output was redirected with -o, " ++
699 "but no output will be generated\n" ++
700 "because there is no " ++
701 moduleNameString (moduleName main_mod) ++ " module.")
703 -- link everything together
704 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
706 loadFinish Succeeded linkresult ref hsc_env1
709 -- Tricky. We need to back out the effects of compiling any
710 -- half-done cycles, both so as to clean up the top level envs
711 -- and to avoid telling the interactive linker to link them.
712 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
715 = map ms_mod modsDone
716 let mods_to_zap_names
717 = findPartiallyCompletedCycles modsDone_names
720 = filter ((`notElem` mods_to_zap_names).ms_mod)
723 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
726 -- Clean up after ourselves
727 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
729 -- there should be no Nothings where linkables should be, now
730 ASSERT(all (isJust.hm_linkable)
731 (eltsUFM (hsc_HPT hsc_env))) do
733 -- Link everything together
734 linkresult <- link (ghcLink dflags) dflags False hpt4
736 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
737 loadFinish Failed linkresult ref hsc_env4
739 -- Finish up after a load.
741 -- If the link failed, unload everything and return.
742 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
743 loadFinish _all_ok Failed ref hsc_env
744 = do unload hsc_env []
745 writeIORef ref $! discardProg hsc_env
748 -- Empty the interactive context and set the module context to the topmost
749 -- newly loaded module, or the Prelude if none were loaded.
750 loadFinish all_ok Succeeded ref hsc_env
751 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
755 -- Forget the current program, but retain the persistent info in HscEnv
756 discardProg :: HscEnv -> HscEnv
758 = hsc_env { hsc_mod_graph = emptyMG,
759 hsc_IC = emptyInteractiveContext,
760 hsc_HPT = emptyHomePackageTable }
762 -- used to fish out the preprocess output files for the purposes of
763 -- cleaning up. The preprocessed file *might* be the same as the
764 -- source file, but that doesn't do any harm.
765 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
766 ppFilesFromSummaries summaries = map ms_hspp_file summaries
768 -- -----------------------------------------------------------------------------
772 CheckedModule { parsedSource :: ParsedSource,
773 renamedSource :: Maybe RenamedSource,
774 typecheckedSource :: Maybe TypecheckedSource,
775 checkedModuleInfo :: Maybe ModuleInfo,
776 coreModule :: Maybe CoreModule
778 -- ToDo: improvements that could be made here:
779 -- if the module succeeded renaming but not typechecking,
780 -- we can still get back the GlobalRdrEnv and exports, so
781 -- perhaps the ModuleInfo should be split up into separate
782 -- fields within CheckedModule.
784 type ParsedSource = Located (HsModule RdrName)
785 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
786 Maybe (HsDoc Name), HaddockModInfo Name)
787 type TypecheckedSource = LHsBinds Id
790 -- - things that aren't in the output of the typechecker right now:
794 -- - type/data/newtype declarations
795 -- - class declarations
797 -- - extra things in the typechecker's output:
798 -- - default methods are turned into top-level decls.
799 -- - dictionary bindings
802 -- | This is the way to get access to parsed and typechecked source code
803 -- for a module. 'checkModule' attempts to typecheck the module. If
804 -- successful, it returns the abstract syntax for the module.
805 -- If compileToCore is true, it also desugars the module and returns the
806 -- resulting Core bindings as a component of the CheckedModule.
807 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
808 checkModule (Session ref) mod compile_to_core
810 hsc_env <- readIORef ref
811 let mg = hsc_mod_graph hsc_env
812 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
814 (ms:_) -> checkModule_ ref ms compile_to_core False
816 -- | parses and typechecks a module, optionally generates Core, and also
817 -- loads the module into the 'Session' so that modules which depend on
818 -- this one may subsequently be typechecked using 'checkModule' or
819 -- 'checkAndLoadModule'. If you need to check more than one module,
820 -- you probably want to use 'checkAndLoadModule'. Constructing the
821 -- interface takes a little work, so it might be slightly slower than
823 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
824 checkAndLoadModule (Session ref) ms compile_to_core
825 = checkModule_ ref ms compile_to_core True
827 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
828 -> IO (Maybe CheckedModule)
829 checkModule_ ref ms compile_to_core load
831 let mod = ms_mod_name ms
832 hsc_env0 <- readIORef ref
833 let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
834 mb_parsed <- parseFile hsc_env ms
836 Nothing -> return Nothing
837 Just rdr_module -> do
838 mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
839 case mb_typechecked of
840 Nothing -> return (Just CheckedModule {
841 parsedSource = rdr_module,
842 renamedSource = Nothing,
843 typecheckedSource = Nothing,
844 checkedModuleInfo = Nothing,
845 coreModule = Nothing })
846 Just (tcg, rn_info) -> do
847 details <- makeSimpleDetails hsc_env tcg
849 let tc_binds = tcg_binds tcg
850 let rdr_env = tcg_rdr_env tcg
851 let minf = ModuleInfo {
852 minf_type_env = md_types details,
853 minf_exports = availsToNameSet $
855 minf_rdr_env = Just rdr_env,
856 minf_instances = md_insts details
858 ,minf_modBreaks = emptyModBreaks
862 mb_guts <- if compile_to_core
863 then deSugarModule hsc_env ms tcg
866 let mb_core = fmap (\ mg ->
867 CoreModule { cm_module = mg_module mg,
868 cm_types = mg_types mg,
869 cm_binds = mg_binds mg })
872 -- If we are loading this module so that we can typecheck
873 -- dependent modules, generate an interface and stuff it
874 -- all in the HomePackageTable.
876 (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
877 let mod_info = HomeModInfo {
879 hm_details = details,
880 hm_linkable = Nothing }
881 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
882 writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
884 return (Just (CheckedModule {
885 parsedSource = rdr_module,
886 renamedSource = rn_info,
887 typecheckedSource = Just tc_binds,
888 checkedModuleInfo = Just minf,
889 coreModule = mb_core }))
891 -- | This is the way to get access to the Core bindings corresponding
892 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
893 -- desugar the module, then returns the resulting Core module (consisting of
894 -- the module name, type declarations, and function declarations) if
896 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
897 compileToCoreModule session fn = do
898 -- First, set the target to the desired filename
899 target <- guessTarget fn Nothing
900 addTarget session target
901 load session LoadAllTargets
902 -- Then find dependencies
903 maybeModGraph <- depanal session [] True
904 case maybeModGraph of
905 Nothing -> return Nothing
907 case find ((== fn) . msHsFilePath) modGraph of
908 Just modSummary -> do
909 -- Now we have the module name;
910 -- parse, typecheck and desugar the module
911 let mod = ms_mod_name modSummary
912 maybeCheckedModule <- checkModule session mod True
913 case maybeCheckedModule of
914 Nothing -> return Nothing
915 Just checkedMod -> return $ coreModule checkedMod
916 Nothing -> panic "compileToCoreModule: target FilePath not found in\
917 module dependency graph"
919 -- | Provided for backwards-compatibility: compileToCore returns just the Core
920 -- bindings, but for most purposes, you probably want to call
921 -- compileToCoreModule.
922 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
923 compileToCore session fn = do
924 maybeCoreModule <- compileToCoreModule session fn
925 return $ fmap cm_binds maybeCoreModule
926 -- ---------------------------------------------------------------------------
929 unload :: HscEnv -> [Linkable] -> IO ()
930 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
931 = case ghcLink (hsc_dflags hsc_env) of
933 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
935 LinkInMemory -> panic "unload: no interpreter"
936 -- urgh. avoid warnings:
937 hsc_env stable_linkables
941 -- -----------------------------------------------------------------------------
945 Stability tells us which modules definitely do not need to be recompiled.
946 There are two main reasons for having stability:
948 - avoid doing a complete upsweep of the module graph in GHCi when
949 modules near the bottom of the tree have not changed.
951 - to tell GHCi when it can load object code: we can only load object code
952 for a module when we also load object code fo all of the imports of the
953 module. So we need to know that we will definitely not be recompiling
954 any of these modules, and we can use the object code.
956 The stability check is as follows. Both stableObject and
957 stableBCO are used during the upsweep phase later.
960 stable m = stableObject m || stableBCO m
963 all stableObject (imports m)
964 && old linkable does not exist, or is == on-disk .o
965 && date(on-disk .o) > date(.hs)
968 all stable (imports m)
969 && date(BCO) > date(.hs)
972 These properties embody the following ideas:
974 - if a module is stable, then:
975 - if it has been compiled in a previous pass (present in HPT)
976 then it does not need to be compiled or re-linked.
977 - if it has not been compiled in a previous pass,
978 then we only need to read its .hi file from disk and
979 link it to produce a ModDetails.
981 - if a modules is not stable, we will definitely be at least
982 re-linking, and possibly re-compiling it during the upsweep.
983 All non-stable modules can (and should) therefore be unlinked
986 - Note that objects are only considered stable if they only depend
987 on other objects. We can't link object code against byte code.
991 :: HomePackageTable -- HPT from last compilation
992 -> [SCC ModSummary] -- current module graph (cyclic)
993 -> [ModuleName] -- all home modules
994 -> ([ModuleName], -- stableObject
995 [ModuleName]) -- stableBCO
997 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
999 checkSCC (stable_obj, stable_bco) scc0
1000 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1001 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1002 | otherwise = (stable_obj, stable_bco)
1004 scc = flattenSCC scc0
1005 scc_mods = map ms_mod_name scc
1006 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1008 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1009 -- all imports outside the current SCC, but in the home pkg
1011 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1012 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1016 && all object_ok scc
1019 and (zipWith (||) stable_obj_imps stable_bco_imps)
1023 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1027 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1028 Just hmi | Just l <- hm_linkable hmi
1029 -> isObjectLinkable l && t == linkableTime l
1031 -- why '>=' rather than '>' above? If the filesystem stores
1032 -- times to the nearset second, we may occasionally find that
1033 -- the object & source have the same modification time,
1034 -- especially if the source was automatically generated
1035 -- and compiled. Using >= is slightly unsafe, but it matches
1036 -- make's behaviour.
1039 = case lookupUFM hpt (ms_mod_name ms) of
1040 Just hmi | Just l <- hm_linkable hmi ->
1041 not (isObjectLinkable l) &&
1042 linkableTime l >= ms_hs_date ms
1045 ms_allimps :: ModSummary -> [ModuleName]
1046 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1048 -- -----------------------------------------------------------------------------
1049 -- Prune the HomePackageTable
1051 -- Before doing an upsweep, we can throw away:
1053 -- - For non-stable modules:
1054 -- - all ModDetails, all linked code
1055 -- - all unlinked code that is out of date with respect to
1058 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1059 -- space at the end of the upsweep, because the topmost ModDetails of the
1060 -- old HPT holds on to the entire type environment from the previous
1063 pruneHomePackageTable
1066 -> ([ModuleName],[ModuleName])
1069 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1072 | is_stable modl = hmi'
1073 | otherwise = hmi'{ hm_details = emptyModDetails }
1075 modl = moduleName (mi_module (hm_iface hmi))
1076 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1077 = hmi{ hm_linkable = Nothing }
1080 where ms = expectJust "prune" (lookupUFM ms_map modl)
1082 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1084 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1086 -- -----------------------------------------------------------------------------
1088 -- Return (names of) all those in modsDone who are part of a cycle
1089 -- as defined by theGraph.
1090 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1091 findPartiallyCompletedCycles modsDone theGraph
1095 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1096 chew ((CyclicSCC vs):rest)
1097 = let names_in_this_cycle = nub (map ms_mod vs)
1099 = nub ([done | done <- modsDone,
1100 done `elem` names_in_this_cycle])
1101 chewed_rest = chew rest
1103 if notNull mods_in_this_cycle
1104 && length mods_in_this_cycle < length names_in_this_cycle
1105 then mods_in_this_cycle ++ chewed_rest
1108 -- -----------------------------------------------------------------------------
1111 -- This is where we compile each module in the module graph, in a pass
1112 -- from the bottom to the top of the graph.
1114 -- There better had not be any cyclic groups here -- we check for them.
1117 :: HscEnv -- Includes initially-empty HPT
1118 -> HomePackageTable -- HPT from last time round (pruned)
1119 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1120 -> IO () -- How to clean up unwanted tmp files
1121 -> [SCC ModSummary] -- Mods to do (the worklist)
1123 HscEnv, -- With an updated HPT
1124 [ModSummary]) -- Mods which succeeded
1126 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1127 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1128 return (res, hsc_env, reverse done)
1131 upsweep' hsc_env _old_hpt done
1133 = return (Succeeded, hsc_env, done)
1135 upsweep' hsc_env _old_hpt done
1136 (CyclicSCC ms:_) _ _
1137 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1138 return (Failed, hsc_env, done)
1140 upsweep' hsc_env old_hpt done
1141 (AcyclicSCC mod:mods) mod_index nmods
1142 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1143 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1144 -- (moduleEnvElts (hsc_HPT hsc_env)))
1146 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1149 cleanup -- Remove unwanted tmp files between compilations
1152 Nothing -> return (Failed, hsc_env, [])
1154 let this_mod = ms_mod_name mod
1156 -- Add new info to hsc_env
1157 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1158 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1160 -- Space-saving: delete the old HPT entry
1161 -- for mod BUT if mod is a hs-boot
1162 -- node, don't delete it. For the
1163 -- interface, the HPT entry is probaby for the
1164 -- main Haskell source file. Deleting it
1165 -- would force the real module to be recompiled
1167 old_hpt1 | isBootSummary mod = old_hpt
1168 | otherwise = delFromUFM old_hpt this_mod
1172 -- fixup our HomePackageTable after we've finished compiling
1173 -- a mutually-recursive loop. See reTypecheckLoop, below.
1174 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1176 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1179 -- Compile a single module. Always produce a Linkable for it if
1180 -- successful. If no compilation happened, return the old Linkable.
1181 upsweep_mod :: HscEnv
1183 -> ([ModuleName],[ModuleName])
1185 -> Int -- index of module
1186 -> Int -- total number of modules
1187 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1189 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1191 this_mod_name = ms_mod_name summary
1192 this_mod = ms_mod summary
1193 mb_obj_date = ms_obj_date summary
1194 obj_fn = ml_obj_file (ms_location summary)
1195 hs_date = ms_hs_date summary
1197 is_stable_obj = this_mod_name `elem` stable_obj
1198 is_stable_bco = this_mod_name `elem` stable_bco
1200 old_hmi = lookupUFM old_hpt this_mod_name
1202 -- We're using the dflags for this module now, obtained by
1203 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1204 dflags = ms_hspp_opts summary
1205 prevailing_target = hscTarget (hsc_dflags hsc_env)
1206 local_target = hscTarget dflags
1208 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1209 -- we don't do anything dodgy: these should only work to change
1210 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1211 -- end up trying to link object code to byte code.
1212 target = if prevailing_target /= local_target
1213 && (not (isObjectTarget prevailing_target)
1214 || not (isObjectTarget local_target))
1215 then prevailing_target
1218 -- store the corrected hscTarget into the summary
1219 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1221 -- The old interface is ok if
1222 -- a) we're compiling a source file, and the old HPT
1223 -- entry is for a source file
1224 -- b) we're compiling a hs-boot file
1225 -- Case (b) allows an hs-boot file to get the interface of its
1226 -- real source file on the second iteration of the compilation
1227 -- manager, but that does no harm. Otherwise the hs-boot file
1228 -- will always be recompiled
1233 Just hm_info | isBootSummary summary -> Just iface
1234 | not (mi_boot iface) -> Just iface
1235 | otherwise -> Nothing
1237 iface = hm_iface hm_info
1239 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1240 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1242 compile_it_discard_iface
1243 = compile hsc_env summary' mod_index nmods Nothing
1249 -- Regardless of whether we're generating object code or
1250 -- byte code, we can always use an existing object file
1251 -- if it is *stable* (see checkStability).
1252 | is_stable_obj, isJust old_hmi ->
1254 -- object is stable, and we have an entry in the
1255 -- old HPT: nothing to do
1257 | is_stable_obj, isNothing old_hmi -> do
1258 linkable <- findObjectLinkable this_mod obj_fn
1259 (expectJust "upseep1" mb_obj_date)
1260 compile_it (Just linkable)
1261 -- object is stable, but we need to load the interface
1262 -- off disk to make a HMI.
1266 ASSERT(isJust old_hmi) -- must be in the old_hpt
1268 -- BCO is stable: nothing to do
1270 | Just hmi <- old_hmi,
1271 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1272 linkableTime l >= ms_hs_date summary ->
1274 -- we have an old BCO that is up to date with respect
1275 -- to the source: do a recompilation check as normal.
1279 -- no existing code at all: we must recompile.
1281 -- When generating object code, if there's an up-to-date
1282 -- object file on the disk, then we can use it.
1283 -- However, if the object file is new (compared to any
1284 -- linkable we had from a previous compilation), then we
1285 -- must discard any in-memory interface, because this
1286 -- means the user has compiled the source file
1287 -- separately and generated a new interface, that we must
1288 -- read from the disk.
1290 obj | isObjectTarget obj,
1291 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1294 | Just l <- hm_linkable hmi,
1295 isObjectLinkable l && linkableTime l == obj_date
1296 -> compile_it (Just l)
1298 linkable <- findObjectLinkable this_mod obj_fn obj_date
1299 compile_it_discard_iface (Just linkable)
1306 -- Filter modules in the HPT
1307 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1308 retainInTopLevelEnvs keep_these hpt
1309 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1311 , let mb_mod_info = lookupUFM hpt mod
1312 , isJust mb_mod_info ]
1314 -- ---------------------------------------------------------------------------
1315 -- Typecheck module loops
1318 See bug #930. This code fixes a long-standing bug in --make. The
1319 problem is that when compiling the modules *inside* a loop, a data
1320 type that is only defined at the top of the loop looks opaque; but
1321 after the loop is done, the structure of the data type becomes
1324 The difficulty is then that two different bits of code have
1325 different notions of what the data type looks like.
1327 The idea is that after we compile a module which also has an .hs-boot
1328 file, we re-generate the ModDetails for each of the modules that
1329 depends on the .hs-boot file, so that everyone points to the proper
1330 TyCons, Ids etc. defined by the real module, not the boot module.
1331 Fortunately re-generating a ModDetails from a ModIface is easy: the
1332 function TcIface.typecheckIface does exactly that.
1334 Picking the modules to re-typecheck is slightly tricky. Starting from
1335 the module graph consisting of the modules that have already been
1336 compiled, we reverse the edges (so they point from the imported module
1337 to the importing module), and depth-first-search from the .hs-boot
1338 node. This gives us all the modules that depend transitively on the
1339 .hs-boot module, and those are exactly the modules that we need to
1342 Following this fix, GHC can compile itself with --make -O2.
1345 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1346 reTypecheckLoop hsc_env ms graph
1347 | not (isBootSummary ms) &&
1348 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1350 let mss = reachableBackwards (ms_mod_name ms) graph
1351 non_boot = filter (not.isBootSummary) mss
1352 debugTraceMsg (hsc_dflags hsc_env) 2 $
1353 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1354 typecheckLoop hsc_env (map ms_mod_name non_boot)
1358 this_mod = ms_mod ms
1360 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1361 typecheckLoop hsc_env mods = do
1363 fixIO $ \new_hpt -> do
1364 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1365 mds <- initIfaceCheck new_hsc_env $
1366 mapM (typecheckIface . hm_iface) hmis
1367 let new_hpt = addListToUFM old_hpt
1368 (zip mods [ hmi{ hm_details = details }
1369 | (hmi,details) <- zip hmis mds ])
1371 return hsc_env{ hsc_HPT = new_hpt }
1373 old_hpt = hsc_HPT hsc_env
1374 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1376 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1377 reachableBackwards mod summaries
1378 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1380 -- all the nodes reachable by traversing the edges backwards
1381 -- from the root node:
1382 nodes_we_want = reachable (transposeG graph) root
1384 -- the rest just sets up the graph:
1385 (nodes, lookup_key) = moduleGraphNodes False summaries
1386 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1388 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1389 | otherwise = panic "reachableBackwards"
1391 -- ---------------------------------------------------------------------------
1392 -- Topological sort of the module graph
1395 :: Bool -- Drop hi-boot nodes? (see below)
1399 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1400 -- The resulting list of strongly-connected-components is in topologically
1401 -- sorted order, starting with the module(s) at the bottom of the
1402 -- dependency graph (ie compile them first) and ending with the ones at
1405 -- Drop hi-boot nodes (first boolean arg)?
1407 -- False: treat the hi-boot summaries as nodes of the graph,
1408 -- so the graph must be acyclic
1410 -- True: eliminate the hi-boot nodes, and instead pretend
1411 -- the a source-import of Foo is an import of Foo
1412 -- The resulting graph has no hi-boot nodes, but can by cyclic
1414 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1415 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1416 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1417 = stronglyConnComp (map vertex_fn (reachable graph root))
1419 -- restrict the graph to just those modules reachable from
1420 -- the specified module. We do this by building a graph with
1421 -- the full set of nodes, and determining the reachable set from
1422 -- the specified node.
1423 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1424 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1426 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1427 | otherwise = throwDyn (ProgramError "module does not exist")
1429 moduleGraphNodes :: Bool -> [ModSummary]
1430 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1431 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1433 -- Drop hs-boot nodes by using HsSrcFile as the key
1434 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1435 | otherwise = HsBootFile
1437 -- We use integers as the keys for the SCC algorithm
1438 nodes :: [(ModSummary, Int, [Int])]
1439 nodes = [(s, expectJust "topSort" $
1440 lookup_key (ms_hsc_src s) (ms_mod_name s),
1441 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1442 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1443 (-- see [boot-edges] below
1444 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1446 else case lookup_key HsBootFile (ms_mod_name s) of
1451 , not (isBootSummary s && drop_hs_boot_nodes) ]
1452 -- Drop the hi-boot ones if told to do so
1454 -- [boot-edges] if this is a .hs and there is an equivalent
1455 -- .hs-boot, add a link from the former to the latter. This
1456 -- has the effect of detecting bogus cases where the .hs-boot
1457 -- depends on the .hs, by introducing a cycle. Additionally,
1458 -- it ensures that we will always process the .hs-boot before
1459 -- the .hs, and so the HomePackageTable will always have the
1460 -- most up to date information.
1462 key_map :: NodeMap Int
1463 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1467 lookup_key :: HscSource -> ModuleName -> Maybe Int
1468 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1470 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1471 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1472 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1473 -- the IsBootInterface parameter True; else False
1476 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1477 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1479 msKey :: ModSummary -> NodeKey
1480 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1482 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1483 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1485 nodeMapElts :: NodeMap a -> [a]
1486 nodeMapElts = eltsFM
1488 -- If there are {-# SOURCE #-} imports between strongly connected
1489 -- components in the topological sort, then those imports can
1490 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1491 -- were necessary, then the edge would be part of a cycle.
1492 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1493 warnUnnecessarySourceImports dflags sccs =
1494 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1496 let mods_in_this_cycle = map ms_mod_name ms in
1497 [ warn i | m <- ms, i <- ms_srcimps m,
1498 unLoc i `notElem` mods_in_this_cycle ]
1500 warn :: Located ModuleName -> WarnMsg
1503 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1504 <+> quotes (ppr mod))
1506 -----------------------------------------------------------------------------
1507 -- Downsweep (dependency analysis)
1509 -- Chase downwards from the specified root set, returning summaries
1510 -- for all home modules encountered. Only follow source-import
1513 -- We pass in the previous collection of summaries, which is used as a
1514 -- cache to avoid recalculating a module summary if the source is
1517 -- The returned list of [ModSummary] nodes has one node for each home-package
1518 -- module, plus one for any hs-boot files. The imports of these nodes
1519 -- are all there, including the imports of non-home-package modules.
1522 -> [ModSummary] -- Old summaries
1523 -> [ModuleName] -- Ignore dependencies on these; treat
1524 -- them as if they were package modules
1525 -> Bool -- True <=> allow multiple targets to have
1526 -- the same module name; this is
1527 -- very useful for ghc -M
1528 -> IO (Maybe [ModSummary])
1529 -- The elts of [ModSummary] all have distinct
1530 -- (Modules, IsBoot) identifiers, unless the Bool is true
1531 -- in which case there can be repeats
1532 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1533 = -- catch error messages and return them
1534 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1535 rootSummaries <- mapM getRootSummary roots
1536 let root_map = mkRootMap rootSummaries
1537 checkDuplicates root_map
1538 summs <- loop (concatMap msDeps rootSummaries) root_map
1541 roots = hsc_targets hsc_env
1543 old_summary_map :: NodeMap ModSummary
1544 old_summary_map = mkNodeMap old_summaries
1546 getRootSummary :: Target -> IO ModSummary
1547 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1548 = do exists <- doesFileExist file
1550 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1551 else throwDyn $ mkPlainErrMsg noSrcSpan $
1552 text "can't find file:" <+> text file
1553 getRootSummary (Target (TargetModule modl) maybe_buf)
1554 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1555 (L rootLoc modl) maybe_buf excl_mods
1556 case maybe_summary of
1557 Nothing -> packageModErr modl
1560 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1562 -- In a root module, the filename is allowed to diverge from the module
1563 -- name, so we have to check that there aren't multiple root files
1564 -- defining the same module (otherwise the duplicates will be silently
1565 -- ignored, leading to confusing behaviour).
1566 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1567 checkDuplicates root_map
1568 | allow_dup_roots = return ()
1569 | null dup_roots = return ()
1570 | otherwise = multiRootsErr (head dup_roots)
1572 dup_roots :: [[ModSummary]] -- Each at least of length 2
1573 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1575 loop :: [(Located ModuleName,IsBootInterface)]
1576 -- Work list: process these modules
1577 -> NodeMap [ModSummary]
1578 -- Visited set; the range is a list because
1579 -- the roots can have the same module names
1580 -- if allow_dup_roots is True
1582 -- The result includes the worklist, except
1583 -- for those mentioned in the visited set
1584 loop [] done = return (concat (nodeMapElts done))
1585 loop ((wanted_mod, is_boot) : ss) done
1586 | Just summs <- lookupFM done key
1587 = if isSingleton summs then
1590 do { multiRootsErr summs; return [] }
1591 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1592 is_boot wanted_mod Nothing excl_mods
1594 Nothing -> loop ss done
1595 Just s -> loop (msDeps s ++ ss)
1596 (addToFM done key [s]) }
1598 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1600 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1601 mkRootMap summaries = addListToFM_C (++) emptyFM
1602 [ (msKey s, [s]) | s <- summaries ]
1604 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1605 -- (msDeps s) returns the dependencies of the ModSummary s.
1606 -- A wrinkle is that for a {-# SOURCE #-} import we return
1607 -- *both* the hs-boot file
1608 -- *and* the source file
1609 -- as "dependencies". That ensures that the list of all relevant
1610 -- modules always contains B.hs if it contains B.hs-boot.
1611 -- Remember, this pass isn't doing the topological sort. It's
1612 -- just gathering the list of all relevant ModSummaries
1614 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1615 ++ [ (m,False) | m <- ms_imps s ]
1617 -----------------------------------------------------------------------------
1618 -- Summarising modules
1620 -- We have two types of summarisation:
1622 -- * Summarise a file. This is used for the root module(s) passed to
1623 -- cmLoadModules. The file is read, and used to determine the root
1624 -- module name. The module name may differ from the filename.
1626 -- * Summarise a module. We are given a module name, and must provide
1627 -- a summary. The finder is used to locate the file in which the module
1632 -> [ModSummary] -- old summaries
1633 -> FilePath -- source file name
1634 -> Maybe Phase -- start phase
1635 -> Maybe (StringBuffer,ClockTime)
1638 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1639 -- we can use a cached summary if one is available and the
1640 -- source file hasn't changed, But we have to look up the summary
1641 -- by source file, rather than module name as we do in summarise.
1642 | Just old_summary <- findSummaryBySourceFile old_summaries file
1644 let location = ms_location old_summary
1646 -- return the cached summary if the source didn't change
1647 src_timestamp <- case maybe_buf of
1648 Just (_,t) -> return t
1649 Nothing -> getModificationTime file
1650 -- The file exists; we checked in getRootSummary above.
1651 -- If it gets removed subsequently, then this
1652 -- getModificationTime may fail, but that's the right
1655 if ms_hs_date old_summary == src_timestamp
1656 then do -- update the object-file timestamp
1657 obj_timestamp <- getObjTimestamp location False
1658 return old_summary{ ms_obj_date = obj_timestamp }
1666 let dflags = hsc_dflags hsc_env
1668 (dflags', hspp_fn, buf)
1669 <- preprocessFile dflags file mb_phase maybe_buf
1671 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1673 -- Make a ModLocation for this file
1674 location <- mkHomeModLocation dflags mod_name file
1676 -- Tell the Finder cache where it is, so that subsequent calls
1677 -- to findModule will find it, even if it's not on any search path
1678 mod <- addHomeModuleToFinder hsc_env mod_name location
1680 src_timestamp <- case maybe_buf of
1681 Just (_,t) -> return t
1682 Nothing -> getModificationTime file
1683 -- getMofificationTime may fail
1685 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1687 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1688 ms_location = location,
1689 ms_hspp_file = hspp_fn,
1690 ms_hspp_opts = dflags',
1691 ms_hspp_buf = Just buf,
1692 ms_srcimps = srcimps, ms_imps = the_imps,
1693 ms_hs_date = src_timestamp,
1694 ms_obj_date = obj_timestamp })
1696 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1697 findSummaryBySourceFile summaries file
1698 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1699 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1703 -- Summarise a module, and pick up source and timestamp.
1706 -> NodeMap ModSummary -- Map of old summaries
1707 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1708 -> Located ModuleName -- Imported module to be summarised
1709 -> Maybe (StringBuffer, ClockTime)
1710 -> [ModuleName] -- Modules to exclude
1711 -> IO (Maybe ModSummary) -- Its new summary
1713 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1714 | wanted_mod `elem` excl_mods
1717 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1718 = do -- Find its new timestamp; all the
1719 -- ModSummaries in the old map have valid ml_hs_files
1720 let location = ms_location old_summary
1721 src_fn = expectJust "summariseModule" (ml_hs_file location)
1723 -- check the modification time on the source file, and
1724 -- return the cached summary if it hasn't changed. If the
1725 -- file has disappeared, we need to call the Finder again.
1727 Just (_,t) -> check_timestamp old_summary location src_fn t
1729 m <- System.IO.Error.try (getModificationTime src_fn)
1731 Right t -> check_timestamp old_summary location src_fn t
1732 Left e | isDoesNotExistError e -> find_it
1733 | otherwise -> ioError e
1735 | otherwise = find_it
1737 dflags = hsc_dflags hsc_env
1739 hsc_src = if is_boot then HsBootFile else HsSrcFile
1741 check_timestamp old_summary location src_fn src_timestamp
1742 | ms_hs_date old_summary == src_timestamp = do
1743 -- update the object-file timestamp
1744 obj_timestamp <- getObjTimestamp location is_boot
1745 return (Just old_summary{ ms_obj_date = obj_timestamp })
1747 -- source changed: re-summarise.
1748 new_summary location (ms_mod old_summary) src_fn src_timestamp
1751 -- Don't use the Finder's cache this time. If the module was
1752 -- previously a package module, it may have now appeared on the
1753 -- search path, so we want to consider it to be a home module. If
1754 -- the module was previously a home module, it may have moved.
1755 uncacheModule hsc_env wanted_mod
1756 found <- findImportedModule hsc_env wanted_mod Nothing
1759 | isJust (ml_hs_file location) ->
1761 just_found location mod
1763 -- Drop external-pkg
1764 ASSERT(modulePackageId mod /= thisPackage dflags)
1768 err -> noModError dflags loc wanted_mod err
1771 just_found location mod = do
1772 -- Adjust location to point to the hs-boot source file,
1773 -- hi file, object file, when is_boot says so
1774 let location' | is_boot = addBootSuffixLocn location
1775 | otherwise = location
1776 src_fn = expectJust "summarise2" (ml_hs_file location')
1778 -- Check that it exists
1779 -- It might have been deleted since the Finder last found it
1780 maybe_t <- modificationTimeIfExists src_fn
1782 Nothing -> noHsFileErr loc src_fn
1783 Just t -> new_summary location' mod src_fn t
1786 new_summary location mod src_fn src_timestamp
1788 -- Preprocess the source file and get its imports
1789 -- The dflags' contains the OPTIONS pragmas
1790 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1791 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1793 when (mod_name /= wanted_mod) $
1794 throwDyn $ mkPlainErrMsg mod_loc $
1795 text "file name does not match module name"
1796 <+> quotes (ppr mod_name)
1798 -- Find the object timestamp, and return the summary
1799 obj_timestamp <- getObjTimestamp location is_boot
1801 return (Just ( ModSummary { ms_mod = mod,
1802 ms_hsc_src = hsc_src,
1803 ms_location = location,
1804 ms_hspp_file = hspp_fn,
1805 ms_hspp_opts = dflags',
1806 ms_hspp_buf = Just buf,
1807 ms_srcimps = srcimps,
1809 ms_hs_date = src_timestamp,
1810 ms_obj_date = obj_timestamp }))
1813 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1814 getObjTimestamp location is_boot
1815 = if is_boot then return Nothing
1816 else modificationTimeIfExists (ml_obj_file location)
1819 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1820 -> IO (DynFlags, FilePath, StringBuffer)
1821 preprocessFile dflags src_fn mb_phase Nothing
1823 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1824 buf <- hGetStringBuffer hspp_fn
1825 return (dflags', hspp_fn, buf)
1827 preprocessFile dflags src_fn mb_phase (Just (buf, _time))
1829 -- case we bypass the preprocessing stage?
1831 local_opts = getOptions buf src_fn
1833 (dflags', _errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1834 -- XXX: shouldn't we be reporting the errors?
1838 | Just (Unlit _) <- mb_phase = True
1839 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1840 -- note: local_opts is only required if there's no Unlit phase
1841 | dopt Opt_Cpp dflags' = True
1842 | dopt Opt_Pp dflags' = True
1845 when needs_preprocessing $
1846 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1848 return (dflags', src_fn, buf)
1851 -----------------------------------------------------------------------------
1853 -----------------------------------------------------------------------------
1855 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1856 -- ToDo: we don't have a proper line number for this error
1857 noModError dflags loc wanted_mod err
1858 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1860 noHsFileErr :: SrcSpan -> String -> a
1861 noHsFileErr loc path
1862 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1864 packageModErr :: ModuleName -> a
1866 = throwDyn $ mkPlainErrMsg noSrcSpan $
1867 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1869 multiRootsErr :: [ModSummary] -> IO ()
1870 multiRootsErr [] = panic "multiRootsErr"
1871 multiRootsErr summs@(summ1:_)
1872 = throwDyn $ mkPlainErrMsg noSrcSpan $
1873 text "module" <+> quotes (ppr mod) <+>
1874 text "is defined in multiple files:" <+>
1875 sep (map text files)
1878 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1880 cyclicModuleErr :: [ModSummary] -> SDoc
1882 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1883 2 (vcat (map show_one ms))
1885 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1886 nest 2 $ ptext SLIT("imports:") <+>
1887 (pp_imps HsBootFile (ms_srcimps ms)
1888 $$ pp_imps HsSrcFile (ms_imps ms))]
1889 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1890 pp_imps src mods = fsep (map (show_mod src) mods)
1893 -- | Inform GHC that the working directory has changed. GHC will flush
1894 -- its cache of module locations, since it may no longer be valid.
1895 -- Note: if you change the working directory, you should also unload
1896 -- the current program (set targets to empty, followed by load).
1897 workingDirectoryChanged :: Session -> IO ()
1898 workingDirectoryChanged s = withSession s $ flushFinderCaches
1900 -- -----------------------------------------------------------------------------
1901 -- inspecting the session
1903 -- | Get the module dependency graph.
1904 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1905 getModuleGraph s = withSession s (return . hsc_mod_graph)
1907 isLoaded :: Session -> ModuleName -> IO Bool
1908 isLoaded s m = withSession s $ \hsc_env ->
1909 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1911 getBindings :: Session -> IO [TyThing]
1912 getBindings s = withSession s $ \hsc_env ->
1913 -- we have to implement the shadowing behaviour of ic_tmp_ids here
1914 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
1916 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
1917 filtered = foldr f (const []) tmp_ids emptyUniqSet
1919 | uniq `elementOfUniqSet` set = rest set
1920 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
1921 where uniq = getUnique (nameOccName (idName id))
1925 getPrintUnqual :: Session -> IO PrintUnqualified
1926 getPrintUnqual s = withSession s $ \hsc_env ->
1927 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
1929 -- | Container for information about a 'Module'.
1930 data ModuleInfo = ModuleInfo {
1931 minf_type_env :: TypeEnv,
1932 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1933 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1934 minf_instances :: [Instance]
1936 ,minf_modBreaks :: ModBreaks
1938 -- ToDo: this should really contain the ModIface too
1940 -- We don't want HomeModInfo here, because a ModuleInfo applies
1941 -- to package modules too.
1943 -- | Request information about a loaded 'Module'
1944 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1945 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1946 let mg = hsc_mod_graph hsc_env
1947 if mdl `elem` map ms_mod mg
1948 then getHomeModuleInfo hsc_env (moduleName mdl)
1950 {- if isHomeModule (hsc_dflags hsc_env) mdl
1952 else -} getPackageModuleInfo hsc_env mdl
1953 -- getPackageModuleInfo will attempt to find the interface, so
1954 -- we don't want to call it for a home module, just in case there
1955 -- was a problem loading the module and the interface doesn't
1956 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1958 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1960 getPackageModuleInfo hsc_env mdl = do
1961 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1963 Nothing -> return Nothing
1965 eps <- readIORef (hsc_EPS hsc_env)
1967 names = availsToNameSet avails
1969 tys = [ ty | name <- concatMap availNames avails,
1970 Just ty <- [lookupTypeEnv pte name] ]
1972 return (Just (ModuleInfo {
1973 minf_type_env = mkTypeEnv tys,
1974 minf_exports = names,
1975 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1976 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1977 minf_modBreaks = emptyModBreaks
1980 getPackageModuleInfo _hsc_env _mdl = do
1981 -- bogusly different for non-GHCI (ToDo)
1985 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
1986 getHomeModuleInfo hsc_env mdl =
1987 case lookupUFM (hsc_HPT hsc_env) mdl of
1988 Nothing -> return Nothing
1990 let details = hm_details hmi
1991 return (Just (ModuleInfo {
1992 minf_type_env = md_types details,
1993 minf_exports = availsToNameSet (md_exports details),
1994 minf_rdr_env = mi_globals $! hm_iface hmi,
1995 minf_instances = md_insts details
1997 ,minf_modBreaks = getModBreaks hmi
2001 -- | The list of top-level entities defined in a module
2002 modInfoTyThings :: ModuleInfo -> [TyThing]
2003 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2005 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2006 modInfoTopLevelScope minf
2007 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2009 modInfoExports :: ModuleInfo -> [Name]
2010 modInfoExports minf = nameSetToList $! minf_exports minf
2012 -- | Returns the instances defined by the specified module.
2013 -- Warning: currently unimplemented for package modules.
2014 modInfoInstances :: ModuleInfo -> [Instance]
2015 modInfoInstances = minf_instances
2017 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2018 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2020 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2021 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2022 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2024 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2025 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2026 case lookupTypeEnv (minf_type_env minf) name of
2027 Just tyThing -> return (Just tyThing)
2029 eps <- readIORef (hsc_EPS hsc_env)
2030 return $! lookupType (hsc_dflags hsc_env)
2031 (hsc_HPT hsc_env) (eps_PTE eps) name
2034 modInfoModBreaks :: ModuleInfo -> ModBreaks
2035 modInfoModBreaks = minf_modBreaks
2038 isDictonaryId :: Id -> Bool
2040 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2042 -- | Looks up a global name: that is, any top-level name in any
2043 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2044 -- the interactive context, and therefore does not require a preceding
2046 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2047 lookupGlobalName s name = withSession s $ \hsc_env -> do
2048 eps <- readIORef (hsc_EPS hsc_env)
2049 return $! lookupType (hsc_dflags hsc_env)
2050 (hsc_HPT hsc_env) (eps_PTE eps) name
2052 -- -----------------------------------------------------------------------------
2053 -- Misc exported utils
2055 dataConType :: DataCon -> Type
2056 dataConType dc = idType (dataConWrapId dc)
2058 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2059 pprParenSymName :: NamedThing a => a -> SDoc
2060 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2062 -- ----------------------------------------------------------------------------
2067 -- - Data and Typeable instances for HsSyn.
2069 -- ToDo: check for small transformations that happen to the syntax in
2070 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2072 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2073 -- to get from TyCons, Ids etc. to TH syntax (reify).
2075 -- :browse will use either lm_toplev or inspect lm_interface, depending
2076 -- on whether the module is interpreted or not.
2078 -- This is for reconstructing refactored source code
2079 -- Calls the lexer repeatedly.
2080 -- ToDo: add comment tokens to token stream
2081 getTokenStream :: Session -> Module -> IO [Located Token]
2084 -- -----------------------------------------------------------------------------
2085 -- Interactive evaluation
2087 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2088 -- filesystem and package database to find the corresponding 'Module',
2089 -- using the algorithm that is used for an @import@ declaration.
2090 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2091 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2093 dflags = hsc_dflags hsc_env
2094 hpt = hsc_HPT hsc_env
2095 this_pkg = thisPackage dflags
2097 case lookupUFM hpt mod_name of
2098 Just mod_info -> return (mi_module (hm_iface mod_info))
2099 _not_a_home_module -> do
2100 res <- findImportedModule hsc_env mod_name maybe_pkg
2102 Found _ m | modulePackageId m /= this_pkg -> return m
2103 | otherwise -> throwDyn (CmdLineError (showSDoc $
2104 text "module" <+> pprModule m <+>
2105 text "is not loaded"))
2106 err -> let msg = cannotFindModule dflags mod_name err in
2107 throwDyn (CmdLineError (showSDoc msg))
2110 getHistorySpan :: Session -> History -> IO SrcSpan
2111 getHistorySpan sess h = withSession sess $ \hsc_env ->
2112 return$ InteractiveEval.getHistorySpan hsc_env h
2114 obtainTerm :: Session -> Bool -> Id -> IO Term
2115 obtainTerm sess force id = withSession sess $ \hsc_env ->
2116 InteractiveEval.obtainTerm hsc_env force id
2118 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2119 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2120 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2122 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2123 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2124 InteractiveEval.obtainTermB hsc_env bound force id