1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18 GhcMode(..), GhcLink(..), defaultObjectTarget,
25 Target(..), TargetId(..), Phase,
32 -- * Extending the program scope
33 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
34 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
35 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
36 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
38 -- * Loading\/compiling the program
40 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
41 workingDirectoryChanged,
42 checkModule, checkAndLoadModule, CheckedModule(..),
43 TypecheckedSource, ParsedSource, RenamedSource,
44 compileToCore, compileToCoreModule, compileToCoreSimplified,
47 -- * Parsing Haddock comments
50 -- * Inspecting the module structure of the program
51 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
56 -- * Inspecting modules
63 modInfoIsExportedName,
66 mkPrintUnqualifiedForModule,
69 PrintUnqualified, alwaysQualify,
71 -- * Interactive evaluation
72 getBindings, getPrintUnqual,
75 setContext, getContext,
85 runStmt, SingleStep(..),
87 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
88 resumeHistory, resumeHistoryIx),
89 History(historyBreakInfo, historyEnclosingDecl),
90 GHC.getHistorySpan, getHistoryModule,
94 InteractiveEval.forward,
97 InteractiveEval.compileExpr, HValue, dynCompileExpr,
99 GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
101 ModBreaks(..), BreakIndex,
102 BreakInfo(breakInfo_number, breakInfo_module),
103 BreakArray, setBreakOn, setBreakOff, getBreak,
106 -- * Abstract syntax elements
112 Module, mkModule, pprModule, moduleName, modulePackageId,
113 ModuleName, mkModuleName, moduleNameString,
117 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
119 RdrName(Qual,Unqual),
123 isImplicitId, isDeadBinder,
124 isExportedId, isLocalId, isGlobalId,
126 isPrimOpId, isFCallId, isClassOpId_maybe,
127 isDataConWorkId, idDataCon,
128 isBottomingId, isDictonaryId,
129 recordSelectorFieldLabel,
131 -- ** Type constructors
133 tyConTyVars, tyConDataCons, tyConArity,
134 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
136 synTyConDefn, synTyConType, synTyConResKind,
142 -- ** Data constructors
144 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
145 dataConIsInfix, isVanillaDataCon,
147 StrictnessMark(..), isMarkedStrict,
151 classMethods, classSCTheta, classTvsFds,
156 instanceDFunId, pprInstance, pprInstanceHdr,
158 -- ** Types and Kinds
159 Type, splitForAllTys, funResultTy,
160 pprParendType, pprTypeApp,
163 ThetaType, pprThetaArrow,
169 module HsSyn, -- ToDo: remove extraneous bits
173 defaultFixity, maxPrecedence,
177 -- ** Source locations
179 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
180 srcLocFile, srcLocLine, srcLocCol,
182 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
183 srcSpanStart, srcSpanEnd,
185 srcSpanStartLine, srcSpanEndLine,
186 srcSpanStartCol, srcSpanEndCol,
189 GhcException(..), showGhcException,
199 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
200 * what StaticFlags should we expose, if any?
203 #include "HsVersions.h"
206 import qualified Linker
207 import Linker ( HValue )
211 import InteractiveEval
216 import TcRnTypes hiding (LIE)
217 import TcRnMonad ( initIfaceCheck )
221 import qualified HsSyn -- hack as we want to reexport the whole module
222 import HsSyn hiding ((<.>))
223 import Type hiding (typeKind)
224 import TcType hiding (typeKind)
226 import Var hiding (setIdType)
227 import TysPrim ( alphaTyVars )
232 import Name hiding ( varName )
233 import OccName ( parenSymOcc )
234 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
236 import FamInstEnv ( emptyFamInstEnv )
240 import DriverPipeline
241 import DriverPhases ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
248 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
257 import Bag ( unitBag, listToBag )
260 import StringBuffer ( StringBuffer, hGetStringBuffer )
263 import Maybes ( expectJust, mapCatMaybes )
265 import HaddockLex ( tokenise )
268 import Control.Concurrent
269 import System.Directory ( getModificationTime, doesFileExist,
270 getCurrentDirectory )
273 import qualified Data.List as List
275 import System.Exit ( exitWith, ExitCode(..) )
276 import System.Time ( ClockTime, getClockTime )
277 import Control.Exception as Exception hiding (handle)
279 import System.FilePath
281 import System.IO.Error ( try, isDoesNotExistError )
282 import Prelude hiding (init)
285 -- -----------------------------------------------------------------------------
286 -- Exception handlers
288 -- | Install some default exception handlers and run the inner computation.
289 -- Unless you want to handle exceptions yourself, you should wrap this around
290 -- the top level of your program. The default handlers output the error
291 -- message(s) to stderr and exit cleanly.
292 defaultErrorHandler :: DynFlags -> IO a -> IO a
293 defaultErrorHandler dflags inner =
294 -- top-level exception handler: any unrecognised exception is a compiler bug.
295 handle (\exception -> do
298 -- an IO exception probably isn't our fault, so don't panic
300 fatalErrorMsg dflags (text (show exception))
301 AsyncException StackOverflow ->
302 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
304 fatalErrorMsg dflags (text (show (Panic (show exception))))
305 exitWith (ExitFailure 1)
308 -- program errors: messages with locations attached. Sometimes it is
309 -- convenient to just throw these as exceptions.
310 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
311 exitWith (ExitFailure 1)) $
313 -- error messages propagated as exceptions
314 handleDyn (\dyn -> do
317 PhaseFailed _ code -> exitWith code
318 Interrupted -> exitWith (ExitFailure 1)
319 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
320 exitWith (ExitFailure 1)
324 -- | Install a default cleanup handler to remove temporary files
325 -- deposited by a GHC run. This is seperate from
326 -- 'defaultErrorHandler', because you might want to override the error
327 -- handling, but still get the ordinary cleanup behaviour.
328 defaultCleanupHandler :: DynFlags -> IO a -> IO a
329 defaultCleanupHandler dflags inner =
330 -- make sure we clean up after ourselves
331 later (do cleanTempFiles dflags
334 -- exceptions will be blocked while we clean the temporary files,
335 -- so there shouldn't be any difficulty if we receive further
340 -- | Starts a new session. A session consists of a set of loaded
341 -- modules, a set of options (DynFlags), and an interactive context.
342 -- ToDo: explain argument [[mb_top_dir]]
343 newSession :: Maybe FilePath -> IO Session
344 newSession mb_top_dir = do
346 main_thread <- myThreadId
347 modifyMVar_ interruptTargetThread (return . (main_thread :))
348 installSignalHandlers
351 dflags0 <- initDynFlags defaultDynFlags
352 dflags <- initSysTools mb_top_dir dflags0
353 env <- newHscEnv dflags
357 -- tmp: this breaks the abstraction, but required because DriverMkDepend
358 -- needs to call the Finder. ToDo: untangle this.
359 sessionHscEnv :: Session -> IO HscEnv
360 sessionHscEnv (Session ref) = readIORef ref
362 -- -----------------------------------------------------------------------------
365 -- | Grabs the DynFlags from the Session
366 getSessionDynFlags :: Session -> IO DynFlags
367 getSessionDynFlags s = withSession s (return . hsc_dflags)
369 -- | Updates the DynFlags in a Session. This also reads
370 -- the package database (unless it has already been read),
371 -- and prepares the compilers knowledge about packages. It
372 -- can be called again to load new packages: just add new
373 -- package flags to (packageFlags dflags).
375 -- Returns a list of new packages that may need to be linked in using
376 -- the dynamic linker (see 'linkPackages') as a result of new package
377 -- flags. If you are not doing linking or doing static linking, you
378 -- can ignore the list of packages returned.
380 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
381 setSessionDynFlags (Session ref) dflags = do
382 hsc_env <- readIORef ref
383 (dflags', preload) <- initPackages dflags
384 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
387 -- | If there is no -o option, guess the name of target executable
388 -- by using top-level source file name as a base.
389 guessOutputFile :: Session -> IO ()
390 guessOutputFile s = modifySession s $ \env ->
391 let dflags = hsc_dflags env
392 mod_graph = hsc_mod_graph env
393 mainModuleSrcPath :: Maybe String
394 mainModuleSrcPath = do
395 let isMain = (== mainModIs dflags) . ms_mod
396 [ms] <- return (filter isMain mod_graph)
397 ml_hs_file (ms_location ms)
398 name = fmap dropExtension mainModuleSrcPath
400 #if defined(mingw32_HOST_OS)
401 -- we must add the .exe extention unconditionally here, otherwise
402 -- when name has an extension of its own, the .exe extension will
403 -- not be added by DriverPipeline.exeFileName. See #2248
404 name_exe = fmap (<.> "exe") name
409 case outputFile dflags of
411 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
413 -- -----------------------------------------------------------------------------
416 -- ToDo: think about relative vs. absolute file paths. And what
417 -- happens when the current directory changes.
419 -- | Sets the targets for this session. Each target may be a module name
420 -- or a filename. The targets correspond to the set of root modules for
421 -- the program\/library. Unloading the current program is achieved by
422 -- setting the current set of targets to be empty, followed by load.
423 setTargets :: Session -> [Target] -> IO ()
424 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
426 -- | returns the current set of targets
427 getTargets :: Session -> IO [Target]
428 getTargets s = withSession s (return . hsc_targets)
430 -- | Add another target
431 addTarget :: Session -> Target -> IO ()
433 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
436 removeTarget :: Session -> TargetId -> IO ()
437 removeTarget s target_id
438 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
440 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
442 -- Attempts to guess what Target a string refers to. This function implements
443 -- the --make/GHCi command-line syntax for filenames:
445 -- - if the string looks like a Haskell source filename, then interpret
447 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
449 -- - otherwise interpret the string as a module name
451 guessTarget :: String -> Maybe Phase -> IO Target
452 guessTarget file (Just phase)
453 = return (Target (TargetFile file (Just phase)) Nothing)
454 guessTarget file Nothing
455 | isHaskellSrcFilename file
456 = return (Target (TargetFile file Nothing) Nothing)
457 | looksLikeModuleName file
458 = return (Target (TargetModule (mkModuleName file)) Nothing)
460 = do exists <- doesFileExist hs_file
462 then return (Target (TargetFile hs_file Nothing) Nothing)
464 exists <- doesFileExist lhs_file
466 then return (Target (TargetFile lhs_file Nothing) Nothing)
468 throwDyn (ProgramError (showSDoc $
469 text "target" <+> quotes (text file) <+>
470 text "is not a module name or a source file"))
472 hs_file = file <.> "hs"
473 lhs_file = file <.> "lhs"
475 -- -----------------------------------------------------------------------------
476 -- Extending the program scope
478 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
479 extendGlobalRdrScope session rdrElts
480 = modifySession session $ \hscEnv ->
481 let global_rdr = hsc_global_rdr_env hscEnv
482 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
484 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
485 setGlobalRdrScope session rdrElts
486 = modifySession session $ \hscEnv ->
487 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
489 extendGlobalTypeScope :: Session -> [Id] -> IO ()
490 extendGlobalTypeScope session ids
491 = modifySession session $ \hscEnv ->
492 let global_type = hsc_global_type_env hscEnv
493 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
495 setGlobalTypeScope :: Session -> [Id] -> IO ()
496 setGlobalTypeScope session ids
497 = modifySession session $ \hscEnv ->
498 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
500 -- -----------------------------------------------------------------------------
501 -- Parsing Haddock comments
503 parseHaddockComment :: String -> Either String (HsDoc RdrName)
504 parseHaddockComment string =
505 case parseHaddockParagraphs (tokenise string) of
509 -- -----------------------------------------------------------------------------
510 -- Loading the program
512 -- Perform a dependency analysis starting from the current targets
513 -- and update the session with the new module graph.
514 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
515 depanal (Session ref) excluded_mods allow_dup_roots = do
516 hsc_env <- readIORef ref
518 dflags = hsc_dflags hsc_env
519 targets = hsc_targets hsc_env
520 old_graph = hsc_mod_graph hsc_env
522 showPass dflags "Chasing dependencies"
523 debugTraceMsg dflags 2 (hcat [
524 text "Chasing modules from: ",
525 hcat (punctuate comma (map pprTarget targets))])
527 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
529 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
534 -- | The result of load.
536 = LoadOk Errors -- ^ all specified targets were loaded successfully.
537 | LoadFailed Errors -- ^ not all modules were loaded.
539 type Errors = [String]
541 data ErrMsg = ErrMsg {
542 errMsgSeverity :: Severity, -- warning, error, etc.
543 errMsgSpans :: [SrcSpan],
544 errMsgShortDoc :: Doc,
545 errMsgExtraInfo :: Doc
551 | LoadUpTo ModuleName
552 | LoadDependenciesOf ModuleName
554 -- | Try to load the program. If a Module is supplied, then just
555 -- attempt to load up to this target. If no Module is supplied,
556 -- then try to load all targets.
557 load :: Session -> LoadHowMuch -> IO SuccessFlag
560 -- Dependency analysis first. Note that this fixes the module graph:
561 -- even if we don't get a fully successful upsweep, the full module
562 -- graph is still retained in the Session. We can tell which modules
563 -- were successfully loaded by inspecting the Session's HPT.
564 mb_graph <- depanal s [] False
566 Just mod_graph -> load2 s how_much mod_graph
567 Nothing -> return Failed
569 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
570 load2 s@(Session ref) how_much mod_graph = do
572 hsc_env <- readIORef ref
574 let hpt1 = hsc_HPT hsc_env
575 let dflags = hsc_dflags hsc_env
577 -- The "bad" boot modules are the ones for which we have
578 -- B.hs-boot in the module graph, but no B.hs
579 -- The downsweep should have ensured this does not happen
581 let all_home_mods = [ms_mod_name s
582 | s <- mod_graph, not (isBootSummary s)]
583 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
584 not (ms_mod_name s `elem` all_home_mods)]
585 ASSERT( null bad_boot_mods ) return ()
587 -- check that the module given in HowMuch actually exists, otherwise
588 -- topSortModuleGraph will bomb later.
589 let checkHowMuch (LoadUpTo m) = checkMod m
590 checkHowMuch (LoadDependenciesOf m) = checkMod m
594 | m `elem` all_home_mods = and_then
596 errorMsg dflags (text "no such module:" <+>
600 checkHowMuch how_much $ do
602 -- mg2_with_srcimps drops the hi-boot nodes, returning a
603 -- graph with cycles. Among other things, it is used for
604 -- backing out partially complete cycles following a failed
605 -- upsweep, and for removing from hpt all the modules
606 -- not in strict downwards closure, during calls to compile.
607 let mg2_with_srcimps :: [SCC ModSummary]
608 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
610 -- If we can determine that any of the {-# SOURCE #-} imports
611 -- are definitely unnecessary, then emit a warning.
612 warnUnnecessarySourceImports dflags mg2_with_srcimps
615 -- check the stability property for each module.
616 stable_mods@(stable_obj,stable_bco)
617 = checkStability hpt1 mg2_with_srcimps all_home_mods
619 -- prune bits of the HPT which are definitely redundant now,
621 pruned_hpt = pruneHomePackageTable hpt1
622 (flattenSCCs mg2_with_srcimps)
627 -- before we unload anything, make sure we don't leave an old
628 -- interactive context around pointing to dead bindings. Also,
629 -- write the pruned HPT to allow the old HPT to be GC'd.
630 writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext,
631 hsc_HPT = pruned_hpt }
633 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
634 text "Stable BCO:" <+> ppr stable_bco)
636 -- Unload any modules which are going to be re-linked this time around.
637 let stable_linkables = [ linkable
638 | m <- stable_obj++stable_bco,
639 Just hmi <- [lookupUFM pruned_hpt m],
640 Just linkable <- [hm_linkable hmi] ]
641 unload hsc_env stable_linkables
643 -- We could at this point detect cycles which aren't broken by
644 -- a source-import, and complain immediately, but it seems better
645 -- to let upsweep_mods do this, so at least some useful work gets
646 -- done before the upsweep is abandoned.
647 --hPutStrLn stderr "after tsort:\n"
648 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
650 -- Now do the upsweep, calling compile for each module in
651 -- turn. Final result is version 3 of everything.
653 -- Topologically sort the module graph, this time including hi-boot
654 -- nodes, and possibly just including the portion of the graph
655 -- reachable from the module specified in the 2nd argument to load.
656 -- This graph should be cycle-free.
657 -- If we're restricting the upsweep to a portion of the graph, we
658 -- also want to retain everything that is still stable.
659 let full_mg :: [SCC ModSummary]
660 full_mg = topSortModuleGraph False mod_graph Nothing
662 maybe_top_mod = case how_much of
664 LoadDependenciesOf m -> Just m
667 partial_mg0 :: [SCC ModSummary]
668 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
670 -- LoadDependenciesOf m: we want the upsweep to stop just
671 -- short of the specified module (unless the specified module
674 | LoadDependenciesOf _mod <- how_much
675 = ASSERT( case last partial_mg0 of
676 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
677 List.init partial_mg0
683 | AcyclicSCC ms <- full_mg,
684 ms_mod_name ms `elem` stable_obj++stable_bco,
685 ms_mod_name ms `notElem` [ ms_mod_name ms' |
686 AcyclicSCC ms' <- partial_mg ] ]
688 mg = stable_mg ++ partial_mg
690 -- clean up between compilations
691 let cleanup = cleanTempFilesExcept dflags
692 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
694 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
696 (upsweep_ok, hsc_env1, modsUpswept)
697 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
698 pruned_hpt stable_mods cleanup mg
700 -- Make modsDone be the summaries for each home module now
701 -- available; this should equal the domain of hpt3.
702 -- Get in in a roughly top .. bottom order (hence reverse).
704 let modsDone = reverse modsUpswept
706 -- Try and do linking in some form, depending on whether the
707 -- upsweep was completely or only partially successful.
709 if succeeded upsweep_ok
712 -- Easy; just relink it all.
713 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
715 -- Clean up after ourselves
716 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
718 -- Issue a warning for the confusing case where the user
719 -- said '-o foo' but we're not going to do any linking.
720 -- We attempt linking if either (a) one of the modules is
721 -- called Main, or (b) the user said -no-hs-main, indicating
722 -- that main() is going to come from somewhere else.
724 let ofile = outputFile dflags
725 let no_hs_main = dopt Opt_NoHsMain dflags
727 main_mod = mainModIs dflags
728 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
729 do_linking = a_root_is_Main || no_hs_main
731 when (ghcLink dflags == LinkBinary
732 && isJust ofile && not do_linking) $
733 debugTraceMsg dflags 1 $
734 text ("Warning: output was redirected with -o, " ++
735 "but no output will be generated\n" ++
736 "because there is no " ++
737 moduleNameString (moduleName main_mod) ++ " module.")
739 -- link everything together
740 linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
742 loadFinish Succeeded linkresult ref hsc_env1
745 -- Tricky. We need to back out the effects of compiling any
746 -- half-done cycles, both so as to clean up the top level envs
747 -- and to avoid telling the interactive linker to link them.
748 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
751 = map ms_mod modsDone
752 let mods_to_zap_names
753 = findPartiallyCompletedCycles modsDone_names
756 = filter ((`notElem` mods_to_zap_names).ms_mod)
759 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
762 -- Clean up after ourselves
763 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
765 -- there should be no Nothings where linkables should be, now
766 ASSERT(all (isJust.hm_linkable)
767 (eltsUFM (hsc_HPT hsc_env))) do
769 -- Link everything together
770 linkresult <- link (ghcLink dflags) dflags False hpt4
772 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
773 loadFinish Failed linkresult ref hsc_env4
775 -- Finish up after a load.
777 -- If the link failed, unload everything and return.
778 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
779 loadFinish _all_ok Failed ref hsc_env
780 = do unload hsc_env []
781 writeIORef ref $! discardProg hsc_env
784 -- Empty the interactive context and set the module context to the topmost
785 -- newly loaded module, or the Prelude if none were loaded.
786 loadFinish all_ok Succeeded ref hsc_env
787 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
791 -- Forget the current program, but retain the persistent info in HscEnv
792 discardProg :: HscEnv -> HscEnv
794 = hsc_env { hsc_mod_graph = emptyMG,
795 hsc_IC = emptyInteractiveContext,
796 hsc_HPT = emptyHomePackageTable }
798 -- used to fish out the preprocess output files for the purposes of
799 -- cleaning up. The preprocessed file *might* be the same as the
800 -- source file, but that doesn't do any harm.
801 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
802 ppFilesFromSummaries summaries = map ms_hspp_file summaries
804 -- -----------------------------------------------------------------------------
808 CheckedModule { parsedSource :: ParsedSource,
809 renamedSource :: Maybe RenamedSource,
810 typecheckedSource :: Maybe TypecheckedSource,
811 checkedModuleInfo :: Maybe ModuleInfo,
812 coreModule :: Maybe ModGuts
814 -- ToDo: improvements that could be made here:
815 -- if the module succeeded renaming but not typechecking,
816 -- we can still get back the GlobalRdrEnv and exports, so
817 -- perhaps the ModuleInfo should be split up into separate
818 -- fields within CheckedModule.
820 type ParsedSource = Located (HsModule RdrName)
821 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
822 Maybe (HsDoc Name), HaddockModInfo Name)
823 type TypecheckedSource = LHsBinds Id
826 -- - things that aren't in the output of the typechecker right now:
830 -- - type/data/newtype declarations
831 -- - class declarations
833 -- - extra things in the typechecker's output:
834 -- - default methods are turned into top-level decls.
835 -- - dictionary bindings
838 -- | This is the way to get access to parsed and typechecked source code
839 -- for a module. 'checkModule' attempts to typecheck the module. If
840 -- successful, it returns the abstract syntax for the module.
841 -- If compileToCore is true, it also desugars the module and returns the
842 -- resulting Core bindings as a component of the CheckedModule.
843 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
844 checkModule (Session ref) mod compile_to_core
846 hsc_env <- readIORef ref
847 let mg = hsc_mod_graph hsc_env
848 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
850 (ms:_) -> checkModule_ ref ms compile_to_core False
852 -- | parses and typechecks a module, optionally generates Core, and also
853 -- loads the module into the 'Session' so that modules which depend on
854 -- this one may subsequently be typechecked using 'checkModule' or
855 -- 'checkAndLoadModule'. If you need to check more than one module,
856 -- you probably want to use 'checkAndLoadModule'. Constructing the
857 -- interface takes a little work, so it might be slightly slower than
859 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
860 checkAndLoadModule (Session ref) ms compile_to_core
861 = checkModule_ ref ms compile_to_core True
863 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
864 -> IO (Maybe CheckedModule)
865 checkModule_ ref ms compile_to_core load
867 let mod = ms_mod_name ms
868 hsc_env0 <- readIORef ref
869 let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
870 mb_parsed <- parseFile hsc_env ms
872 Nothing -> return Nothing
873 Just rdr_module -> do
874 mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
875 case mb_typechecked of
876 Nothing -> return (Just CheckedModule {
877 parsedSource = rdr_module,
878 renamedSource = Nothing,
879 typecheckedSource = Nothing,
880 checkedModuleInfo = Nothing,
881 coreModule = Nothing })
882 Just (tcg, rn_info) -> do
883 details <- makeSimpleDetails hsc_env tcg
885 let tc_binds = tcg_binds tcg
886 let rdr_env = tcg_rdr_env tcg
887 let minf = ModuleInfo {
888 minf_type_env = md_types details,
889 minf_exports = availsToNameSet $
891 minf_rdr_env = Just rdr_env,
892 minf_instances = md_insts details
894 ,minf_modBreaks = emptyModBreaks
898 mb_guts <- if compile_to_core
899 then deSugarModule hsc_env ms tcg
902 -- If we are loading this module so that we can typecheck
903 -- dependent modules, generate an interface and stuff it
904 -- all in the HomePackageTable.
906 (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
907 let mod_info = HomeModInfo {
909 hm_details = details,
910 hm_linkable = Nothing }
911 let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
912 writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
914 return (Just (CheckedModule {
915 parsedSource = rdr_module,
916 renamedSource = rn_info,
917 typecheckedSource = Just tc_binds,
918 checkedModuleInfo = Just minf,
919 coreModule = mb_guts }))
921 -- | This is the way to get access to the Core bindings corresponding
922 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
923 -- desugar the module, then returns the resulting Core module (consisting of
924 -- the module name, type declarations, and function declarations) if
926 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
927 compileToCoreModule = compileCore False
929 -- | Like compileToCoreModule, but invokes the simplifier, so
930 -- as to return simplified and tidied Core.
931 compileToCoreSimplified :: Session -> FilePath -> IO (Maybe CoreModule)
932 compileToCoreSimplified = compileCore True
934 -- | Provided for backwards-compatibility: compileToCore returns just the Core
935 -- bindings, but for most purposes, you probably want to call
936 -- compileToCoreModule.
937 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
938 compileToCore session fn = do
939 maybeCoreModule <- compileToCoreModule session fn
940 return $ fmap cm_binds maybeCoreModule
942 -- | Takes a CoreModule and compiles the bindings therein
943 -- to object code. The first argument is a bool flag indicating
944 -- whether to run the simplifier.
945 -- The resulting .o, .hi, and executable files, if any, are stored in the
946 -- current directory, and named according to the module name.
947 -- Returns True iff compilation succeeded.
948 -- This has only so far been tested with a single self-contained module.
949 compileCoreToObj :: Bool -> Session -> CoreModule -> IO Bool
950 compileCoreToObj simplify session cm@(CoreModule{ cm_module = mName }) = do
951 hscEnv <- sessionHscEnv session
952 dflags <- getSessionDynFlags session
953 currentTime <- getClockTime
954 cwd <- getCurrentDirectory
955 modLocation <- mkHiOnlyModLocation dflags (hiSuf dflags) cwd
956 ((moduleNameSlashes . moduleName) mName)
958 let modSummary = ModSummary { ms_mod = mName,
959 ms_hsc_src = ExtCoreFile,
960 ms_location = modLocation,
961 -- By setting the object file timestamp to Nothing,
962 -- we always force recompilation, which is what we
963 -- want. (Thus it doesn't matter what the timestamp
964 -- for the (nonexistent) source file is.)
965 ms_hs_date = currentTime,
966 ms_obj_date = Nothing,
967 -- Only handling the single-module case for now, so no imports.
972 ms_hspp_opts = dflags,
973 ms_hspp_buf = Nothing
976 mbHscResult <- evalComp
977 ((if simplify then hscSimplify else return) (mkModGuts cm)
978 >>= hscNormalIface >>= hscWriteIface >>= hscOneShot)
979 (CompState{ compHscEnv=hscEnv,
980 compModSummary=modSummary,
981 compOldIface=Nothing})
982 return $ isJust mbHscResult
984 -- Makes a "vanilla" ModGuts.
985 mkModGuts :: CoreModule -> ModGuts
986 mkModGuts coreModule = ModGuts {
987 mg_module = cm_module coreModule,
990 mg_deps = noDependencies,
991 mg_dir_imps = emptyModuleEnv,
992 mg_used_names = emptyNameSet,
993 mg_rdr_env = emptyGlobalRdrEnv,
994 mg_fix_env = emptyFixityEnv,
995 mg_types = emptyTypeEnv,
999 mg_binds = cm_binds coreModule,
1000 mg_foreign = NoStubs,
1001 mg_warns = NoWarnings,
1002 mg_hpc_info = emptyHpcInfo False,
1003 mg_modBreaks = emptyModBreaks,
1004 mg_vect_info = noVectInfo,
1005 mg_inst_env = emptyInstEnv,
1006 mg_fam_inst_env = emptyFamInstEnv
1009 compileCore :: Bool -> Session -> FilePath -> IO (Maybe CoreModule)
1010 compileCore simplify session fn = do
1011 -- First, set the target to the desired filename
1012 target <- guessTarget fn Nothing
1013 addTarget session target
1014 load session LoadAllTargets
1015 -- Then find dependencies
1016 maybeModGraph <- depanal session [] True
1017 case maybeModGraph of
1018 Nothing -> return Nothing
1020 case find ((== fn) . msHsFilePath) modGraph of
1021 Just modSummary -> do
1022 -- Now we have the module name;
1023 -- parse, typecheck and desugar the module
1024 let mod = ms_mod_name modSummary
1025 maybeCheckedModule <- checkModule session mod True
1026 case maybeCheckedModule of
1027 Nothing -> return Nothing
1028 Just checkedMod -> (liftM $ fmap gutsToCoreModule) $
1029 case (coreModule checkedMod) of
1030 Just mg | simplify -> (sessionHscEnv session)
1031 -- If simplify is true: simplify (hscSimplify),
1032 -- then tidy (tidyProgram).
1033 >>= \ hscEnv -> evalComp (hscSimplify mg)
1034 (CompState{ compHscEnv=hscEnv,
1035 compModSummary=modSummary,
1036 compOldIface=Nothing})
1037 >>= (tidyProgram hscEnv)
1038 >>= (return . Just . Left)
1039 Just guts -> return $ Just $ Right guts
1040 Nothing -> return Nothing
1041 Nothing -> panic "compileToCoreModule: target FilePath not found in\
1042 module dependency graph"
1043 where -- two versions, based on whether we simplify (thus run tidyProgram,
1044 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1045 -- we just have a ModGuts.
1046 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1047 gutsToCoreModule (Left (cg, md)) = CoreModule {
1048 cm_module = cg_module cg, cm_types = md_types md,
1049 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1051 gutsToCoreModule (Right mg) = CoreModule {
1052 cm_module = mg_module mg, cm_types = mg_types mg,
1053 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
1056 -- ---------------------------------------------------------------------------
1059 unload :: HscEnv -> [Linkable] -> IO ()
1060 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1061 = case ghcLink (hsc_dflags hsc_env) of
1063 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1065 LinkInMemory -> panic "unload: no interpreter"
1066 -- urgh. avoid warnings:
1067 hsc_env stable_linkables
1071 -- -----------------------------------------------------------------------------
1075 Stability tells us which modules definitely do not need to be recompiled.
1076 There are two main reasons for having stability:
1078 - avoid doing a complete upsweep of the module graph in GHCi when
1079 modules near the bottom of the tree have not changed.
1081 - to tell GHCi when it can load object code: we can only load object code
1082 for a module when we also load object code fo all of the imports of the
1083 module. So we need to know that we will definitely not be recompiling
1084 any of these modules, and we can use the object code.
1086 The stability check is as follows. Both stableObject and
1087 stableBCO are used during the upsweep phase later.
1090 stable m = stableObject m || stableBCO m
1093 all stableObject (imports m)
1094 && old linkable does not exist, or is == on-disk .o
1095 && date(on-disk .o) > date(.hs)
1098 all stable (imports m)
1099 && date(BCO) > date(.hs)
1102 These properties embody the following ideas:
1104 - if a module is stable, then:
1105 - if it has been compiled in a previous pass (present in HPT)
1106 then it does not need to be compiled or re-linked.
1107 - if it has not been compiled in a previous pass,
1108 then we only need to read its .hi file from disk and
1109 link it to produce a ModDetails.
1111 - if a modules is not stable, we will definitely be at least
1112 re-linking, and possibly re-compiling it during the upsweep.
1113 All non-stable modules can (and should) therefore be unlinked
1116 - Note that objects are only considered stable if they only depend
1117 on other objects. We can't link object code against byte code.
1121 :: HomePackageTable -- HPT from last compilation
1122 -> [SCC ModSummary] -- current module graph (cyclic)
1123 -> [ModuleName] -- all home modules
1124 -> ([ModuleName], -- stableObject
1125 [ModuleName]) -- stableBCO
1127 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1129 checkSCC (stable_obj, stable_bco) scc0
1130 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1131 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
1132 | otherwise = (stable_obj, stable_bco)
1134 scc = flattenSCC scc0
1135 scc_mods = map ms_mod_name scc
1136 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
1138 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1139 -- all imports outside the current SCC, but in the home pkg
1141 stable_obj_imps = map (`elem` stable_obj) scc_allimps
1142 stable_bco_imps = map (`elem` stable_bco) scc_allimps
1146 && all object_ok scc
1149 and (zipWith (||) stable_obj_imps stable_bco_imps)
1153 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
1157 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1158 Just hmi | Just l <- hm_linkable hmi
1159 -> isObjectLinkable l && t == linkableTime l
1161 -- why '>=' rather than '>' above? If the filesystem stores
1162 -- times to the nearset second, we may occasionally find that
1163 -- the object & source have the same modification time,
1164 -- especially if the source was automatically generated
1165 -- and compiled. Using >= is slightly unsafe, but it matches
1166 -- make's behaviour.
1169 = case lookupUFM hpt (ms_mod_name ms) of
1170 Just hmi | Just l <- hm_linkable hmi ->
1171 not (isObjectLinkable l) &&
1172 linkableTime l >= ms_hs_date ms
1175 ms_allimps :: ModSummary -> [ModuleName]
1176 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1178 -- -----------------------------------------------------------------------------
1179 -- Prune the HomePackageTable
1181 -- Before doing an upsweep, we can throw away:
1183 -- - For non-stable modules:
1184 -- - all ModDetails, all linked code
1185 -- - all unlinked code that is out of date with respect to
1188 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1189 -- space at the end of the upsweep, because the topmost ModDetails of the
1190 -- old HPT holds on to the entire type environment from the previous
1193 pruneHomePackageTable
1196 -> ([ModuleName],[ModuleName])
1199 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1202 | is_stable modl = hmi'
1203 | otherwise = hmi'{ hm_details = emptyModDetails }
1205 modl = moduleName (mi_module (hm_iface hmi))
1206 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1207 = hmi{ hm_linkable = Nothing }
1210 where ms = expectJust "prune" (lookupUFM ms_map modl)
1212 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1214 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1216 -- -----------------------------------------------------------------------------
1218 -- Return (names of) all those in modsDone who are part of a cycle
1219 -- as defined by theGraph.
1220 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1221 findPartiallyCompletedCycles modsDone theGraph
1225 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
1226 chew ((CyclicSCC vs):rest)
1227 = let names_in_this_cycle = nub (map ms_mod vs)
1229 = nub ([done | done <- modsDone,
1230 done `elem` names_in_this_cycle])
1231 chewed_rest = chew rest
1233 if notNull mods_in_this_cycle
1234 && length mods_in_this_cycle < length names_in_this_cycle
1235 then mods_in_this_cycle ++ chewed_rest
1238 -- -----------------------------------------------------------------------------
1241 -- This is where we compile each module in the module graph, in a pass
1242 -- from the bottom to the top of the graph.
1244 -- There better had not be any cyclic groups here -- we check for them.
1247 :: HscEnv -- Includes initially-empty HPT
1248 -> HomePackageTable -- HPT from last time round (pruned)
1249 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1250 -> IO () -- How to clean up unwanted tmp files
1251 -> [SCC ModSummary] -- Mods to do (the worklist)
1253 HscEnv, -- With an updated HPT
1254 [ModSummary]) -- Mods which succeeded
1256 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1257 (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1258 return (res, hsc_env, reverse done)
1261 upsweep' hsc_env _old_hpt done
1263 = return (Succeeded, hsc_env, done)
1265 upsweep' hsc_env _old_hpt done
1266 (CyclicSCC ms:_) _ _
1267 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1268 return (Failed, hsc_env, done)
1270 upsweep' hsc_env old_hpt done
1271 (AcyclicSCC mod:mods) mod_index nmods
1272 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1273 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1274 -- (moduleEnvElts (hsc_HPT hsc_env)))
1276 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1279 cleanup -- Remove unwanted tmp files between compilations
1282 Nothing -> return (Failed, hsc_env, done)
1284 let this_mod = ms_mod_name mod
1286 -- Add new info to hsc_env
1287 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1288 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1290 -- Space-saving: delete the old HPT entry
1291 -- for mod BUT if mod is a hs-boot
1292 -- node, don't delete it. For the
1293 -- interface, the HPT entry is probaby for the
1294 -- main Haskell source file. Deleting it
1295 -- would force the real module to be recompiled
1297 old_hpt1 | isBootSummary mod = old_hpt
1298 | otherwise = delFromUFM old_hpt this_mod
1302 -- fixup our HomePackageTable after we've finished compiling
1303 -- a mutually-recursive loop. See reTypecheckLoop, below.
1304 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1306 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1309 -- Compile a single module. Always produce a Linkable for it if
1310 -- successful. If no compilation happened, return the old Linkable.
1311 upsweep_mod :: HscEnv
1313 -> ([ModuleName],[ModuleName])
1315 -> Int -- index of module
1316 -> Int -- total number of modules
1317 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1319 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1321 this_mod_name = ms_mod_name summary
1322 this_mod = ms_mod summary
1323 mb_obj_date = ms_obj_date summary
1324 obj_fn = ml_obj_file (ms_location summary)
1325 hs_date = ms_hs_date summary
1327 is_stable_obj = this_mod_name `elem` stable_obj
1328 is_stable_bco = this_mod_name `elem` stable_bco
1330 old_hmi = lookupUFM old_hpt this_mod_name
1332 -- We're using the dflags for this module now, obtained by
1333 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1334 dflags = ms_hspp_opts summary
1335 prevailing_target = hscTarget (hsc_dflags hsc_env)
1336 local_target = hscTarget dflags
1338 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1339 -- we don't do anything dodgy: these should only work to change
1340 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1341 -- end up trying to link object code to byte code.
1342 target = if prevailing_target /= local_target
1343 && (not (isObjectTarget prevailing_target)
1344 || not (isObjectTarget local_target))
1345 then prevailing_target
1348 -- store the corrected hscTarget into the summary
1349 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1351 -- The old interface is ok if
1352 -- a) we're compiling a source file, and the old HPT
1353 -- entry is for a source file
1354 -- b) we're compiling a hs-boot file
1355 -- Case (b) allows an hs-boot file to get the interface of its
1356 -- real source file on the second iteration of the compilation
1357 -- manager, but that does no harm. Otherwise the hs-boot file
1358 -- will always be recompiled
1363 Just hm_info | isBootSummary summary -> Just iface
1364 | not (mi_boot iface) -> Just iface
1365 | otherwise -> Nothing
1367 iface = hm_iface hm_info
1369 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1370 compile_it = compile hsc_env summary' mod_index nmods mb_old_iface
1372 compile_it_discard_iface
1373 = compile hsc_env summary' mod_index nmods Nothing
1379 -- Regardless of whether we're generating object code or
1380 -- byte code, we can always use an existing object file
1381 -- if it is *stable* (see checkStability).
1382 | is_stable_obj, isJust old_hmi ->
1384 -- object is stable, and we have an entry in the
1385 -- old HPT: nothing to do
1387 | is_stable_obj, isNothing old_hmi -> do
1388 linkable <- findObjectLinkable this_mod obj_fn
1389 (expectJust "upseep1" mb_obj_date)
1390 compile_it (Just linkable)
1391 -- object is stable, but we need to load the interface
1392 -- off disk to make a HMI.
1396 ASSERT(isJust old_hmi) -- must be in the old_hpt
1398 -- BCO is stable: nothing to do
1400 | Just hmi <- old_hmi,
1401 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1402 linkableTime l >= ms_hs_date summary ->
1404 -- we have an old BCO that is up to date with respect
1405 -- to the source: do a recompilation check as normal.
1409 -- no existing code at all: we must recompile.
1411 -- When generating object code, if there's an up-to-date
1412 -- object file on the disk, then we can use it.
1413 -- However, if the object file is new (compared to any
1414 -- linkable we had from a previous compilation), then we
1415 -- must discard any in-memory interface, because this
1416 -- means the user has compiled the source file
1417 -- separately and generated a new interface, that we must
1418 -- read from the disk.
1420 obj | isObjectTarget obj,
1421 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1424 | Just l <- hm_linkable hmi,
1425 isObjectLinkable l && linkableTime l == obj_date
1426 -> compile_it (Just l)
1428 linkable <- findObjectLinkable this_mod obj_fn obj_date
1429 compile_it_discard_iface (Just linkable)
1436 -- Filter modules in the HPT
1437 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1438 retainInTopLevelEnvs keep_these hpt
1439 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1441 , let mb_mod_info = lookupUFM hpt mod
1442 , isJust mb_mod_info ]
1444 -- ---------------------------------------------------------------------------
1445 -- Typecheck module loops
1448 See bug #930. This code fixes a long-standing bug in --make. The
1449 problem is that when compiling the modules *inside* a loop, a data
1450 type that is only defined at the top of the loop looks opaque; but
1451 after the loop is done, the structure of the data type becomes
1454 The difficulty is then that two different bits of code have
1455 different notions of what the data type looks like.
1457 The idea is that after we compile a module which also has an .hs-boot
1458 file, we re-generate the ModDetails for each of the modules that
1459 depends on the .hs-boot file, so that everyone points to the proper
1460 TyCons, Ids etc. defined by the real module, not the boot module.
1461 Fortunately re-generating a ModDetails from a ModIface is easy: the
1462 function TcIface.typecheckIface does exactly that.
1464 Picking the modules to re-typecheck is slightly tricky. Starting from
1465 the module graph consisting of the modules that have already been
1466 compiled, we reverse the edges (so they point from the imported module
1467 to the importing module), and depth-first-search from the .hs-boot
1468 node. This gives us all the modules that depend transitively on the
1469 .hs-boot module, and those are exactly the modules that we need to
1472 Following this fix, GHC can compile itself with --make -O2.
1475 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1476 reTypecheckLoop hsc_env ms graph
1477 | not (isBootSummary ms) &&
1478 any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1480 let mss = reachableBackwards (ms_mod_name ms) graph
1481 non_boot = filter (not.isBootSummary) mss
1482 debugTraceMsg (hsc_dflags hsc_env) 2 $
1483 text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1484 typecheckLoop hsc_env (map ms_mod_name non_boot)
1488 this_mod = ms_mod ms
1490 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1491 typecheckLoop hsc_env mods = do
1493 fixIO $ \new_hpt -> do
1494 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1495 mds <- initIfaceCheck new_hsc_env $
1496 mapM (typecheckIface . hm_iface) hmis
1497 let new_hpt = addListToUFM old_hpt
1498 (zip mods [ hmi{ hm_details = details }
1499 | (hmi,details) <- zip hmis mds ])
1501 return hsc_env{ hsc_HPT = new_hpt }
1503 old_hpt = hsc_HPT hsc_env
1504 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1506 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1507 reachableBackwards mod summaries
1508 = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1510 -- all the nodes reachable by traversing the edges backwards
1511 -- from the root node:
1512 nodes_we_want = reachable (transposeG graph) root
1514 -- the rest just sets up the graph:
1515 (nodes, lookup_key) = moduleGraphNodes False summaries
1516 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1518 | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1519 | otherwise = panic "reachableBackwards"
1521 -- ---------------------------------------------------------------------------
1522 -- Topological sort of the module graph
1525 :: Bool -- Drop hi-boot nodes? (see below)
1529 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1530 -- The resulting list of strongly-connected-components is in topologically
1531 -- sorted order, starting with the module(s) at the bottom of the
1532 -- dependency graph (ie compile them first) and ending with the ones at
1535 -- Drop hi-boot nodes (first boolean arg)?
1537 -- False: treat the hi-boot summaries as nodes of the graph,
1538 -- so the graph must be acyclic
1540 -- True: eliminate the hi-boot nodes, and instead pretend
1541 -- the a source-import of Foo is an import of Foo
1542 -- The resulting graph has no hi-boot nodes, but can by cyclic
1544 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1545 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1546 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1547 = stronglyConnComp (map vertex_fn (reachable graph root))
1549 -- restrict the graph to just those modules reachable from
1550 -- the specified module. We do this by building a graph with
1551 -- the full set of nodes, and determining the reachable set from
1552 -- the specified node.
1553 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1554 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1556 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1557 | otherwise = throwDyn (ProgramError "module does not exist")
1559 moduleGraphNodes :: Bool -> [ModSummary]
1560 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1561 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1563 -- Drop hs-boot nodes by using HsSrcFile as the key
1564 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1565 | otherwise = HsBootFile
1567 -- We use integers as the keys for the SCC algorithm
1568 nodes :: [(ModSummary, Int, [Int])]
1569 nodes = [(s, expectJust "topSort" $
1570 lookup_key (ms_hsc_src s) (ms_mod_name s),
1571 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1572 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1573 (-- see [boot-edges] below
1574 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1576 else case lookup_key HsBootFile (ms_mod_name s) of
1581 , not (isBootSummary s && drop_hs_boot_nodes) ]
1582 -- Drop the hi-boot ones if told to do so
1584 -- [boot-edges] if this is a .hs and there is an equivalent
1585 -- .hs-boot, add a link from the former to the latter. This
1586 -- has the effect of detecting bogus cases where the .hs-boot
1587 -- depends on the .hs, by introducing a cycle. Additionally,
1588 -- it ensures that we will always process the .hs-boot before
1589 -- the .hs, and so the HomePackageTable will always have the
1590 -- most up to date information.
1592 key_map :: NodeMap Int
1593 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1597 lookup_key :: HscSource -> ModuleName -> Maybe Int
1598 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1600 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1601 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1602 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1603 -- the IsBootInterface parameter True; else False
1606 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1607 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1609 msKey :: ModSummary -> NodeKey
1610 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1612 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1613 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1615 nodeMapElts :: NodeMap a -> [a]
1616 nodeMapElts = eltsFM
1618 -- If there are {-# SOURCE #-} imports between strongly connected
1619 -- components in the topological sort, then those imports can
1620 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1621 -- were necessary, then the edge would be part of a cycle.
1622 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1623 warnUnnecessarySourceImports dflags sccs =
1624 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1626 let mods_in_this_cycle = map ms_mod_name ms in
1627 [ warn i | m <- ms, i <- ms_srcimps m,
1628 unLoc i `notElem` mods_in_this_cycle ]
1630 warn :: Located ModuleName -> WarnMsg
1633 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1634 <+> quotes (ppr mod))
1636 -----------------------------------------------------------------------------
1637 -- Downsweep (dependency analysis)
1639 -- Chase downwards from the specified root set, returning summaries
1640 -- for all home modules encountered. Only follow source-import
1643 -- We pass in the previous collection of summaries, which is used as a
1644 -- cache to avoid recalculating a module summary if the source is
1647 -- The returned list of [ModSummary] nodes has one node for each home-package
1648 -- module, plus one for any hs-boot files. The imports of these nodes
1649 -- are all there, including the imports of non-home-package modules.
1652 -> [ModSummary] -- Old summaries
1653 -> [ModuleName] -- Ignore dependencies on these; treat
1654 -- them as if they were package modules
1655 -> Bool -- True <=> allow multiple targets to have
1656 -- the same module name; this is
1657 -- very useful for ghc -M
1658 -> IO (Maybe [ModSummary])
1659 -- The elts of [ModSummary] all have distinct
1660 -- (Modules, IsBoot) identifiers, unless the Bool is true
1661 -- in which case there can be repeats
1662 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1663 = -- catch error messages and return them
1664 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1665 rootSummaries <- mapM getRootSummary roots
1666 let root_map = mkRootMap rootSummaries
1667 checkDuplicates root_map
1668 summs <- loop (concatMap msDeps rootSummaries) root_map
1671 roots = hsc_targets hsc_env
1673 old_summary_map :: NodeMap ModSummary
1674 old_summary_map = mkNodeMap old_summaries
1676 getRootSummary :: Target -> IO ModSummary
1677 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1678 = do exists <- doesFileExist file
1680 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1681 else throwDyn $ mkPlainErrMsg noSrcSpan $
1682 text "can't find file:" <+> text file
1683 getRootSummary (Target (TargetModule modl) maybe_buf)
1684 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1685 (L rootLoc modl) maybe_buf excl_mods
1686 case maybe_summary of
1687 Nothing -> packageModErr modl
1690 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1692 -- In a root module, the filename is allowed to diverge from the module
1693 -- name, so we have to check that there aren't multiple root files
1694 -- defining the same module (otherwise the duplicates will be silently
1695 -- ignored, leading to confusing behaviour).
1696 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1697 checkDuplicates root_map
1698 | allow_dup_roots = return ()
1699 | null dup_roots = return ()
1700 | otherwise = multiRootsErr (head dup_roots)
1702 dup_roots :: [[ModSummary]] -- Each at least of length 2
1703 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1705 loop :: [(Located ModuleName,IsBootInterface)]
1706 -- Work list: process these modules
1707 -> NodeMap [ModSummary]
1708 -- Visited set; the range is a list because
1709 -- the roots can have the same module names
1710 -- if allow_dup_roots is True
1712 -- The result includes the worklist, except
1713 -- for those mentioned in the visited set
1714 loop [] done = return (concat (nodeMapElts done))
1715 loop ((wanted_mod, is_boot) : ss) done
1716 | Just summs <- lookupFM done key
1717 = if isSingleton summs then
1720 do { multiRootsErr summs; return [] }
1721 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1722 is_boot wanted_mod Nothing excl_mods
1724 Nothing -> loop ss done
1725 Just s -> loop (msDeps s ++ ss)
1726 (addToFM done key [s]) }
1728 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1730 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1731 mkRootMap summaries = addListToFM_C (++) emptyFM
1732 [ (msKey s, [s]) | s <- summaries ]
1734 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1735 -- (msDeps s) returns the dependencies of the ModSummary s.
1736 -- A wrinkle is that for a {-# SOURCE #-} import we return
1737 -- *both* the hs-boot file
1738 -- *and* the source file
1739 -- as "dependencies". That ensures that the list of all relevant
1740 -- modules always contains B.hs if it contains B.hs-boot.
1741 -- Remember, this pass isn't doing the topological sort. It's
1742 -- just gathering the list of all relevant ModSummaries
1744 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1745 ++ [ (m,False) | m <- ms_imps s ]
1747 -----------------------------------------------------------------------------
1748 -- Summarising modules
1750 -- We have two types of summarisation:
1752 -- * Summarise a file. This is used for the root module(s) passed to
1753 -- cmLoadModules. The file is read, and used to determine the root
1754 -- module name. The module name may differ from the filename.
1756 -- * Summarise a module. We are given a module name, and must provide
1757 -- a summary. The finder is used to locate the file in which the module
1762 -> [ModSummary] -- old summaries
1763 -> FilePath -- source file name
1764 -> Maybe Phase -- start phase
1765 -> Maybe (StringBuffer,ClockTime)
1768 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1769 -- we can use a cached summary if one is available and the
1770 -- source file hasn't changed, But we have to look up the summary
1771 -- by source file, rather than module name as we do in summarise.
1772 | Just old_summary <- findSummaryBySourceFile old_summaries file
1774 let location = ms_location old_summary
1776 -- return the cached summary if the source didn't change
1777 src_timestamp <- case maybe_buf of
1778 Just (_,t) -> return t
1779 Nothing -> getModificationTime file
1780 -- The file exists; we checked in getRootSummary above.
1781 -- If it gets removed subsequently, then this
1782 -- getModificationTime may fail, but that's the right
1785 if ms_hs_date old_summary == src_timestamp
1786 then do -- update the object-file timestamp
1788 if isObjectTarget (hscTarget (hsc_dflags hsc_env)) -- bug #1205
1789 then getObjTimestamp location False
1791 return old_summary{ ms_obj_date = obj_timestamp }
1799 let dflags = hsc_dflags hsc_env
1801 (dflags', hspp_fn, buf)
1802 <- preprocessFile hsc_env file mb_phase maybe_buf
1804 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1806 -- Make a ModLocation for this file
1807 location <- mkHomeModLocation dflags mod_name file
1809 -- Tell the Finder cache where it is, so that subsequent calls
1810 -- to findModule will find it, even if it's not on any search path
1811 mod <- addHomeModuleToFinder hsc_env mod_name location
1813 src_timestamp <- case maybe_buf of
1814 Just (_,t) -> return t
1815 Nothing -> getModificationTime file
1816 -- getMofificationTime may fail
1818 -- when the user asks to load a source file by name, we only
1819 -- use an object file if -fobject-code is on. See #1205.
1821 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1822 then modificationTimeIfExists (ml_obj_file location)
1825 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1826 ms_location = location,
1827 ms_hspp_file = hspp_fn,
1828 ms_hspp_opts = dflags',
1829 ms_hspp_buf = Just buf,
1830 ms_srcimps = srcimps, ms_imps = the_imps,
1831 ms_hs_date = src_timestamp,
1832 ms_obj_date = obj_timestamp })
1834 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1835 findSummaryBySourceFile summaries file
1836 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1837 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1841 -- Summarise a module, and pick up source and timestamp.
1844 -> NodeMap ModSummary -- Map of old summaries
1845 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1846 -> Located ModuleName -- Imported module to be summarised
1847 -> Maybe (StringBuffer, ClockTime)
1848 -> [ModuleName] -- Modules to exclude
1849 -> IO (Maybe ModSummary) -- Its new summary
1851 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1852 | wanted_mod `elem` excl_mods
1855 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1856 = do -- Find its new timestamp; all the
1857 -- ModSummaries in the old map have valid ml_hs_files
1858 let location = ms_location old_summary
1859 src_fn = expectJust "summariseModule" (ml_hs_file location)
1861 -- check the modification time on the source file, and
1862 -- return the cached summary if it hasn't changed. If the
1863 -- file has disappeared, we need to call the Finder again.
1865 Just (_,t) -> check_timestamp old_summary location src_fn t
1867 m <- System.IO.Error.try (getModificationTime src_fn)
1869 Right t -> check_timestamp old_summary location src_fn t
1870 Left e | isDoesNotExistError e -> find_it
1871 | otherwise -> ioError e
1873 | otherwise = find_it
1875 dflags = hsc_dflags hsc_env
1877 hsc_src = if is_boot then HsBootFile else HsSrcFile
1879 check_timestamp old_summary location src_fn src_timestamp
1880 | ms_hs_date old_summary == src_timestamp = do
1881 -- update the object-file timestamp
1882 obj_timestamp <- getObjTimestamp location is_boot
1883 return (Just old_summary{ ms_obj_date = obj_timestamp })
1885 -- source changed: re-summarise.
1886 new_summary location (ms_mod old_summary) src_fn src_timestamp
1889 -- Don't use the Finder's cache this time. If the module was
1890 -- previously a package module, it may have now appeared on the
1891 -- search path, so we want to consider it to be a home module. If
1892 -- the module was previously a home module, it may have moved.
1893 uncacheModule hsc_env wanted_mod
1894 found <- findImportedModule hsc_env wanted_mod Nothing
1897 | isJust (ml_hs_file location) ->
1899 just_found location mod
1901 -- Drop external-pkg
1902 ASSERT(modulePackageId mod /= thisPackage dflags)
1905 err -> noModError dflags loc wanted_mod err
1908 just_found location mod = do
1909 -- Adjust location to point to the hs-boot source file,
1910 -- hi file, object file, when is_boot says so
1911 let location' | is_boot = addBootSuffixLocn location
1912 | otherwise = location
1913 src_fn = expectJust "summarise2" (ml_hs_file location')
1915 -- Check that it exists
1916 -- It might have been deleted since the Finder last found it
1917 maybe_t <- modificationTimeIfExists src_fn
1919 Nothing -> noHsFileErr loc src_fn
1920 Just t -> new_summary location' mod src_fn t
1923 new_summary location mod src_fn src_timestamp
1925 -- Preprocess the source file and get its imports
1926 -- The dflags' contains the OPTIONS pragmas
1927 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
1928 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1930 when (mod_name /= wanted_mod) $
1931 throwDyn $ mkPlainErrMsg mod_loc $
1932 text "File name does not match module name:"
1933 $$ text "Saw:" <+> quotes (ppr mod_name)
1934 $$ text "Expected:" <+> quotes (ppr wanted_mod)
1936 -- Find the object timestamp, and return the summary
1937 obj_timestamp <- getObjTimestamp location is_boot
1939 return (Just ( ModSummary { ms_mod = mod,
1940 ms_hsc_src = hsc_src,
1941 ms_location = location,
1942 ms_hspp_file = hspp_fn,
1943 ms_hspp_opts = dflags',
1944 ms_hspp_buf = Just buf,
1945 ms_srcimps = srcimps,
1947 ms_hs_date = src_timestamp,
1948 ms_obj_date = obj_timestamp }))
1951 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1952 getObjTimestamp location is_boot
1953 = if is_boot then return Nothing
1954 else modificationTimeIfExists (ml_obj_file location)
1957 preprocessFile :: HscEnv -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1958 -> IO (DynFlags, FilePath, StringBuffer)
1959 preprocessFile hsc_env src_fn mb_phase Nothing
1961 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
1962 buf <- hGetStringBuffer hspp_fn
1963 return (dflags', hspp_fn, buf)
1965 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
1967 let dflags = hsc_dflags hsc_env
1968 -- case we bypass the preprocessing stage?
1970 local_opts = getOptions dflags buf src_fn
1972 (dflags', leftovers, warns) <- parseDynamicFlags dflags (map unLoc local_opts)
1973 checkProcessArgsResult leftovers src_fn
1974 handleFlagWarnings dflags' warns
1978 | Just (Unlit _) <- mb_phase = True
1979 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1980 -- note: local_opts is only required if there's no Unlit phase
1981 | dopt Opt_Cpp dflags' = True
1982 | dopt Opt_Pp dflags' = True
1985 when needs_preprocessing $
1986 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1988 return (dflags', src_fn, buf)
1991 -----------------------------------------------------------------------------
1993 -----------------------------------------------------------------------------
1995 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1996 -- ToDo: we don't have a proper line number for this error
1997 noModError dflags loc wanted_mod err
1998 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
2000 noHsFileErr :: SrcSpan -> String -> a
2001 noHsFileErr loc path
2002 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2004 packageModErr :: ModuleName -> a
2006 = throwDyn $ mkPlainErrMsg noSrcSpan $
2007 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2009 multiRootsErr :: [ModSummary] -> IO ()
2010 multiRootsErr [] = panic "multiRootsErr"
2011 multiRootsErr summs@(summ1:_)
2012 = throwDyn $ mkPlainErrMsg noSrcSpan $
2013 text "module" <+> quotes (ppr mod) <+>
2014 text "is defined in multiple files:" <+>
2015 sep (map text files)
2018 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2020 cyclicModuleErr :: [ModSummary] -> SDoc
2022 = hang (ptext (sLit "Module imports form a cycle for modules:"))
2023 2 (vcat (map show_one ms))
2025 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2026 nest 2 $ ptext (sLit "imports:") <+>
2027 (pp_imps HsBootFile (ms_srcimps ms)
2028 $$ pp_imps HsSrcFile (ms_imps ms))]
2029 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2030 pp_imps src mods = fsep (map (show_mod src) mods)
2033 -- | Inform GHC that the working directory has changed. GHC will flush
2034 -- its cache of module locations, since it may no longer be valid.
2035 -- Note: if you change the working directory, you should also unload
2036 -- the current program (set targets to empty, followed by load).
2037 workingDirectoryChanged :: Session -> IO ()
2038 workingDirectoryChanged s = withSession s $ flushFinderCaches
2040 -- -----------------------------------------------------------------------------
2041 -- inspecting the session
2043 -- | Get the module dependency graph.
2044 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
2045 getModuleGraph s = withSession s (return . hsc_mod_graph)
2047 isLoaded :: Session -> ModuleName -> IO Bool
2048 isLoaded s m = withSession s $ \hsc_env ->
2049 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2051 getBindings :: Session -> IO [TyThing]
2052 getBindings s = withSession s $ \hsc_env ->
2053 -- we have to implement the shadowing behaviour of ic_tmp_ids here
2054 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2056 tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2057 filtered = foldr f (const []) tmp_ids emptyUniqSet
2059 | uniq `elementOfUniqSet` set = rest set
2060 | otherwise = AnId id : rest (addOneToUniqSet set uniq)
2061 where uniq = getUnique (nameOccName (idName id))
2065 getPrintUnqual :: Session -> IO PrintUnqualified
2066 getPrintUnqual s = withSession s $ \hsc_env ->
2067 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2069 -- | Container for information about a 'Module'.
2070 data ModuleInfo = ModuleInfo {
2071 minf_type_env :: TypeEnv,
2072 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2073 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
2074 minf_instances :: [Instance]
2076 ,minf_modBreaks :: ModBreaks
2078 -- ToDo: this should really contain the ModIface too
2080 -- We don't want HomeModInfo here, because a ModuleInfo applies
2081 -- to package modules too.
2083 -- | Request information about a loaded 'Module'
2084 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
2085 getModuleInfo s mdl = withSession s $ \hsc_env -> do
2086 let mg = hsc_mod_graph hsc_env
2087 if mdl `elem` map ms_mod mg
2088 then getHomeModuleInfo hsc_env (moduleName mdl)
2090 {- if isHomeModule (hsc_dflags hsc_env) mdl
2092 else -} getPackageModuleInfo hsc_env mdl
2093 -- getPackageModuleInfo will attempt to find the interface, so
2094 -- we don't want to call it for a home module, just in case there
2095 -- was a problem loading the module and the interface doesn't
2096 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
2098 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2100 getPackageModuleInfo hsc_env mdl = do
2101 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2103 Nothing -> return Nothing
2105 eps <- readIORef (hsc_EPS hsc_env)
2107 names = availsToNameSet avails
2109 tys = [ ty | name <- concatMap availNames avails,
2110 Just ty <- [lookupTypeEnv pte name] ]
2112 return (Just (ModuleInfo {
2113 minf_type_env = mkTypeEnv tys,
2114 minf_exports = names,
2115 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2116 minf_instances = error "getModuleInfo: instances for package module unimplemented",
2117 minf_modBreaks = emptyModBreaks
2120 getPackageModuleInfo _hsc_env _mdl = do
2121 -- bogusly different for non-GHCI (ToDo)
2125 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2126 getHomeModuleInfo hsc_env mdl =
2127 case lookupUFM (hsc_HPT hsc_env) mdl of
2128 Nothing -> return Nothing
2130 let details = hm_details hmi
2131 return (Just (ModuleInfo {
2132 minf_type_env = md_types details,
2133 minf_exports = availsToNameSet (md_exports details),
2134 minf_rdr_env = mi_globals $! hm_iface hmi,
2135 minf_instances = md_insts details
2137 ,minf_modBreaks = getModBreaks hmi
2141 -- | The list of top-level entities defined in a module
2142 modInfoTyThings :: ModuleInfo -> [TyThing]
2143 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2145 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2146 modInfoTopLevelScope minf
2147 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2149 modInfoExports :: ModuleInfo -> [Name]
2150 modInfoExports minf = nameSetToList $! minf_exports minf
2152 -- | Returns the instances defined by the specified module.
2153 -- Warning: currently unimplemented for package modules.
2154 modInfoInstances :: ModuleInfo -> [Instance]
2155 modInfoInstances = minf_instances
2157 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2158 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2160 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2161 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2162 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2164 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2165 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2166 case lookupTypeEnv (minf_type_env minf) name of
2167 Just tyThing -> return (Just tyThing)
2169 eps <- readIORef (hsc_EPS hsc_env)
2170 return $! lookupType (hsc_dflags hsc_env)
2171 (hsc_HPT hsc_env) (eps_PTE eps) name
2174 modInfoModBreaks :: ModuleInfo -> ModBreaks
2175 modInfoModBreaks = minf_modBreaks
2178 isDictonaryId :: Id -> Bool
2180 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2182 -- | Looks up a global name: that is, any top-level name in any
2183 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
2184 -- the interactive context, and therefore does not require a preceding
2186 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2187 lookupGlobalName s name = withSession s $ \hsc_env -> do
2188 eps <- readIORef (hsc_EPS hsc_env)
2189 return $! lookupType (hsc_dflags hsc_env)
2190 (hsc_HPT hsc_env) (eps_PTE eps) name
2193 -- | get the GlobalRdrEnv for a session
2194 getGRE :: Session -> IO GlobalRdrEnv
2195 getGRE s = withSession s $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2198 -- -----------------------------------------------------------------------------
2199 -- Misc exported utils
2201 dataConType :: DataCon -> Type
2202 dataConType dc = idType (dataConWrapId dc)
2204 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2205 pprParenSymName :: NamedThing a => a -> SDoc
2206 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2208 -- ----------------------------------------------------------------------------
2213 -- - Data and Typeable instances for HsSyn.
2215 -- ToDo: check for small transformations that happen to the syntax in
2216 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2218 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
2219 -- to get from TyCons, Ids etc. to TH syntax (reify).
2221 -- :browse will use either lm_toplev or inspect lm_interface, depending
2222 -- on whether the module is interpreted or not.
2224 -- This is for reconstructing refactored source code
2225 -- Calls the lexer repeatedly.
2226 -- ToDo: add comment tokens to token stream
2227 getTokenStream :: Session -> Module -> IO [Located Token]
2230 -- -----------------------------------------------------------------------------
2231 -- Interactive evaluation
2233 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2234 -- filesystem and package database to find the corresponding 'Module',
2235 -- using the algorithm that is used for an @import@ declaration.
2236 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2237 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2239 dflags = hsc_dflags hsc_env
2240 hpt = hsc_HPT hsc_env
2241 this_pkg = thisPackage dflags
2243 case lookupUFM hpt mod_name of
2244 Just mod_info -> return (mi_module (hm_iface mod_info))
2245 _not_a_home_module -> do
2246 res <- findImportedModule hsc_env mod_name maybe_pkg
2248 Found _ m | modulePackageId m /= this_pkg -> return m
2249 | otherwise -> throwDyn (CmdLineError (showSDoc $
2250 text "module" <+> quotes (ppr (moduleName m)) <+>
2251 text "is not loaded"))
2252 err -> let msg = cannotFindModule dflags mod_name err in
2253 throwDyn (CmdLineError (showSDoc msg))
2256 getHistorySpan :: Session -> History -> IO SrcSpan
2257 getHistorySpan sess h = withSession sess $ \hsc_env ->
2258 return$ InteractiveEval.getHistorySpan hsc_env h
2260 obtainTerm :: Session -> Bool -> Id -> IO Term
2261 obtainTerm sess force id = withSession sess $ \hsc_env ->
2262 InteractiveEval.obtainTerm hsc_env force id
2264 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2265 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2266 InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2268 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2269 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2270 InteractiveEval.obtainTermB hsc_env bound force id