1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
26 Target(..), TargetId(..),
33 -- * Loading\/compiling the program
35 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
37 workingDirectoryChanged,
38 checkModule, CheckedModule(..),
39 TypecheckedSource, ParsedSource, RenamedSource,
41 -- * Inspecting the module structure of the program
42 ModuleGraph, ModSummary(..),
47 -- * Inspecting modules
52 modInfoPrintUnqualified,
56 -- * Interactive evaluation
57 getBindings, getPrintUnqual,
59 setContext, getContext,
62 getInfo, GetInfoResult,
74 -- * Abstract syntax elements
77 Module, mkModule, pprModule,
84 isImplicitId, isDeadBinder,
85 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
87 isPrimOpId, isFCallId,
88 isDataConWorkId, idDataCon,
89 isBottomingId, isDictonaryId,
91 -- ** Type constructors
93 isClassTyCon, isSynTyCon, isNewTyCon,
95 -- ** Data constructors
100 classSCTheta, classTvsFds,
102 -- ** Types and Kinds
110 module HsSyn, -- ToDo: remove extraneous bits
113 GhcException(..), showGhcException,
123 * inline bits of HscMain here to simplify layering: hscGetInfo,
125 * we need to expose DynFlags, so should parseDynamicFlags really be
126 part of this interface?
127 * what StaticFlags should we expose, if any?
130 #include "HsVersions.h"
133 import qualified Linker
134 import Linker ( HValue, extendLinkEnv )
135 import NameEnv ( lookupNameEnv )
136 import TcRnDriver ( getModuleContents, tcRnLookupRdrName,
138 import RdrName ( plusGlobalRdrEnv, Provenance(..), ImportSpec(..),
139 emptyGlobalRdrEnv, mkGlobalRdrEnv )
140 import HscMain ( hscGetInfo, GetInfoResult, hscParseIdentifier,
141 hscStmt, hscTcExpr, hscKcType )
142 import Type ( tidyType )
143 import VarEnv ( emptyTidyEnv )
144 import GHC.Exts ( unsafeCoerce# )
145 import IfaceSyn ( IfaceDecl )
146 import Name ( getName, nameModule_maybe )
147 import SrcLoc ( mkSrcLoc, srcLocSpan, interactiveSrcLoc )
148 import Bag ( unitBag, emptyBag )
151 import Packages ( initPackages )
152 import NameSet ( NameSet, nameSetToList )
153 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName, gre_name,
156 import Type ( Kind, Type, dropForAlls )
157 import Id ( Id, idType, isImplicitId, isDeadBinder,
158 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
160 isPrimOpId, isFCallId,
161 isDataConWorkId, idDataCon,
163 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon )
164 import Class ( Class, classSCTheta, classTvsFds )
165 import DataCon ( DataCon )
166 import Name ( Name, nameModule )
167 import NameEnv ( nameEnvElts )
168 import SrcLoc ( Located(..) )
169 import DriverPipeline
170 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
171 import GetImports ( getImports )
172 import Packages ( isHomePackage )
174 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
178 import SysTools ( initSysTools, cleanTempFiles )
183 import ErrUtils ( showPass, Messages, putMsg, debugTraceMsg )
184 import qualified ErrUtils
186 import StringBuffer ( StringBuffer, hGetStringBuffer )
188 import SysTools ( cleanTempFilesExcept )
189 import BasicTypes ( SuccessFlag(..), succeeded, failed )
190 import Maybes ( orElse, expectJust, mapCatMaybes )
191 import TcType ( tcSplitSigmaTy, isDictTy )
192 import FastString ( mkFastString )
194 import Directory ( getModificationTime, doesFileExist )
195 import Maybe ( isJust, isNothing, fromJust, fromMaybe, catMaybes )
196 import Maybes ( expectJust )
197 import List ( partition, nub )
198 import qualified List
199 import Monad ( unless, when, foldM )
200 import System ( exitWith, ExitCode(..) )
201 import Time ( ClockTime )
202 import EXCEPTION as Exception hiding (handle)
205 import Prelude hiding (init)
207 -- -----------------------------------------------------------------------------
208 -- Exception handlers
210 -- | Install some default exception handlers and run the inner computation.
211 -- Unless you want to handle exceptions yourself, you should wrap this around
212 -- the top level of your program. The default handlers output the error
213 -- message(s) to stderr and exit cleanly.
214 defaultErrorHandler :: IO a -> IO a
215 defaultErrorHandler inner =
216 -- top-level exception handler: any unrecognised exception is a compiler bug.
217 handle (\exception -> do
220 -- an IO exception probably isn't our fault, so don't panic
221 IOException _ -> putMsg (show exception)
222 AsyncException StackOverflow ->
223 putMsg "stack overflow: use +RTS -K<size> to increase it"
224 _other -> putMsg (show (Panic (show exception)))
225 exitWith (ExitFailure 1)
228 -- all error messages are propagated as exceptions
229 handleDyn (\dyn -> do
232 PhaseFailed _ code -> exitWith code
233 Interrupted -> exitWith (ExitFailure 1)
234 _ -> do putMsg (show (dyn :: GhcException))
235 exitWith (ExitFailure 1)
239 -- | Install a default cleanup handler to remove temporary files
240 -- deposited by a GHC run. This is seperate from
241 -- 'defaultErrorHandler', because you might want to override the error
242 -- handling, but still get the ordinary cleanup behaviour.
243 defaultCleanupHandler :: DynFlags -> IO a -> IO a
244 defaultCleanupHandler dflags inner =
245 -- make sure we clean up after ourselves
246 later (unless (dopt Opt_KeepTmpFiles dflags) $
247 cleanTempFiles dflags)
248 -- exceptions will be blocked while we clean the temporary files,
249 -- so there shouldn't be any difficulty if we receive further
254 -- | Initialises GHC. This must be done /once/ only. Takes the
255 -- command-line arguments. All command-line arguments which aren't
256 -- understood by GHC will be returned.
258 init :: [String] -> IO [String]
261 installSignalHandlers
263 -- Grab the -B option if there is one
264 let (minusB_args, argv1) = partition (prefixMatch "-B") args
265 dflags0 <- initSysTools minusB_args defaultDynFlags
266 writeIORef v_initDynFlags dflags0
268 -- Parse the static flags
269 argv2 <- parseStaticFlags argv1
272 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
273 -- stores the DynFlags between the call to init and subsequent
274 -- calls to newSession.
276 -- | Starts a new session. A session consists of a set of loaded
277 -- modules, a set of options (DynFlags), and an interactive context.
278 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
280 newSession :: GhcMode -> IO Session
282 dflags0 <- readIORef v_initDynFlags
283 dflags <- initDynFlags dflags0
284 env <- newHscEnv dflags{ ghcMode=mode }
288 -- tmp: this breaks the abstraction, but required because DriverMkDepend
289 -- needs to call the Finder. ToDo: untangle this.
290 sessionHscEnv :: Session -> IO HscEnv
291 sessionHscEnv (Session ref) = readIORef ref
293 withSession :: Session -> (HscEnv -> IO a) -> IO a
294 withSession (Session ref) f = do h <- readIORef ref; f h
296 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
297 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
299 -- -----------------------------------------------------------------------------
302 -- | Grabs the DynFlags from the Session
303 getSessionDynFlags :: Session -> IO DynFlags
304 getSessionDynFlags s = withSession s (return . hsc_dflags)
306 -- | Updates the DynFlags in a Session
307 setSessionDynFlags :: Session -> DynFlags -> IO ()
308 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
310 -- | Messages during compilation (eg. warnings and progress messages)
311 -- are reported using this callback. By default, these messages are
312 -- printed to stderr.
313 setMsgHandler :: (String -> IO ()) -> IO ()
314 setMsgHandler = ErrUtils.setMsgHandler
316 -- -----------------------------------------------------------------------------
319 -- ToDo: think about relative vs. absolute file paths. And what
320 -- happens when the current directory changes.
322 -- | Sets the targets for this session. Each target may be a module name
323 -- or a filename. The targets correspond to the set of root modules for
324 -- the program\/library. Unloading the current program is achieved by
325 -- setting the current set of targets to be empty, followed by load.
326 setTargets :: Session -> [Target] -> IO ()
327 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
329 -- | returns the current set of targets
330 getTargets :: Session -> IO [Target]
331 getTargets s = withSession s (return . hsc_targets)
333 -- | Add another target
334 addTarget :: Session -> Target -> IO ()
336 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
339 removeTarget :: Session -> TargetId -> IO ()
340 removeTarget s target_id
341 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
343 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
345 -- Attempts to guess what Target a string refers to. This function implements
346 -- the --make/GHCi command-line syntax for filenames:
348 -- - if the string looks like a Haskell source filename, then interpret
350 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
352 -- - otherwise interpret the string as a module name
354 guessTarget :: String -> IO Target
356 | isHaskellSrcFilename file
357 = return (Target (TargetFile file) Nothing)
359 = do exists <- doesFileExist hs_file
360 if exists then return (Target (TargetFile hs_file) Nothing) else do
361 exists <- doesFileExist lhs_file
362 if exists then return (Target (TargetFile lhs_file) Nothing) else do
363 return (Target (TargetModule (mkModule file)) Nothing)
365 hs_file = file ++ ".hs"
366 lhs_file = file ++ ".lhs"
368 -- -----------------------------------------------------------------------------
369 -- Loading the program
371 -- Perform a dependency analysis starting from the current targets
372 -- and update the session with the new module graph.
373 depanal :: Session -> [Module] -> IO ()
374 depanal (Session ref) excluded_mods = do
375 hsc_env <- readIORef ref
377 dflags = hsc_dflags hsc_env
378 gmode = ghcMode (hsc_dflags hsc_env)
379 targets = hsc_targets hsc_env
380 old_graph = hsc_mod_graph hsc_env
382 showPass dflags "Chasing dependencies"
383 when (gmode == BatchCompile) $
384 debugTraceMsg dflags 1 (showSDoc (hcat [
385 text "Chasing modules from: ",
386 hcat (punctuate comma (map pprTarget targets))]))
388 graph <- downsweep hsc_env old_graph excluded_mods
389 writeIORef ref hsc_env{ hsc_mod_graph=graph }
392 -- | The result of load.
394 = LoadOk Errors -- ^ all specified targets were loaded successfully.
395 | LoadFailed Errors -- ^ not all modules were loaded.
397 type Errors = [String]
399 data ErrMsg = ErrMsg {
400 errMsgSeverity :: Severity, -- warning, error, etc.
401 errMsgSpans :: [SrcSpan],
402 errMsgShortDoc :: Doc,
403 errMsgExtraInfo :: Doc
410 | LoadDependenciesOf Module
412 -- | Try to load the program. If a Module is supplied, then just
413 -- attempt to load up to this target. If no Module is supplied,
414 -- then try to load all targets.
415 load :: Session -> LoadHowMuch -> IO SuccessFlag
416 load session how_much =
417 loadMsgs session how_much ErrUtils.printErrorsAndWarnings
419 -- | Version of 'load' that takes a callback function to be invoked
420 -- on compiler errors and warnings as they occur during compilation.
421 loadMsgs :: Session -> LoadHowMuch -> (Messages-> IO ()) -> IO SuccessFlag
422 loadMsgs s@(Session ref) how_much msg_act
424 -- Dependency analysis first. Note that this fixes the module graph:
425 -- even if we don't get a fully successful upsweep, the full module
426 -- graph is still retained in the Session. We can tell which modules
427 -- were successfully loaded by inspecting the Session's HPT.
430 hsc_env <- readIORef ref
432 let hpt1 = hsc_HPT hsc_env
433 let dflags = hsc_dflags hsc_env
434 let mod_graph = hsc_mod_graph hsc_env
436 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
437 let verb = verbosity dflags
439 -- The "bad" boot modules are the ones for which we have
440 -- B.hs-boot in the module graph, but no B.hs
441 -- The downsweep should have ensured this does not happen
443 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
444 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
445 not (ms_mod s `elem` all_home_mods)]
446 ASSERT( null bad_boot_mods ) return ()
448 -- mg2_with_srcimps drops the hi-boot nodes, returning a
449 -- graph with cycles. Among other things, it is used for
450 -- backing out partially complete cycles following a failed
451 -- upsweep, and for removing from hpt all the modules
452 -- not in strict downwards closure, during calls to compile.
453 let mg2_with_srcimps :: [SCC ModSummary]
454 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
456 -- check the stability property for each module.
457 stable_mods@(stable_obj,stable_bco)
458 | BatchCompile <- ghci_mode = ([],[])
459 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
461 -- prune bits of the HPT which are definitely redundant now,
463 pruned_hpt = pruneHomePackageTable hpt1
464 (flattenSCCs mg2_with_srcimps)
469 debugTraceMsg dflags 2 (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
470 text "Stable BCO:" <+> ppr stable_bco))
472 -- Unload any modules which are going to be re-linked this time around.
473 let stable_linkables = [ linkable
474 | m <- stable_obj++stable_bco,
475 Just hmi <- [lookupModuleEnv pruned_hpt m],
476 Just linkable <- [hm_linkable hmi] ]
477 unload hsc_env stable_linkables
479 -- We could at this point detect cycles which aren't broken by
480 -- a source-import, and complain immediately, but it seems better
481 -- to let upsweep_mods do this, so at least some useful work gets
482 -- done before the upsweep is abandoned.
483 --hPutStrLn stderr "after tsort:\n"
484 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
486 -- Now do the upsweep, calling compile for each module in
487 -- turn. Final result is version 3 of everything.
489 -- Topologically sort the module graph, this time including hi-boot
490 -- nodes, and possibly just including the portion of the graph
491 -- reachable from the module specified in the 2nd argument to load.
492 -- This graph should be cycle-free.
493 -- If we're restricting the upsweep to a portion of the graph, we
494 -- also want to retain everything that is still stable.
495 let full_mg :: [SCC ModSummary]
496 full_mg = topSortModuleGraph False mod_graph Nothing
498 maybe_top_mod = case how_much of
500 LoadDependenciesOf m -> Just m
503 partial_mg0 :: [SCC ModSummary]
504 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
506 -- LoadDependenciesOf m: we want the upsweep to stop just
507 -- short of the specified module (unless the specified module
510 | LoadDependenciesOf mod <- how_much
511 = ASSERT( case last partial_mg0 of
512 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
513 List.init partial_mg0
519 | AcyclicSCC ms <- full_mg,
520 ms_mod ms `elem` stable_obj++stable_bco,
521 ms_mod ms `notElem` [ ms_mod ms' |
522 AcyclicSCC ms' <- partial_mg ] ]
524 mg = stable_mg ++ partial_mg
526 -- clean up between compilations
527 let cleanup = cleanTempFilesExcept dflags
528 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
530 (upsweep_ok, hsc_env1, modsUpswept)
531 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
532 pruned_hpt stable_mods cleanup msg_act mg
534 -- Make modsDone be the summaries for each home module now
535 -- available; this should equal the domain of hpt3.
536 -- Get in in a roughly top .. bottom order (hence reverse).
538 let modsDone = reverse modsUpswept
540 -- Try and do linking in some form, depending on whether the
541 -- upsweep was completely or only partially successful.
543 if succeeded upsweep_ok
546 -- Easy; just relink it all.
547 do debugTraceMsg dflags 2 "Upsweep completely successful."
549 -- Clean up after ourselves
550 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
552 -- Issue a warning for the confusing case where the user
553 -- said '-o foo' but we're not going to do any linking.
554 -- We attempt linking if either (a) one of the modules is
555 -- called Main, or (b) the user said -no-hs-main, indicating
556 -- that main() is going to come from somewhere else.
558 let ofile = outputFile dflags
559 let no_hs_main = dopt Opt_NoHsMain dflags
560 let mb_main_mod = mainModIs dflags
562 main_mod = mb_main_mod `orElse` "Main"
564 = any ((==main_mod).moduleUserString.ms_mod)
566 do_linking = a_root_is_Main || no_hs_main
568 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
569 debugTraceMsg dflags 1 ("Warning: output was redirected with -o, " ++
570 "but no output will be generated\n" ++
571 "because there is no " ++ main_mod ++ " module.")
573 -- link everything together
574 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
576 loadFinish Succeeded linkresult ref hsc_env1
579 -- Tricky. We need to back out the effects of compiling any
580 -- half-done cycles, both so as to clean up the top level envs
581 -- and to avoid telling the interactive linker to link them.
582 do debugTraceMsg dflags 2 "Upsweep partially successful."
585 = map ms_mod modsDone
586 let mods_to_zap_names
587 = findPartiallyCompletedCycles modsDone_names
590 = filter ((`notElem` mods_to_zap_names).ms_mod)
593 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
596 -- Clean up after ourselves
597 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
599 -- there should be no Nothings where linkables should be, now
600 ASSERT(all (isJust.hm_linkable)
601 (moduleEnvElts (hsc_HPT hsc_env))) do
603 -- Link everything together
604 linkresult <- link ghci_mode dflags False hpt4
606 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
607 loadFinish Failed linkresult ref hsc_env4
609 -- Finish up after a load.
611 -- If the link failed, unload everything and return.
612 loadFinish all_ok Failed ref hsc_env
613 = do unload hsc_env []
614 writeIORef ref $! discardProg hsc_env
617 -- Empty the interactive context and set the module context to the topmost
618 -- newly loaded module, or the Prelude if none were loaded.
619 loadFinish all_ok Succeeded ref hsc_env
620 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
624 -- Forget the current program, but retain the persistent info in HscEnv
625 discardProg :: HscEnv -> HscEnv
627 = hsc_env { hsc_mod_graph = emptyMG,
628 hsc_IC = emptyInteractiveContext,
629 hsc_HPT = emptyHomePackageTable }
631 -- used to fish out the preprocess output files for the purposes of
632 -- cleaning up. The preprocessed file *might* be the same as the
633 -- source file, but that doesn't do any harm.
634 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
636 -- -----------------------------------------------------------------------------
640 CheckedModule { parsedSource :: ParsedSource,
641 renamedSource :: Maybe RenamedSource,
642 typecheckedSource :: Maybe TypecheckedSource,
643 checkedModuleInfo :: Maybe ModuleInfo
646 type ParsedSource = Located (HsModule RdrName)
647 type RenamedSource = HsGroup Name
648 type TypecheckedSource = LHsBinds Id
650 -- | This is the way to get access to parsed and typechecked source code
651 -- for a module. 'checkModule' loads all the dependencies of the specified
652 -- module in the Session, and then attempts to typecheck the module. If
653 -- successful, it returns the abstract syntax for the module.
654 checkModule :: Session -> Module -> (Messages -> IO ())
655 -> IO (Maybe CheckedModule)
656 checkModule session@(Session ref) mod msg_act = do
657 -- load up the dependencies first
658 r <- loadMsgs session (LoadDependenciesOf mod) msg_act
659 if (failed r) then return Nothing else do
661 -- now parse & typecheck the module
662 hsc_env <- readIORef ref
663 let mg = hsc_mod_graph hsc_env
664 case [ ms | ms <- mg, ms_mod ms == mod ] of
667 -- Add in the OPTIONS from the source file This is nasty:
668 -- we've done this once already, in the compilation manager
669 -- It might be better to cache the flags in the
670 -- ml_hspp_file field, say
671 let dflags0 = hsc_dflags hsc_env
672 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
673 opts = getOptionsFromStringBuffer hspp_buf
674 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
675 if (not (null leftovers))
676 then do let filename = fromJust (ml_hs_file (ms_location ms))
677 msg_act (optionsErrorMsgs leftovers opts filename)
681 r <- hscFileCheck hsc_env{hsc_dflags=dflags1} msg_act ms
685 HscChecked parsed renamed Nothing ->
686 return (Just (CheckedModule {
687 parsedSource = parsed,
688 renamedSource = renamed,
689 typecheckedSource = Nothing,
690 checkedModuleInfo = Nothing }))
691 HscChecked parsed renamed
692 (Just (tc_binds, rdr_env, details)) -> do
693 let minf = ModuleInfo {
694 minf_type_env = md_types details,
695 minf_exports = md_exports details,
696 minf_rdr_env = Just rdr_env
698 return (Just (CheckedModule {
699 parsedSource = parsed,
700 renamedSource = renamed,
701 typecheckedSource = Just tc_binds,
702 checkedModuleInfo = Just minf }))
704 -- ---------------------------------------------------------------------------
707 unload :: HscEnv -> [Linkable] -> IO ()
708 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
709 = case ghcMode (hsc_dflags hsc_env) of
710 BatchCompile -> return ()
711 JustTypecheck -> return ()
713 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
715 Interactive -> panic "unload: no interpreter"
717 other -> panic "unload: strange mode"
719 -- -----------------------------------------------------------------------------
723 Stability tells us which modules definitely do not need to be recompiled.
724 There are two main reasons for having stability:
726 - avoid doing a complete upsweep of the module graph in GHCi when
727 modules near the bottom of the tree have not changed.
729 - to tell GHCi when it can load object code: we can only load object code
730 for a module when we also load object code fo all of the imports of the
731 module. So we need to know that we will definitely not be recompiling
732 any of these modules, and we can use the object code.
734 NB. stability is of no importance to BatchCompile at all, only Interactive.
735 (ToDo: what about JustTypecheck?)
737 The stability check is as follows. Both stableObject and
738 stableBCO are used during the upsweep phase later.
741 stable m = stableObject m || stableBCO m
744 all stableObject (imports m)
745 && old linkable does not exist, or is == on-disk .o
746 && date(on-disk .o) > date(.hs)
749 all stable (imports m)
750 && date(BCO) > date(.hs)
753 These properties embody the following ideas:
755 - if a module is stable:
756 - if it has been compiled in a previous pass (present in HPT)
757 then it does not need to be compiled or re-linked.
758 - if it has not been compiled in a previous pass,
759 then we only need to read its .hi file from disk and
760 link it to produce a ModDetails.
762 - if a modules is not stable, we will definitely be at least
763 re-linking, and possibly re-compiling it during the upsweep.
764 All non-stable modules can (and should) therefore be unlinked
767 - Note that objects are only considered stable if they only depend
768 on other objects. We can't link object code against byte code.
772 :: HomePackageTable -- HPT from last compilation
773 -> [SCC ModSummary] -- current module graph (cyclic)
774 -> [Module] -- all home modules
775 -> ([Module], -- stableObject
776 [Module]) -- stableBCO
778 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
780 checkSCC (stable_obj, stable_bco) scc0
781 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
782 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
783 | otherwise = (stable_obj, stable_bco)
785 scc = flattenSCC scc0
786 scc_mods = map ms_mod scc
787 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
789 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
790 -- all imports outside the current SCC, but in the home pkg
792 stable_obj_imps = map (`elem` stable_obj) scc_allimps
793 stable_bco_imps = map (`elem` stable_bco) scc_allimps
800 and (zipWith (||) stable_obj_imps stable_bco_imps)
804 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
808 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
810 Just hmi | Just l <- hm_linkable hmi
811 -> isObjectLinkable l && t == linkableTime l
812 -- why '>=' rather than '>' above? If the filesystem stores
813 -- times to the nearset second, we may occasionally find that
814 -- the object & source have the same modification time,
815 -- especially if the source was automatically generated
816 -- and compiled. Using >= is slightly unsafe, but it matches
820 = case lookupModuleEnv hpt (ms_mod ms) of
822 Just hmi | Just l <- hm_linkable hmi ->
823 not (isObjectLinkable l) &&
824 linkableTime l >= ms_hs_date ms
826 ms_allimps :: ModSummary -> [Module]
827 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
829 -- -----------------------------------------------------------------------------
830 -- Prune the HomePackageTable
832 -- Before doing an upsweep, we can throw away:
834 -- - For non-stable modules:
835 -- - all ModDetails, all linked code
836 -- - all unlinked code that is out of date with respect to
839 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
840 -- space at the end of the upsweep, because the topmost ModDetails of the
841 -- old HPT holds on to the entire type environment from the previous
844 pruneHomePackageTable
847 -> ([Module],[Module])
850 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
851 = mapModuleEnv prune hpt
853 | is_stable modl = hmi'
854 | otherwise = hmi'{ hm_details = emptyModDetails }
856 modl = mi_module (hm_iface hmi)
857 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
858 = hmi{ hm_linkable = Nothing }
861 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
863 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
865 is_stable m = m `elem` stable_obj || m `elem` stable_bco
867 -- -----------------------------------------------------------------------------
869 -- Return (names of) all those in modsDone who are part of a cycle
870 -- as defined by theGraph.
871 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
872 findPartiallyCompletedCycles modsDone theGraph
876 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
877 chew ((CyclicSCC vs):rest)
878 = let names_in_this_cycle = nub (map ms_mod vs)
880 = nub ([done | done <- modsDone,
881 done `elem` names_in_this_cycle])
882 chewed_rest = chew rest
884 if notNull mods_in_this_cycle
885 && length mods_in_this_cycle < length names_in_this_cycle
886 then mods_in_this_cycle ++ chewed_rest
889 -- -----------------------------------------------------------------------------
892 -- This is where we compile each module in the module graph, in a pass
893 -- from the bottom to the top of the graph.
895 -- There better had not be any cyclic groups here -- we check for them.
898 :: HscEnv -- Includes initially-empty HPT
899 -> HomePackageTable -- HPT from last time round (pruned)
900 -> ([Module],[Module]) -- stable modules (see checkStability)
901 -> IO () -- How to clean up unwanted tmp files
902 -> (Messages -> IO ()) -- Compiler error message callback
903 -> [SCC ModSummary] -- Mods to do (the worklist)
905 HscEnv, -- With an updated HPT
906 [ModSummary]) -- Mods which succeeded
908 upsweep hsc_env old_hpt stable_mods cleanup msg_act mods
909 = upsweep' hsc_env old_hpt stable_mods cleanup msg_act mods 1 (length mods)
911 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
913 = return (Succeeded, hsc_env, [])
915 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
917 = do putMsg (showSDoc (cyclicModuleErr ms))
918 return (Failed, hsc_env, [])
920 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
921 (AcyclicSCC mod:mods) mod_index nmods
922 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
923 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
924 -- (moduleEnvElts (hsc_HPT hsc_env)))
926 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods msg_act mod
929 cleanup -- Remove unwanted tmp files between compilations
932 Nothing -> return (Failed, hsc_env, [])
934 { let this_mod = ms_mod mod
936 -- Add new info to hsc_env
937 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
939 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
941 -- Space-saving: delete the old HPT entry
942 -- for mod BUT if mod is a hs-boot
943 -- node, don't delete it. For the
944 -- interface, the HPT entry is probaby for the
945 -- main Haskell source file. Deleting it
946 -- would force .. (what?? --SDM)
947 old_hpt1 | isBootSummary mod = old_hpt
948 | otherwise = delModuleEnv old_hpt this_mod
950 ; (restOK, hsc_env2, modOKs)
951 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
952 msg_act mods (mod_index+1) nmods
953 ; return (restOK, hsc_env2, mod:modOKs)
957 -- Compile a single module. Always produce a Linkable for it if
958 -- successful. If no compilation happened, return the old Linkable.
959 upsweep_mod :: HscEnv
961 -> ([Module],[Module])
962 -> (Messages -> IO ())
964 -> Int -- index of module
965 -> Int -- total number of modules
966 -> IO (Maybe HomeModInfo) -- Nothing => Failed
968 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) msg_act summary mod_index nmods
971 this_mod = ms_mod summary
972 mb_obj_date = ms_obj_date summary
973 obj_fn = ml_obj_file (ms_location summary)
974 hs_date = ms_hs_date summary
976 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
977 compile_it = upsweep_compile hsc_env old_hpt this_mod
978 msg_act summary mod_index nmods
980 case ghcMode (hsc_dflags hsc_env) of
983 -- Batch-compilating is easy: just check whether we have
984 -- an up-to-date object file. If we do, then the compiler
985 -- needs to do a recompilation check.
986 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
988 findObjectLinkable this_mod obj_fn obj_date
989 compile_it (Just linkable)
996 _ | is_stable_obj, isJust old_hmi ->
998 -- object is stable, and we have an entry in the
999 -- old HPT: nothing to do
1001 | is_stable_obj, isNothing old_hmi -> do
1003 findObjectLinkable this_mod obj_fn
1004 (expectJust "upseep1" mb_obj_date)
1005 compile_it (Just linkable)
1006 -- object is stable, but we need to load the interface
1007 -- off disk to make a HMI.
1010 ASSERT(isJust old_hmi) -- must be in the old_hpt
1012 -- BCO is stable: nothing to do
1014 | Just hmi <- old_hmi,
1015 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1016 linkableTime l >= ms_hs_date summary ->
1018 -- we have an old BCO that is up to date with respect
1019 -- to the source: do a recompilation check as normal.
1023 -- no existing code at all: we must recompile.
1025 is_stable_obj = this_mod `elem` stable_obj
1026 is_stable_bco = this_mod `elem` stable_bco
1028 old_hmi = lookupModuleEnv old_hpt this_mod
1030 -- Run hsc to compile a module
1031 upsweep_compile hsc_env old_hpt this_mod msg_act summary
1033 mb_old_linkable = do
1035 -- The old interface is ok if it's in the old HPT
1036 -- a) we're compiling a source file, and the old HPT
1037 -- entry is for a source file
1038 -- b) we're compiling a hs-boot file
1039 -- Case (b) allows an hs-boot file to get the interface of its
1040 -- real source file on the second iteration of the compilation
1041 -- manager, but that does no harm. Otherwise the hs-boot file
1042 -- will always be recompiled
1045 = case lookupModuleEnv old_hpt this_mod of
1047 Just hm_info | isBootSummary summary -> Just iface
1048 | not (mi_boot iface) -> Just iface
1049 | otherwise -> Nothing
1051 iface = hm_iface hm_info
1053 compresult <- compile hsc_env msg_act summary mb_old_linkable mb_old_iface
1057 -- Compilation failed. Compile may still have updated the PCS, tho.
1058 CompErrs -> return Nothing
1060 -- Compilation "succeeded", and may or may not have returned a new
1061 -- linkable (depending on whether compilation was actually performed
1063 CompOK new_details new_iface new_linkable
1064 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1065 hm_details = new_details,
1066 hm_linkable = new_linkable }
1067 return (Just new_info)
1070 -- Filter modules in the HPT
1071 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1072 retainInTopLevelEnvs keep_these hpt
1073 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1075 , let mb_mod_info = lookupModuleEnv hpt mod
1076 , isJust mb_mod_info ]
1078 -- ---------------------------------------------------------------------------
1079 -- Topological sort of the module graph
1082 :: Bool -- Drop hi-boot nodes? (see below)
1086 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1087 -- The resulting list of strongly-connected-components is in topologically
1088 -- sorted order, starting with the module(s) at the bottom of the
1089 -- dependency graph (ie compile them first) and ending with the ones at
1092 -- Drop hi-boot nodes (first boolean arg)?
1094 -- False: treat the hi-boot summaries as nodes of the graph,
1095 -- so the graph must be acyclic
1097 -- True: eliminate the hi-boot nodes, and instead pretend
1098 -- the a source-import of Foo is an import of Foo
1099 -- The resulting graph has no hi-boot nodes, but can by cyclic
1101 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1102 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1103 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1104 = stronglyConnComp (map vertex_fn (reachable graph root))
1106 -- restrict the graph to just those modules reachable from
1107 -- the specified module. We do this by building a graph with
1108 -- the full set of nodes, and determining the reachable set from
1109 -- the specified node.
1110 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1111 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1113 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1114 | otherwise = throwDyn (ProgramError "module does not exist")
1116 moduleGraphNodes :: Bool -> [ModSummary]
1117 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1118 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1120 -- Drop hs-boot nodes by using HsSrcFile as the key
1121 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1122 | otherwise = HsBootFile
1124 -- We use integers as the keys for the SCC algorithm
1125 nodes :: [(ModSummary, Int, [Int])]
1126 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1127 out_edge_keys hs_boot_key (ms_srcimps s) ++
1128 out_edge_keys HsSrcFile (ms_imps s) )
1130 , not (isBootSummary s && drop_hs_boot_nodes) ]
1131 -- Drop the hi-boot ones if told to do so
1133 key_map :: NodeMap Int
1134 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1137 lookup_key :: HscSource -> Module -> Maybe Int
1138 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1140 out_edge_keys :: HscSource -> [Module] -> [Int]
1141 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1142 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1143 -- the IsBootInterface parameter True; else False
1146 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1147 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1149 msKey :: ModSummary -> NodeKey
1150 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1152 emptyNodeMap :: NodeMap a
1153 emptyNodeMap = emptyFM
1155 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1156 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1158 nodeMapElts :: NodeMap a -> [a]
1159 nodeMapElts = eltsFM
1161 -- -----------------------------------------------------------------
1162 -- The unlinked image
1164 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1165 -- binaries (byte code or object code). Even when it links bytecode
1166 -- it keeps the unlinked version so it can re-link it later without
1169 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1171 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1172 findModuleLinkable_maybe lis mod
1173 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1176 many -> pprPanic "findModuleLinkable" (ppr mod)
1178 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1179 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1181 -----------------------------------------------------------------------------
1182 -- Downsweep (dependency analysis)
1184 -- Chase downwards from the specified root set, returning summaries
1185 -- for all home modules encountered. Only follow source-import
1188 -- We pass in the previous collection of summaries, which is used as a
1189 -- cache to avoid recalculating a module summary if the source is
1192 -- The returned list of [ModSummary] nodes has one node for each home-package
1193 -- module, plus one for any hs-boot files. The imports of these nodes
1194 -- are all there, including the imports of non-home-package modules.
1197 -> [ModSummary] -- Old summaries
1198 -> [Module] -- Ignore dependencies on these; treat them as
1199 -- if they were package modules
1201 downsweep hsc_env old_summaries excl_mods
1202 = do rootSummaries <- mapM getRootSummary roots
1203 checkDuplicates rootSummaries
1204 loop (concatMap msDeps rootSummaries)
1205 (mkNodeMap rootSummaries)
1207 roots = hsc_targets hsc_env
1209 old_summary_map :: NodeMap ModSummary
1210 old_summary_map = mkNodeMap old_summaries
1212 getRootSummary :: Target -> IO ModSummary
1213 getRootSummary (Target (TargetFile file) maybe_buf)
1214 = do exists <- doesFileExist file
1216 then summariseFile hsc_env old_summaries file maybe_buf
1218 throwDyn (CmdLineError ("can't find file: " ++ file))
1219 getRootSummary (Target (TargetModule modl) maybe_buf)
1220 = do maybe_summary <- summariseModule hsc_env emptyNodeMap Nothing False
1221 modl maybe_buf excl_mods
1222 case maybe_summary of
1223 Nothing -> packageModErr modl
1226 -- In a root module, the filename is allowed to diverge from the module
1227 -- name, so we have to check that there aren't multiple root files
1228 -- defining the same module (otherwise the duplicates will be silently
1229 -- ignored, leading to confusing behaviour).
1230 checkDuplicates :: [ModSummary] -> IO ()
1231 checkDuplicates summaries = mapM_ check summaries
1236 many -> multiRootsErr modl many
1237 where modl = ms_mod summ
1239 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1240 | summ' <- summaries, ms_mod summ' == modl ]
1242 loop :: [(FilePath,Module,IsBootInterface)]
1243 -- Work list: process these modules
1244 -> NodeMap ModSummary
1247 -- The result includes the worklist, except
1248 -- for those mentioned in the visited set
1249 loop [] done = return (nodeMapElts done)
1250 loop ((cur_path, wanted_mod, is_boot) : ss) done
1251 | key `elemFM` done = loop ss done
1252 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1253 (Just cur_path) is_boot
1254 wanted_mod Nothing excl_mods
1256 Nothing -> loop ss done
1257 Just s -> loop (msDeps s ++ ss)
1258 (addToFM done key s) }
1260 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1262 msDeps :: ModSummary -> [(FilePath, -- Importing module
1263 Module, -- Imported module
1264 IsBootInterface)] -- {-# SOURCE #-} import or not
1265 -- (msDeps s) returns the dependencies of the ModSummary s.
1266 -- A wrinkle is that for a {-# SOURCE #-} import we return
1267 -- *both* the hs-boot file
1268 -- *and* the source file
1269 -- as "dependencies". That ensures that the list of all relevant
1270 -- modules always contains B.hs if it contains B.hs-boot.
1271 -- Remember, this pass isn't doing the topological sort. It's
1272 -- just gathering the list of all relevant ModSummaries
1273 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1274 ++ [(f,m,False) | m <- ms_imps s]
1276 f = msHsFilePath s -- Keep the importing module for error reporting
1279 -----------------------------------------------------------------------------
1280 -- Summarising modules
1282 -- We have two types of summarisation:
1284 -- * Summarise a file. This is used for the root module(s) passed to
1285 -- cmLoadModules. The file is read, and used to determine the root
1286 -- module name. The module name may differ from the filename.
1288 -- * Summarise a module. We are given a module name, and must provide
1289 -- a summary. The finder is used to locate the file in which the module
1294 -> [ModSummary] -- old summaries
1295 -> FilePath -- source file name
1296 -> Maybe (StringBuffer,ClockTime)
1299 summariseFile hsc_env old_summaries file maybe_buf
1300 -- we can use a cached summary if one is available and the
1301 -- source file hasn't changed, But we have to look up the summary
1302 -- by source file, rather than module name as we do in summarise.
1303 | Just old_summary <- findSummaryBySourceFile old_summaries file
1305 let location = ms_location old_summary
1307 -- return the cached summary if the source didn't change
1308 src_timestamp <- case maybe_buf of
1309 Just (_,t) -> return t
1310 Nothing -> getModificationTime file
1312 if ms_hs_date old_summary == src_timestamp
1313 then do -- update the object-file timestamp
1314 obj_timestamp <- getObjTimestamp location False
1315 return old_summary{ ms_obj_date = obj_timestamp }
1323 let dflags = hsc_dflags hsc_env
1325 (dflags', hspp_fn, buf)
1326 <- preprocessFile dflags file maybe_buf
1328 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1330 -- Make a ModLocation for this file
1331 location <- mkHomeModLocation dflags mod file
1333 -- Tell the Finder cache where it is, so that subsequent calls
1334 -- to findModule will find it, even if it's not on any search path
1335 addHomeModuleToFinder hsc_env mod location
1337 src_timestamp <- case maybe_buf of
1338 Just (_,t) -> return t
1339 Nothing -> getModificationTime file
1341 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1343 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1344 ms_location = location,
1345 ms_hspp_file = Just hspp_fn,
1346 ms_hspp_buf = Just buf,
1347 ms_srcimps = srcimps, ms_imps = the_imps,
1348 ms_hs_date = src_timestamp,
1349 ms_obj_date = obj_timestamp })
1351 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1352 findSummaryBySourceFile summaries file
1353 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1354 fromJust (ml_hs_file (ms_location ms)) == file ] of
1358 -- Summarise a module, and pick up source and timestamp.
1361 -> NodeMap ModSummary -- Map of old summaries
1362 -> Maybe FilePath -- Importing module (for error messages)
1363 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1364 -> Module -- Imported module to be summarised
1365 -> Maybe (StringBuffer, ClockTime)
1366 -> [Module] -- Modules to exclude
1367 -> IO (Maybe ModSummary) -- Its new summary
1369 summariseModule hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1370 | wanted_mod `elem` excl_mods
1373 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1374 = do -- Find its new timestamp; all the
1375 -- ModSummaries in the old map have valid ml_hs_files
1376 let location = ms_location old_summary
1377 src_fn = expectJust "summariseModule" (ml_hs_file location)
1379 -- return the cached summary if the source didn't change
1380 src_timestamp <- case maybe_buf of
1381 Just (_,t) -> return t
1382 Nothing -> getModificationTime src_fn
1384 if ms_hs_date old_summary == src_timestamp
1385 then do -- update the object-file timestamp
1386 obj_timestamp <- getObjTimestamp location is_boot
1387 return (Just old_summary{ ms_obj_date = obj_timestamp })
1389 -- source changed: re-summarise
1390 new_summary location src_fn maybe_buf src_timestamp
1393 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1396 | not (isHomePackage pkg) -> return Nothing
1397 -- Drop external-pkg
1398 | isJust (ml_hs_file location) -> just_found location
1400 err -> noModError dflags cur_mod wanted_mod err
1403 dflags = hsc_dflags hsc_env
1405 hsc_src = if is_boot then HsBootFile else HsSrcFile
1407 just_found location = do
1408 -- Adjust location to point to the hs-boot source file,
1409 -- hi file, object file, when is_boot says so
1410 let location' | is_boot = addBootSuffixLocn location
1411 | otherwise = location
1412 src_fn = expectJust "summarise2" (ml_hs_file location')
1414 -- Check that it exists
1415 -- It might have been deleted since the Finder last found it
1416 maybe_t <- modificationTimeIfExists src_fn
1418 Nothing -> noHsFileErr cur_mod src_fn
1419 Just t -> new_summary location' src_fn Nothing t
1422 new_summary location src_fn maybe_bug src_timestamp
1424 -- Preprocess the source file and get its imports
1425 -- The dflags' contains the OPTIONS pragmas
1426 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1427 (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1429 when (mod_name /= wanted_mod) $
1430 throwDyn (ProgramError
1431 (showSDoc (text src_fn
1432 <> text ": file name does not match module name"
1433 <+> quotes (ppr mod_name))))
1435 -- Find the object timestamp, and return the summary
1436 obj_timestamp <- getObjTimestamp location is_boot
1438 return (Just ( ModSummary { ms_mod = wanted_mod,
1439 ms_hsc_src = hsc_src,
1440 ms_location = location,
1441 ms_hspp_file = Just hspp_fn,
1442 ms_hspp_buf = Just buf,
1443 ms_srcimps = srcimps,
1445 ms_hs_date = src_timestamp,
1446 ms_obj_date = obj_timestamp }))
1449 getObjTimestamp location is_boot
1450 = if is_boot then return Nothing
1451 else modificationTimeIfExists (ml_obj_file location)
1454 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1455 -> IO (DynFlags, FilePath, StringBuffer)
1456 preprocessFile dflags src_fn Nothing
1458 (dflags', hspp_fn) <- preprocess dflags src_fn
1459 buf <- hGetStringBuffer hspp_fn
1460 return (dflags', hspp_fn, buf)
1462 preprocessFile dflags src_fn (Just (buf, time))
1464 -- case we bypass the preprocessing stage?
1466 local_opts = getOptionsFromStringBuffer buf
1468 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1472 | Unlit _ <- startPhase src_fn = True
1473 -- note: local_opts is only required if there's no Unlit phase
1474 | dopt Opt_Cpp dflags' = True
1475 | dopt Opt_Pp dflags' = True
1478 when needs_preprocessing $
1479 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1481 return (dflags', src_fn, buf)
1484 -----------------------------------------------------------------------------
1486 -----------------------------------------------------------------------------
1488 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1489 -- ToDo: we don't have a proper line number for this error
1490 noModError dflags cur_mod wanted_mod err
1491 = throwDyn $ ProgramError $ showSDoc $
1492 vcat [cantFindError dflags wanted_mod err,
1493 nest 2 (parens (pp_where cur_mod))]
1495 noHsFileErr cur_mod path
1496 = throwDyn $ CmdLineError $ showSDoc $
1497 vcat [text "Can't find" <+> text path,
1498 nest 2 (parens (pp_where cur_mod))]
1500 pp_where Nothing = text "one of the roots of the dependency analysis"
1501 pp_where (Just p) = text "imported from" <+> text p
1504 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1505 quotes (ppr mod) <+>
1506 text "is a package module")))
1508 multiRootsErr mod files
1509 = throwDyn (ProgramError (showSDoc (
1510 text "module" <+> quotes (ppr mod) <+>
1511 text "is defined in multiple files:" <+>
1512 sep (map text files))))
1514 cyclicModuleErr :: [ModSummary] -> SDoc
1516 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1517 2 (vcat (map show_one ms))
1519 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1520 nest 2 $ ptext SLIT("imports:") <+>
1521 (pp_imps HsBootFile (ms_srcimps ms)
1522 $$ pp_imps HsSrcFile (ms_imps ms))]
1523 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1524 pp_imps src mods = fsep (map (show_mod src) mods)
1527 -- | Inform GHC that the working directory has changed. GHC will flush
1528 -- its cache of module locations, since it may no longer be valid.
1529 -- Note: if you change the working directory, you should also unload
1530 -- the current program (set targets to empty, followed by load).
1531 workingDirectoryChanged :: Session -> IO ()
1532 workingDirectoryChanged s = withSession s $ \hsc_env ->
1533 flushFinderCache (hsc_FC hsc_env)
1535 -- -----------------------------------------------------------------------------
1536 -- inspecting the session
1538 -- | Get the module dependency graph.
1539 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1540 getModuleGraph s = withSession s (return . hsc_mod_graph)
1542 isLoaded :: Session -> Module -> IO Bool
1543 isLoaded s m = withSession s $ \hsc_env ->
1544 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1546 getBindings :: Session -> IO [TyThing]
1547 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1549 getPrintUnqual :: Session -> IO PrintUnqualified
1550 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1552 -- | Container for information about a 'Module'.
1553 data ModuleInfo = ModuleInfo {
1554 minf_type_env :: TypeEnv,
1555 minf_exports :: NameSet,
1556 minf_rdr_env :: Maybe GlobalRdrEnv
1558 -- ToDo: this should really contain the ModIface too
1559 -- We don't want HomeModInfo here, because a ModuleInfo applies
1560 -- to package modules too.
1562 -- | Request information about a loaded 'Module'
1563 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1564 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1565 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1568 mb_names <- getModuleExports hsc_env mdl
1570 Nothing -> return Nothing
1572 eps <- readIORef (hsc_EPS hsc_env)
1575 n_list = nameSetToList names
1576 tys = [ ty | name <- n_list,
1577 Just ty <- [lookupTypeEnv pte name] ]
1579 return (Just (ModuleInfo {
1580 minf_type_env = mkTypeEnv tys,
1581 minf_exports = names,
1582 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names mdl
1585 -- bogusly different for non-GHCI (ToDo)
1589 let details = hm_details hmi in
1590 return (Just (ModuleInfo {
1591 minf_type_env = md_types details,
1592 minf_exports = md_exports details,
1593 minf_rdr_env = mi_globals $! hm_iface hmi
1596 -- ToDo: we should be able to call getModuleInfo on a package module,
1597 -- even one that isn't loaded yet.
1599 -- | The list of top-level entities defined in a module
1600 modInfoTyThings :: ModuleInfo -> [TyThing]
1601 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1603 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1604 modInfoTopLevelScope minf
1605 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1607 modInfoExports :: ModuleInfo -> [Name]
1608 modInfoExports minf = nameSetToList $! minf_exports minf
1610 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1611 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1613 isDictonaryId :: Id -> Bool
1615 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1617 -- | Looks up a global name: that is, any top-level name in any
1618 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1619 -- the interactive context, and therefore does not require a preceding
1621 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1622 lookupGlobalName s name = withSession s $ \hsc_env -> do
1623 eps <- readIORef (hsc_EPS hsc_env)
1624 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1630 | BinaryCode FilePath
1632 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1633 -- - typechecked syntax includes extra dictionary translation and
1634 -- AbsBinds which need to be translated back into something closer to
1635 -- the original source.
1638 -- - Data and Typeable instances for HsSyn.
1641 -- - things that aren't in the output of the renamer:
1642 -- - the export list
1646 -- - things that aren't in the output of the typechecker right now:
1647 -- - the export list
1649 -- - type signatures
1650 -- - type/data/newtype declarations
1651 -- - class declarations
1653 -- - extra things in the typechecker's output:
1654 -- - default methods are turned into top-level decls.
1655 -- - dictionary bindings
1657 -- ToDo: check for small transformations that happen to the syntax in
1658 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1660 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1661 -- to get from TyCons, Ids etc. to TH syntax (reify).
1663 -- :browse will use either lm_toplev or inspect lm_interface, depending
1664 -- on whether the module is interpreted or not.
1666 -- This is for reconstructing refactored source code
1667 -- Calls the lexer repeatedly.
1668 -- ToDo: add comment tokens to token stream
1669 getTokenStream :: Session -> Module -> IO [Located Token]
1672 -- -----------------------------------------------------------------------------
1673 -- Interactive evaluation
1677 -- | Set the interactive evaluation context.
1679 -- Setting the context doesn't throw away any bindings; the bindings
1680 -- we've built up in the InteractiveContext simply move to the new
1681 -- module. They always shadow anything in scope in the current context.
1682 setContext :: Session
1683 -> [Module] -- entire top level scope of these modules
1684 -> [Module] -- exports only of these modules
1686 setContext (Session ref) toplevs exports = do
1687 hsc_env <- readIORef ref
1688 let old_ic = hsc_IC hsc_env
1689 hpt = hsc_HPT hsc_env
1691 mapM_ (checkModuleExists hsc_env hpt) exports
1692 export_env <- mkExportEnv hsc_env exports
1693 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1694 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1695 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1696 ic_exports = exports,
1697 ic_rn_gbl_env = all_env } }
1699 -- Make a GlobalRdrEnv based on the exports of the modules only.
1700 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1701 mkExportEnv hsc_env mods = do
1702 mb_name_sets <- mapM (getModuleExports hsc_env) mods
1704 gres = [ nameSetToGlobalRdrEnv name_set mod
1705 | (Just name_set, mod) <- zip mb_name_sets mods ]
1707 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1709 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1710 nameSetToGlobalRdrEnv names mod =
1711 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1712 | name <- nameSetToList names ]
1714 vanillaProv :: Module -> Provenance
1715 -- We're building a GlobalRdrEnv as if the user imported
1716 -- all the specified modules into the global interactive module
1717 vanillaProv mod = Imported [ImportSpec { is_mod = mod, is_as = mod,
1718 is_qual = False, is_explicit = False,
1719 is_loc = srcLocSpan interactiveSrcLoc }]
1721 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1722 checkModuleExists hsc_env hpt mod =
1723 case lookupModuleEnv hpt mod of
1724 Just mod_info -> return ()
1725 _not_a_home_module -> do
1726 res <- findPackageModule hsc_env mod True
1728 Found _ _ -> return ()
1729 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1730 throwDyn (CmdLineError (showSDoc msg))
1732 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1733 mkTopLevEnv hpt modl
1734 = case lookupModuleEnv hpt modl of
1736 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1737 ++ showSDoc (pprModule modl)))
1739 case mi_globals (hm_iface details) of
1741 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1742 ++ showSDoc (pprModule modl)))
1743 Just env -> return env
1745 -- | Get the interactive evaluation context, consisting of a pair of the
1746 -- set of modules from which we take the full top-level scope, and the set
1747 -- of modules from which we take just the exports respectively.
1748 getContext :: Session -> IO ([Module],[Module])
1749 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1750 return (ic_toplev_scope ic, ic_exports ic))
1752 -- | Returns 'True' if the specified module is interpreted, and hence has
1753 -- its full top-level scope available.
1754 moduleIsInterpreted :: Session -> Module -> IO Bool
1755 moduleIsInterpreted s modl = withSession s $ \h ->
1756 case lookupModuleEnv (hsc_HPT h) modl of
1757 Just details -> return (isJust (mi_globals (hm_iface details)))
1758 _not_a_home_module -> return False
1760 -- | Looks up an identifier in the current interactive context (for :info)
1761 {-# DEPRECATED getInfo "we should be using parseName/lookupName instead" #-}
1762 getInfo :: Session -> String -> IO [GetInfoResult]
1763 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1765 -- | Returns all names in scope in the current interactive context
1766 getNamesInScope :: Session -> IO [Name]
1767 getNamesInScope s = withSession s $ \hsc_env -> do
1768 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1770 -- | Parses a string as an identifier, and returns the list of 'Name's that
1771 -- the identifier can refer to in the current interactive context.
1772 parseName :: Session -> String -> IO [Name]
1773 parseName s str = withSession s $ \hsc_env -> do
1774 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1775 case maybe_rdr_name of
1776 Nothing -> return []
1777 Just (L _ rdr_name) -> do
1778 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1780 Nothing -> return []
1781 Just ns -> return ns
1782 -- ToDo: should return error messages
1784 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1785 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1786 lookupName :: Session -> Name -> IO (Maybe TyThing)
1787 lookupName s name = withSession s $ \hsc_env -> do
1788 case lookupTypeEnv (ic_type_env (hsc_IC hsc_env)) name of
1789 Just tt -> return (Just tt)
1791 eps <- readIORef (hsc_EPS hsc_env)
1792 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1794 -- -----------------------------------------------------------------------------
1795 -- Getting the type of an expression
1797 -- | Get the type of an expression
1798 exprType :: Session -> String -> IO (Maybe Type)
1799 exprType s expr = withSession s $ \hsc_env -> do
1800 maybe_stuff <- hscTcExpr hsc_env expr
1802 Nothing -> return Nothing
1803 Just ty -> return (Just tidy_ty)
1805 tidy_ty = tidyType emptyTidyEnv ty
1806 dflags = hsc_dflags hsc_env
1808 -- -----------------------------------------------------------------------------
1809 -- Getting the kind of a type
1811 -- | Get the kind of a type
1812 typeKind :: Session -> String -> IO (Maybe Kind)
1813 typeKind s str = withSession s $ \hsc_env -> do
1814 maybe_stuff <- hscKcType hsc_env str
1816 Nothing -> return Nothing
1817 Just kind -> return (Just kind)
1819 -----------------------------------------------------------------------------
1820 -- cmCompileExpr: compile an expression and deliver an HValue
1822 compileExpr :: Session -> String -> IO (Maybe HValue)
1823 compileExpr s expr = withSession s $ \hsc_env -> do
1824 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1826 Nothing -> return Nothing
1827 Just (new_ic, names, hval) -> do
1829 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1831 case (names,hvals) of
1832 ([n],[hv]) -> return (Just hv)
1833 _ -> panic "compileExpr"
1835 -- -----------------------------------------------------------------------------
1836 -- running a statement interactively
1839 = RunOk [Name] -- ^ names bound by this evaluation
1840 | RunFailed -- ^ statement failed compilation
1841 | RunException Exception -- ^ statement raised an exception
1843 -- | Run a statement in the current interactive context. Statemenet
1844 -- may bind multple values.
1845 runStmt :: Session -> String -> IO RunResult
1846 runStmt (Session ref) expr
1848 hsc_env <- readIORef ref
1850 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1851 -- warnings about the implicit bindings we introduce.
1852 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1853 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1855 maybe_stuff <- hscStmt hsc_env' expr
1858 Nothing -> return RunFailed
1859 Just (new_hsc_env, names, hval) -> do
1861 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1862 either_hvals <- sandboxIO thing_to_run
1864 case either_hvals of
1866 -- on error, keep the *old* interactive context,
1867 -- so that 'it' is not bound to something
1868 -- that doesn't exist.
1869 return (RunException e)
1872 -- Get the newly bound things, and bind them.
1873 -- Don't need to delete any shadowed bindings;
1874 -- the new ones override the old ones.
1875 extendLinkEnv (zip names hvals)
1877 writeIORef ref new_hsc_env
1878 return (RunOk names)
1881 -- We run the statement in a "sandbox" to protect the rest of the
1882 -- system from anything the expression might do. For now, this
1883 -- consists of just wrapping it in an exception handler, but see below
1884 -- for another version.
1886 sandboxIO :: IO a -> IO (Either Exception a)
1887 sandboxIO thing = Exception.try thing
1890 -- This version of sandboxIO runs the expression in a completely new
1891 -- RTS main thread. It is disabled for now because ^C exceptions
1892 -- won't be delivered to the new thread, instead they'll be delivered
1893 -- to the (blocked) GHCi main thread.
1895 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1897 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1898 sandboxIO thing = do
1899 st_thing <- newStablePtr (Exception.try thing)
1900 alloca $ \ p_st_result -> do
1901 stat <- rts_evalStableIO st_thing p_st_result
1902 freeStablePtr st_thing
1904 then do st_result <- peek p_st_result
1905 result <- deRefStablePtr st_result
1906 freeStablePtr st_result
1907 return (Right result)
1909 return (Left (fromIntegral stat))
1911 foreign import "rts_evalStableIO" {- safe -}
1912 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1913 -- more informative than the C type!
1916 -- ---------------------------------------------------------------------------
1917 -- cmBrowseModule: get all the TyThings defined in a module
1919 {-# DEPRECATED browseModule "we should be using getModuleInfo instead" #-}
1920 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1921 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1922 mb_decls <- getModuleContents hsc_env modl exports_only
1924 Nothing -> return [] -- An error of some kind
1925 Just ds -> return ds
1928 -----------------------------------------------------------------------------
1929 -- show a module and it's source/object filenames
1931 showModule :: Session -> ModSummary -> IO String
1932 showModule s mod_summary = withSession s $ \hsc_env -> do
1933 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1934 Nothing -> panic "missing linkable"
1935 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1937 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))