2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
8 ModSummary, -- Abstract
9 ModuleGraph, -- All the modules from the home package
13 cmInit, -- :: GhciMode -> IO CmState
15 cmDepAnal, -- :: CmState -> [FilePath] -> IO ModuleGraph
17 cmLoadModules, -- :: CmState -> ModuleGraph
18 -- -> IO (CmState, Bool, [String])
20 cmUnload, -- :: CmState -> IO CmState
23 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
25 cmSetContext, -- :: CmState -> [String] -> [String] -> IO CmState
26 cmGetContext, -- :: CmState -> IO ([String],[String])
28 cmGetInfo, -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
30 cmBrowseModule, -- :: CmState -> IO [TyThing]
34 cmRunStmt, -- :: CmState -> String -> IO (CmState, CmRunResult)
36 cmTypeOfExpr, -- :: CmState -> String -> IO (CmState, Maybe String)
37 cmKindOfType, -- :: CmState -> String -> IO (CmState, Maybe String)
38 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
41 cmCompileExpr, -- :: CmState -> String -> IO (CmState, Maybe HValue)
42 cmGetModuleGraph, -- :: CmState -> ModuleGraph
46 cmGetBindings, -- :: CmState -> [TyThing]
47 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
52 #include "HsVersions.h"
54 import Packages ( isHomePackage )
55 import DriverPipeline ( CompResult(..), preprocess, compile, link )
56 import HscMain ( newHscEnv )
57 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
61 import PrelNames ( gHC_PRIM )
62 import Module ( Module, mkModule, delModuleEnvList, mkModuleEnv,
63 lookupModuleEnv, moduleEnvElts, extendModuleEnv,
67 import LoadIface ( noIfaceErr )
68 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
69 import ErrUtils ( showPass )
70 import SysTools ( cleanTempFilesExcept )
71 import BasicTypes ( SuccessFlag(..), succeeded, failed )
72 import StringBuffer ( hGetStringBuffer )
76 import CmdLineOpts ( DynFlags(..) )
77 import Maybes ( expectJust, orElse, mapCatMaybes )
80 import DATA_IOREF ( readIORef )
83 import HscMain ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
84 import TcRnDriver ( mkExportEnv, getModuleContents )
85 import IfaceSyn ( IfaceDecl )
86 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
87 import Module ( showModMsg )
91 import Type ( tidyType )
92 import VarEnv ( emptyTidyEnv )
93 import BasicTypes ( Fixity )
94 import Linker ( HValue, unload, extendLinkEnv )
95 import GHC.Exts ( unsafeCoerce# )
97 import SrcLoc ( SrcLoc )
98 import Control.Exception as Exception ( Exception, try )
99 import CmdLineOpts ( DynFlag(..), dopt_unset )
102 import EXCEPTION ( throwDyn )
105 import Directory ( getModificationTime, doesFileExist )
110 import Time ( ClockTime )
114 %************************************************************************
116 The module dependency graph
117 ModSummary, ModGraph, NodeKey, NodeMap
119 %************************************************************************
121 The nodes of the module graph are
122 EITHER a regular Haskell source module
123 OR a hi-boot source module
125 A ModuleGraph contains all the nodes from the home package (only).
126 There will be a node for each source module, plus a node for each hi-boot
130 type ModuleGraph = [ModSummary] -- The module graph,
131 -- NOT NECESSARILY IN TOPOLOGICAL ORDER
133 emptyMG :: ModuleGraph
139 ms_mod :: Module, -- Name of the module
140 ms_boot :: IsBootInterface, -- Whether this is an hi-boot file
141 ms_location :: ModLocation, -- Location
142 ms_srcimps :: [Module], -- Source imports
143 ms_imps :: [Module], -- Non-source imports
144 ms_hs_date :: ClockTime -- Timestamp of summarised file
147 -- The ModLocation contains both the original source filename and the
148 -- filename of the cleaned-up source file after all preprocessing has been
149 -- done. The point is that the summariser will have to cpp/unlit/whatever
150 -- all files anyway, and there's no point in doing this twice -- just
151 -- park the result in a temp file, put the name of it in the location,
152 -- and let @compile@ read from that file on the way back up.
154 instance Outputable ModSummary where
156 = sep [text "ModSummary {",
157 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
158 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
159 text "ms_imps =" <+> ppr (ms_imps ms),
160 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
164 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
167 type NodeKey = (Module, IsBootInterface) -- The nodes of the graph are
168 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod,boot) pairs
170 msKey :: ModSummary -> NodeKey
171 msKey (ModSummary { ms_mod = mod, ms_boot = boot }) = (mod,boot)
173 emptyNodeMap :: NodeMap a
174 emptyNodeMap = emptyFM
176 mkNodeMap :: [(NodeKey,a)] -> NodeMap a
179 nodeMapElts :: NodeMap a -> [a]
184 %************************************************************************
186 The compilation manager state
188 %************************************************************************
192 -- Persistent state for the entire system
195 cm_hsc :: HscEnv, -- Includes the home-package table
196 cm_mg :: ModuleGraph, -- The module graph
197 cm_ic :: InteractiveContext -- Command-line binding info
201 cmGetModuleGraph cmstate = cm_mg cmstate
202 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
203 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
204 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
207 cmInit :: GhciMode -> DynFlags -> IO CmState
208 cmInit ghci_mode dflags
209 = do { hsc_env <- newHscEnv ghci_mode dflags
210 ; return (CmState { cm_hsc = hsc_env,
212 cm_ic = emptyInteractiveContext })}
214 discardCMInfo :: CmState -> CmState
215 -- Forget the compilation manager's state, including the home package table
216 -- but retain the persistent info in HscEnv
217 discardCMInfo cm_state
218 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
219 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
221 -------------------------------------------------------------------
222 -- The unlinked image
224 -- The compilation manager keeps a list of compiled, but as-yet unlinked
225 -- binaries (byte code or object code). Even when it links bytecode
226 -- it keeps the unlinked version so it can re-link it later without
229 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
231 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
232 findModuleLinkable_maybe lis mod
233 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
236 many -> pprPanic "findModuleLinkable" (ppr mod)
240 %************************************************************************
244 %************************************************************************
248 -----------------------------------------------------------------------------
249 -- Setting the context doesn't throw away any bindings; the bindings
250 -- we've built up in the InteractiveContext simply move to the new
251 -- module. They always shadow anything in scope in the current context.
255 -> [String] -- take the top-level scopes of these modules
256 -> [String] -- and the just the exports from these
258 cmSetContext cmstate toplevs exports = do
259 let old_ic = cm_ic cmstate
260 hsc_env = cm_hsc cmstate
261 hpt = hsc_HPT hsc_env
263 export_env <- mkExportEnv hsc_env (map mkModule exports)
264 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
266 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
267 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
268 ic_exports = exports,
269 ic_rn_gbl_env = all_env } }
271 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
273 = case lookupModuleEnv hpt (mkModule mod) of
274 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
275 Just details -> case hm_globals details of
276 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
277 Just env -> return env
279 cmGetContext :: CmState -> IO ([String],[String])
280 cmGetContext CmState{cm_ic=ic} =
281 return (ic_toplev_scope ic, ic_exports ic)
283 cmModuleIsInterpreted :: CmState -> String -> IO Bool
284 cmModuleIsInterpreted cmstate str
285 = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
286 Just details -> return (isJust (hm_globals details))
287 _not_a_home_module -> return False
289 -----------------------------------------------------------------------------
291 cmSetDFlags :: CmState -> DynFlags -> CmState
292 cmSetDFlags cm_state dflags
293 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
295 cmGetDFlags :: CmState -> DynFlags
296 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
298 -----------------------------------------------------------------------------
299 -- cmInfoThing: convert a String to a TyThing
301 -- A string may refer to more than one TyThing (eg. a constructor,
302 -- and type constructor), so we return a list of all the possible TyThings.
304 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
305 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
307 -- ---------------------------------------------------------------------------
308 -- cmBrowseModule: get all the TyThings defined in a module
310 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
311 cmBrowseModule cmstate str exports_only
312 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
313 (mkModule str) exports_only
315 Nothing -> return [] -- An error of some kind
320 -----------------------------------------------------------------------------
321 cmShowModule :: CmState -> ModSummary -> String
322 cmShowModule cmstate mod_summary
323 = case lookupModuleEnv hpt mod of
324 Nothing -> panic "missing linkable"
325 Just mod_info -> showModMsg obj_linkable mod locn
327 obj_linkable = isObjectLinkable (hm_linkable mod_info)
329 hpt = hsc_HPT (cm_hsc cmstate)
330 mod = ms_mod mod_summary
331 locn = ms_location mod_summary
333 -----------------------------------------------------------------------------
334 -- cmRunStmt: Run a statement/expr.
337 = CmRunOk [Name] -- names bound by this evaluation
339 | CmRunException Exception -- statement raised an exception
341 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
342 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
344 -- Turn off -fwarn-unused-bindings when running a statement, to hide
345 -- warnings about the implicit bindings we introduce.
346 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
347 hsc_env' = hsc_env{ hsc_dflags = dflags' }
349 maybe_stuff <- hscStmt hsc_env' icontext expr
352 Nothing -> return (cmstate, CmRunFailed)
353 Just (new_ic, names, hval) -> do
355 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
356 either_hvals <- sandboxIO thing_to_run
360 -- on error, keep the *old* interactive context,
361 -- so that 'it' is not bound to something
362 -- that doesn't exist.
363 return ( cmstate, CmRunException e )
366 -- Get the newly bound things, and bind them.
367 -- Don't need to delete any shadowed bindings;
368 -- the new ones override the old ones.
369 extendLinkEnv (zip names hvals)
371 return (cmstate{ cm_ic=new_ic },
375 -- We run the statement in a "sandbox" to protect the rest of the
376 -- system from anything the expression might do. For now, this
377 -- consists of just wrapping it in an exception handler, but see below
378 -- for another version.
380 sandboxIO :: IO a -> IO (Either Exception a)
381 sandboxIO thing = Exception.try thing
384 -- This version of sandboxIO runs the expression in a completely new
385 -- RTS main thread. It is disabled for now because ^C exceptions
386 -- won't be delivered to the new thread, instead they'll be delivered
387 -- to the (blocked) GHCi main thread.
389 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
391 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
393 st_thing <- newStablePtr (Exception.try thing)
394 alloca $ \ p_st_result -> do
395 stat <- rts_evalStableIO st_thing p_st_result
396 freeStablePtr st_thing
398 then do st_result <- peek p_st_result
399 result <- deRefStablePtr st_result
400 freeStablePtr st_result
401 return (Right result)
403 return (Left (fromIntegral stat))
405 foreign import "rts_evalStableIO" {- safe -}
406 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
407 -- more informative than the C type!
410 -----------------------------------------------------------------------------
411 -- cmTypeOfExpr: returns a string representing the type of an expression
413 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
414 cmTypeOfExpr cmstate expr
415 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
418 Nothing -> return Nothing
419 Just ty -> return (Just res_str)
421 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
422 unqual = icPrintUnqual (cm_ic cmstate)
423 tidy_ty = tidyType emptyTidyEnv ty
426 -----------------------------------------------------------------------------
427 -- cmKindOfType: returns a string representing the kind of a type
429 cmKindOfType :: CmState -> String -> IO (Maybe String)
430 cmKindOfType cmstate str
431 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
433 Nothing -> return Nothing
434 Just kind -> return (Just res_str)
436 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
437 unqual = icPrintUnqual (cm_ic cmstate)
439 -----------------------------------------------------------------------------
440 -- cmTypeOfName: returns a string representing the type of a name.
442 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
443 cmTypeOfName CmState{ cm_ic=ic } name
445 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
446 case lookupNameEnv (ic_type_env ic) name of
447 Nothing -> return Nothing
448 Just (AnId id) -> return (Just str)
450 unqual = icPrintUnqual ic
451 ty = tidyType emptyTidyEnv (idType id)
452 str = showSDocForUser unqual (ppr ty)
454 _ -> panic "cmTypeOfName"
456 -----------------------------------------------------------------------------
457 -- cmCompileExpr: compile an expression and deliver an HValue
459 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
460 cmCompileExpr cmstate expr
463 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
464 ("let __cmCompileExpr = "++expr)
467 Nothing -> return Nothing
468 Just (new_ic, names, hval) -> do
471 hvals <- (unsafeCoerce# hval) :: IO [HValue]
473 case (names,hvals) of
474 ([n],[hv]) -> return (Just hv)
475 _ -> panic "cmCompileExpr"
481 %************************************************************************
483 Loading and unloading
485 %************************************************************************
488 -----------------------------------------------------------------------------
489 -- Unload the compilation manager's state: everything it knows about the
490 -- current collection of modules in the Home package.
492 cmUnload :: CmState -> IO CmState
493 cmUnload state@CmState{ cm_hsc = hsc_env }
494 = do -- Throw away the old home dir cache
497 -- Unload everything the linker knows about
500 -- Start with a fresh CmState, but keep the PersistentCompilerState
501 return (discardCMInfo state)
503 cm_unload hsc_env linkables
504 = case hsc_mode hsc_env of
507 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
509 Interactive -> panic "unload: no interpreter"
513 -----------------------------------------------------------------------------
514 -- Trace dependency graph
516 -- This is a seperate pass so that the caller can back off and keep
517 -- the current state if the downsweep fails. Typically the caller
518 -- might go cmDepAnal
521 -- He wants to do the dependency analysis before the unload, so that
522 -- if the former fails he can use the later
524 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
525 cmDepAnal cmstate rootnames
526 = do showPass dflags "Chasing dependencies"
527 when (verbosity dflags >= 1 && gmode == Batch) $
528 hPutStrLn stderr (showSDoc (hcat [
529 text "Chasing modules from: ",
530 hcat (punctuate comma (map text rootnames))]))
531 downsweep dflags rootnames (cm_mg cmstate)
533 hsc_env = cm_hsc cmstate
534 dflags = hsc_dflags hsc_env
535 gmode = hsc_mode hsc_env
537 -----------------------------------------------------------------------------
538 -- The real business of the compilation manager: given a system state and
539 -- a module name, try and bring the module up to date, probably changing
540 -- the system state at the same time.
542 cmLoadModules :: CmState -- The HPT may not be as up to date
543 -> ModuleGraph -- Bang up to date; but may contain hi-boot no
544 -> IO (CmState, -- new state
545 SuccessFlag, -- was successful
546 [String]) -- list of modules loaded
548 cmLoadModules cmstate1 mg2unsorted
549 = do -- version 1's are the original, before downsweep
550 let hsc_env = cm_hsc cmstate1
551 let hpt1 = hsc_HPT hsc_env
552 let ghci_mode = hsc_mode hsc_env -- this never changes
553 let dflags = hsc_dflags hsc_env -- this never changes
555 -- Do the downsweep to reestablish the module graph
556 let verb = verbosity dflags
558 -- Find out if we have a Main module
559 mb_main_mod <- readIORef v_MainModIs
561 main_mod = mb_main_mod `orElse` "Main"
563 = any ((==main_mod).moduleUserString.ms_mod)
566 let mg2unsorted_names = map ms_mod mg2unsorted
568 -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
569 let mg2 :: [SCC ModSummary]
570 mg2 = topological_sort False mg2unsorted
572 -- mg2_with_srcimps drops the hi-boot nodes, returning a
573 -- graph with cycles. Among other things, it is used for
574 -- backing out partially complete cycles following a failed
575 -- upsweep, and for removing from hpt all the modules
576 -- not in strict downwards closure, during calls to compile.
577 let mg2_with_srcimps :: [SCC ModSummary]
578 mg2_with_srcimps = topological_sort True mg2unsorted
580 -- Sort out which linkables we wish to keep in the unlinked image.
581 -- See getValidLinkables below for details.
582 (valid_old_linkables, new_linkables)
583 <- getValidLinkables ghci_mode (hptLinkables hpt1)
584 mg2unsorted_names mg2_with_srcimps
586 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
588 let hpt2 = delModuleEnvList hpt1 (map linkableModule new_linkables)
589 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
591 -- When (verb >= 2) $
592 -- putStrLn (showSDoc (text "Valid linkables:"
593 -- <+> ppr valid_linkables))
595 -- Figure out a stable set of modules which can be retained
596 -- the top level envs, to avoid upsweeping them. Goes to a
597 -- bit of trouble to avoid upsweeping module cycles.
599 -- Construct a set S of stable modules like this:
600 -- Travel upwards, over the sccified graph. For each scc
601 -- of modules ms, add ms to S only if:
602 -- 1. All home imports of ms are either in ms or S
603 -- 2. A valid old linkable exists for each module in ms
605 -- mg2_with_srcimps has no hi-boot nodes,
606 -- and hence neither does stable_mods
607 stable_summaries <- preUpsweep valid_old_linkables
608 mg2unsorted_names [] mg2_with_srcimps
609 let stable_mods = map ms_mod stable_summaries
610 stable_linkables = filter (\m -> linkableModule m `elem` stable_mods)
614 hPutStrLn stderr (showSDoc (text "Stable modules:"
615 <+> sep (map (text.moduleUserString) stable_mods)))
617 -- Unload any modules which are going to be re-linked this
619 cm_unload hsc_env2 stable_linkables
621 -- we can now glom together our linkable sets
622 let valid_linkables = valid_old_linkables ++ new_linkables
624 -- We could at this point detect cycles which aren't broken by
625 -- a source-import, and complain immediately, but it seems better
626 -- to let upsweep_mods do this, so at least some useful work gets
627 -- done before the upsweep is abandoned.
629 = filter (\scc -> any (`notElem` stable_mods)
630 (map ms_mod (flattenSCC scc)))
633 --hPutStrLn stderr "after tsort:\n"
634 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
636 -- Because we don't take into account source imports when doing
637 -- the topological sort, there shouldn't be any cycles in mg2.
638 -- If there is, we complain and give up -- the user needs to
639 -- break the cycle using a boot file.
641 -- Now do the upsweep, calling compile for each module in
642 -- turn. Final result is version 3 of everything.
644 -- clean up between compilations
645 let cleanup = cleanTempFilesExcept dflags
646 (ppFilesFromSummaries (flattenSCCs mg2))
648 (upsweep_ok, hsc_env3, modsUpswept)
649 <- upsweep_mods hsc_env2 valid_linkables
650 cleanup upsweep_these
652 -- At this point, modsUpswept and newLis should have the same
653 -- length, so there is one new (or old) linkable for each
654 -- mod which was processed (passed to compile).
656 -- Make modsDone be the summaries for each home module now
657 -- available; this should equal the domain of hpt3.
658 -- (NOT STRICTLY TRUE if an interactive session was started
659 -- with some object on disk ???)
660 -- Get in in a roughly top .. bottom order (hence reverse).
662 let modsDone = reverse modsUpswept ++ stable_summaries
664 -- Try and do linking in some form, depending on whether the
665 -- upsweep was completely or only partially successful.
667 if succeeded upsweep_ok
670 -- Easy; just relink it all.
671 do when (verb >= 2) $
672 hPutStrLn stderr "Upsweep completely successful."
674 -- clean up after ourselves
675 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
677 ofile <- readIORef v_Output_file
678 no_hs_main <- readIORef v_NoHsMain
680 -- Issue a warning for the confusing case where the user
681 -- said '-o foo' but we're not going to do any linking.
682 -- We attempt linking if either (a) one of the modules is
683 -- called Main, or (b) the user said -no-hs-main, indicating
684 -- that main() is going to come from somewhere else.
686 let do_linking = a_root_is_Main || no_hs_main
687 when (ghci_mode == Batch && isJust ofile && not do_linking
689 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
691 -- link everything together
692 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
694 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
695 cmLoadFinish Succeeded linkresult cmstate3
698 -- Tricky. We need to back out the effects of compiling any
699 -- half-done cycles, both so as to clean up the top level envs
700 -- and to avoid telling the interactive linker to link them.
701 do when (verb >= 2) $
702 hPutStrLn stderr "Upsweep partially successful."
705 = map ms_mod modsDone
706 let mods_to_zap_names
707 = findPartiallyCompletedCycles modsDone_names
710 = filter ((`notElem` mods_to_zap_names).ms_mod)
713 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
716 -- Clean up after ourselves
717 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
719 -- Link everything together
720 linkresult <- link ghci_mode dflags False hpt4
722 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
723 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
724 cmLoadFinish Failed linkresult cmstate3
727 -- Finish up after a cmLoad.
729 -- If the link failed, unload everything and return.
730 cmLoadFinish ok Failed cmstate
731 = do cm_unload (cm_hsc cmstate) []
732 return (discardCMInfo cmstate, Failed, [])
734 -- Empty the interactive context and set the module context to the topmost
735 -- newly loaded module, or the Prelude if none were loaded.
736 cmLoadFinish ok Succeeded cmstate
737 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
738 mods_loaded = map (moduleUserString.ms_mod)
741 return (new_cmstate, ok, mods_loaded)
743 -- used to fish out the preprocess output files for the purposes of
744 -- cleaning up. The preprocessed file *might* be the same as the
745 -- source file, but that doesn't do any harm.
746 ppFilesFromSummaries summaries
747 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
749 -----------------------------------------------------------------------------
752 -- For each module (or SCC of modules), we take:
754 -- - an on-disk linkable, if this is the first time around and one
757 -- - the old linkable, otherwise (and if one is available).
759 -- and we throw away the linkable if it is older than the source file.
760 -- In interactive mode, we also ignore the on-disk linkables unless
761 -- all of the dependents of this SCC also have on-disk linkables (we
762 -- can't have dynamically loaded objects that depend on interpreted
765 -- If a module has a valid linkable, then it may be STABLE (see below),
766 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
769 -- ToDo: this pass could be merged with the preUpsweep.
773 -> [Linkable] -- old linkables
774 -> [Module] -- all home modules
775 -> [SCC ModSummary] -- all modules in the program, dependency order
776 -> IO ( [Linkable], -- still-valid linkables
777 [Linkable] -- new linkables we just found
780 getValidLinkables mode old_linkables all_home_mods module_graph
781 = do { -- Process the SCCs in bottom-to-top order
782 -- (foldM works left-to-right)
783 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
785 ; return (partition_it ls [] []) }
787 partition_it [] valid new = (valid,new)
788 partition_it ((l,b):ls) valid new
789 | b = partition_it ls valid (l:new)
790 | otherwise = partition_it ls (l:valid) new
795 -> [Linkable] -- old linkables
796 -> [Module] -- all home modules
799 -> IO [(Linkable,Bool)]
801 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
803 scc = flattenSCC scc0
804 scc_names = map ms_mod scc
805 home_module m = m `elem` all_home_mods && m `notElem` scc_names
806 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
807 -- NB. ms_imps, not ms_allimps above. We don't want to
808 -- force a module's SOURCE imports to be already compiled for
809 -- its object linkable to be valid.
811 -- The new_linkables is only the *valid* linkables below here
812 has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
814 Just l -> isObjectLinkable l
816 objects_allowed = mode == Batch || all has_object scc_allhomeimps
820 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
822 -- since an scc can contain only all objects or no objects at all,
823 -- we have to check whether we got all objects or not, and re-do
824 -- the linkable check if not.
827 && not (all isObjectLinkable (map fst new_linkables'))
828 then foldM (getValidLinkable old_linkables False) [] scc
829 else return new_linkables'
831 return (new_linkables ++ new_linkables')
834 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
835 -> IO [(Linkable,Bool)]
836 -- True <=> linkable is new; i.e. freshly discovered on the disk
837 -- presumably generated 'on the side'
838 -- by a separate GHC run
839 getValidLinkable old_linkables objects_allowed new_linkables summary
840 -- 'objects_allowed' says whether we permit this module to
841 -- have a .o-file linkable. We only permit it if all the
842 -- modules it depends on also have .o files; a .o file can't
843 -- link to a bytecode module
844 = do let mod_name = ms_mod summary
847 <- if (not objects_allowed)
850 else findLinkable mod_name (ms_location summary)
852 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
855 case (old_linkable, maybe_disk_linkable) of
856 (Nothing, Nothing) -> []
858 -- new object linkable just appeared
859 (Nothing, Just l) -> up_to_date l True
862 | isObjectLinkable l -> []
863 -- object linkable disappeared! In case we need to
864 -- relink the module, disregard the old linkable and
865 -- just interpret the module from now on.
866 | otherwise -> up_to_date l False
867 -- old byte code linkable
870 | not (isObjectLinkable l) -> up_to_date l False
871 -- if the previous linkable was interpreted, then we
872 -- ignore a newly compiled version, because the version
873 -- numbers in the interface file will be out-of-sync with
874 -- our internal ones.
875 | linkableTime l' > linkableTime l -> up_to_date l' True
876 | linkableTime l' == linkableTime l -> up_to_date l False
878 -- on-disk linkable has been replaced by an older one!
879 -- again, disregard the previous one.
882 | linkableTime l < ms_hs_date summary = []
883 | otherwise = [(l,b)]
884 -- why '<' rather than '<=' above? If the filesystem stores
885 -- times to the nearset second, we may occasionally find that
886 -- the object & source have the same modification time,
887 -- especially if the source was automatically generated
888 -- and compiled. Using >= is slightly unsafe, but it matches
891 return (new_linkables' ++ new_linkables)
894 hptLinkables :: HomePackageTable -> [Linkable]
895 -- Get all the linkables from the home package table, one for each module
896 -- Once the HPT is up to date, these are the ones we should link
897 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
900 -----------------------------------------------------------------------------
901 -- Do a pre-upsweep without use of "compile", to establish a
902 -- (downward-closed) set of stable modules for which we won't call compile.
905 -- * has a valid linkable (see getValidLinkables above)
906 -- * depends only on stable modules
907 -- * has an interface in the HPT (interactive mode only)
909 preUpsweep :: [Linkable] -- new valid linkables
910 -> [Module] -- names of all mods encountered in downsweep
911 -> [ModSummary] -- accumulating stable modules
912 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
913 -> IO [ModSummary] -- stable modules
915 preUpsweep valid_lis all_home_mods stable [] = return stable
916 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
917 = do let scc = flattenSCC scc0
918 scc_allhomeimps :: [Module]
920 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
921 all_imports_in_scc_or_stable
922 = all in_stable_or_scc scc_allhomeimps
923 scc_mods = map ms_mod scc
924 stable_names = scc_mods ++ map ms_mod stable
925 in_stable_or_scc m = m `elem` stable_names
927 -- now we check for valid linkables: each module in the SCC must
928 -- have a valid linkable (see getValidLinkables above).
929 has_valid_linkable scc_mod
930 = isJust (findModuleLinkable_maybe valid_lis scc_mod)
932 scc_is_stable = all_imports_in_scc_or_stable
933 && all has_valid_linkable scc_mods
936 then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
937 else preUpsweep valid_lis all_home_mods stable sccs
940 -- Return (names of) all those in modsDone who are part of a cycle
941 -- as defined by theGraph.
942 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
943 findPartiallyCompletedCycles modsDone theGraph
947 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
948 chew ((CyclicSCC vs):rest)
949 = let names_in_this_cycle = nub (map ms_mod vs)
951 = nub ([done | done <- modsDone,
952 done `elem` names_in_this_cycle])
953 chewed_rest = chew rest
955 if notNull mods_in_this_cycle
956 && length mods_in_this_cycle < length names_in_this_cycle
957 then mods_in_this_cycle ++ chewed_rest
961 -- Compile multiple modules, stopping as soon as an error appears.
962 -- There better had not be any cyclic groups here -- we check for them.
963 upsweep_mods :: HscEnv -- Includes up-to-date HPT
964 -> [Linkable] -- Valid linkables
965 -> IO () -- how to clean up unwanted tmp files
966 -> [SCC ModSummary] -- mods to do (the worklist)
967 -- ...... RETURNING ......
969 HscEnv, -- With an updated HPT
970 [ModSummary]) -- Mods which succeeded
972 upsweep_mods hsc_env oldUI cleanup
974 = return (Succeeded, hsc_env, [])
976 upsweep_mods hsc_env oldUI cleanup
978 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
979 unwords (map (moduleUserString.ms_mod) ms))
980 return (Failed, hsc_env, [])
982 upsweep_mods hsc_env oldUI cleanup
983 (AcyclicSCC mod:mods)
984 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
985 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
986 -- (moduleEnvElts (hsc_HPT hsc_env)))
988 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
990 cleanup -- Remove unwanted tmp files between compilations
992 if failed ok_flag then
993 return (Failed, hsc_env1, [])
995 (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI cleanup mods
996 return (restOK, hsc_env2, mod:modOKs)
999 -- Compile a single module. Always produce a Linkable for it if
1000 -- successful. If no compilation happened, return the old Linkable.
1001 upsweep_mod :: HscEnv
1005 HscEnv) -- With updated HPT
1007 upsweep_mod hsc_env oldUI summary1
1008 | ms_boot summary1 -- The summary describes an hi-boot file,
1009 = -- so there is nothing to do
1010 return (Succeeded, hsc_env)
1012 | otherwise -- The summary describes a regular source file, so compile it
1014 let this_mod = ms_mod summary1
1015 location = ms_location summary1
1016 hpt1 = hsc_HPT hsc_env
1018 let mb_old_iface = case lookupModuleEnv hpt1 this_mod of
1019 Just mod_info -> Just (hm_iface mod_info)
1022 let maybe_old_linkable = findModuleLinkable_maybe oldUI this_mod
1023 source_unchanged = isJust maybe_old_linkable
1025 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1028 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1031 compresult <- compile hsc_env this_mod location
1032 (ms_hs_date summary1)
1033 source_unchanged have_object mb_old_iface
1037 -- Compilation "succeeded", and may or may not have returned a new
1038 -- linkable (depending on whether compilation was actually performed
1040 CompOK new_details new_globals new_iface maybe_new_linkable
1042 new_linkable = maybe_new_linkable `orElse` old_linkable
1043 new_info = HomeModInfo { hm_iface = new_iface,
1044 hm_globals = new_globals,
1045 hm_details = new_details,
1046 hm_linkable = new_linkable }
1047 hpt2 = extendModuleEnv hpt1 this_mod new_info
1049 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
1051 -- Compilation failed. Compile may still have updated the PCS, tho.
1052 CompErrs -> return (Failed, hsc_env)
1054 -- Filter modules in the HPT
1055 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1056 retainInTopLevelEnvs keep_these hpt
1057 = mkModuleEnv [ (mod, fromJust mb_mod_info)
1059 , let mb_mod_info = lookupModuleEnv hpt mod
1060 , isJust mb_mod_info ]
1062 -----------------------------------------------------------------------------
1063 topological_sort :: Bool -- Drop hi-boot nodes? (see below)
1066 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1068 -- Drop hi-boot nodes (first boolean arg)?
1070 -- False: treat the hi-boot summaries as nodes of the graph,
1071 -- so the graph must be acyclic
1073 -- True: eliminate the hi-boot nodes, and instead pretend
1074 -- the a source-import of Foo is an import of Foo
1075 -- The resulting graph has no hi-boot nodes, but can by cyclic
1077 topological_sort drop_hi_boot_nodes summaries
1078 = stronglyConnComp nodes
1080 keep_hi_boot_nodes = not drop_hi_boot_nodes
1082 -- We use integers as the keys for the SCC algorithm
1083 nodes :: [(ModSummary, Int, [Int])]
1084 nodes = [(s, fromJust (lookup_key (ms_boot s) (ms_mod s)),
1085 out_edge_keys keep_hi_boot_nodes (ms_srcimps s) ++
1086 out_edge_keys False (ms_imps s) )
1088 , not (ms_boot s) || keep_hi_boot_nodes ]
1089 -- Drop the hi-boot ones if told to do so
1091 key_map :: NodeMap Int
1092 key_map = listToFM ([(ms_mod s, ms_boot s) | s <- summaries]
1095 lookup_key :: IsBootInterface -> Module -> Maybe Int
1096 lookup_key hi_boot mod = lookupFM key_map (mod, hi_boot)
1098 out_edge_keys :: IsBootInterface -> [Module] -> [Int]
1099 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1100 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1101 -- the IsBootInterface parameter True; else False
1104 -----------------------------------------------------------------------------
1105 -- Downsweep (dependency analysis)
1107 -- Chase downwards from the specified root set, returning summaries
1108 -- for all home modules encountered. Only follow source-import
1111 -- We pass in the previous collection of summaries, which is used as a
1112 -- cache to avoid recalculating a module summary if the source is
1115 downsweep :: DynFlags -> [FilePath] -> [ModSummary] -> IO [ModSummary]
1116 downsweep dflags roots old_summaries
1117 = do rootSummaries <- mapM getRootSummary roots
1118 checkDuplicates rootSummaries
1119 loop rootSummaries emptyNodeMap
1121 old_summary_map :: NodeMap ModSummary
1122 old_summary_map = mkNodeMap [ (msKey s, s) | s <- old_summaries]
1124 getRootSummary :: FilePath -> IO ModSummary
1126 | isHaskellSrcFilename file
1127 = do exists <- doesFileExist file
1128 if exists then summariseFile dflags file else do
1129 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1131 = do exists <- doesFileExist hs_file
1132 if exists then summariseFile dflags hs_file else do
1133 exists <- doesFileExist lhs_file
1134 if exists then summariseFile dflags lhs_file else do
1135 let mod_name = mkModule file
1136 maybe_summary <- getSummary file False {- Not hi-boot -} mod_name
1137 case maybe_summary of
1138 Nothing -> packageModErr mod_name
1141 hs_file = file ++ ".hs"
1142 lhs_file = file ++ ".lhs"
1144 -- In a root module, the filename is allowed to diverge from the module
1145 -- name, so we have to check that there aren't multiple root files
1146 -- defining the same module (otherwise the duplicates will be silently
1147 -- ignored, leading to confusing behaviour).
1148 checkDuplicates :: [ModSummary] -> IO ()
1149 checkDuplicates summaries = mapM_ check summaries
1154 many -> multiRootsErr modl many
1155 where modl = ms_mod summ
1157 [ fromJust (ml_hs_file (ms_location summ'))
1158 | summ' <- summaries, ms_mod summ' == modl ]
1160 loop :: [ModSummary] -- Work list: process the imports of these modules
1161 -> NodeMap ModSummary -- Visited set
1162 -> IO [ModSummary] -- The result includes the worklist, except
1163 -- for those mentioned in the visited set
1164 loop [] done = return (nodeMapElts done)
1165 loop (s:ss) done | key `elemFM` done = loop ss done
1166 | otherwise = do { new_ss <- children s
1167 ; loop (new_ss ++ ss) (addToFM done key s) }
1169 key = (ms_mod s, ms_boot s)
1171 children :: ModSummary -> IO [ModSummary]
1172 children s = do { mb_kids1 <- mapM (getSummary cur_path True) (ms_srcimps s)
1173 ; mb_kids2 <- mapM (getSummary cur_path False) (ms_imps s)
1174 ; return (catMaybes mb_kids1 ++ catMaybes mb_kids2) }
1175 -- The Nothings are the ones from other packages: ignore
1177 cur_path = fromJust (ml_hs_file (ms_location s))
1179 getSummary :: FilePath -- Import directive is in here [only used for err msg]
1180 -> IsBootInterface -- Look for an hi-boot file?
1181 -> Module -- Look for this module
1182 -> IO (Maybe ModSummary)
1183 getSummary cur_mod is_boot wanted_mod
1184 = do found <- findModule dflags wanted_mod True {-explicit-}
1187 | isHomePackage pkg -- Drop an external-package modules
1188 -> do { let old_summary = lookupFM old_summary_map (wanted_mod, is_boot)
1189 ; summarise dflags wanted_mod is_boot location old_summary }
1191 -> return Nothing -- External package module
1193 err -> throwDyn (noModError dflags cur_mod wanted_mod err)
1196 -- ToDo: we don't have a proper line number for this error
1197 noModError dflags loc mod_nm err
1198 = ProgramError (showSDoc (hang (text loc <> colon) 4 $
1199 noIfaceErr dflags mod_nm err))
1201 -----------------------------------------------------------------------------
1202 -- Summarising modules
1204 -- We have two types of summarisation:
1206 -- * Summarise a file. This is used for the root module(s) passed to
1207 -- cmLoadModules. The file is read, and used to determine the root
1208 -- module name. The module name may differ from the filename.
1210 -- * Summarise a module. We are given a module name, and must provide
1211 -- a summary. The finder is used to locate the file in which the module
1214 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1215 summariseFile dflags file
1216 = do hspp_fn <- preprocess dflags file
1218 -- Read the file into a buffer. We're going to cache
1219 -- this buffer in the ModLocation (ml_hspp_buf) so that it
1220 -- doesn't have to be slurped again when hscMain parses the
1222 buf <- hGetStringBuffer hspp_fn
1223 (srcimps,imps,mod) <- getImports dflags buf hspp_fn
1225 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1226 the_imps = filter (/= gHC_PRIM) imps
1228 location <- mkHomeModLocation mod file
1231 <- case ml_hs_file location of
1232 Nothing -> noHsFileErr mod
1233 Just src_fn -> getModificationTime src_fn
1235 return (ModSummary { ms_mod = mod, ms_boot = False,
1236 ms_location = location{ml_hspp_file=Just hspp_fn},
1237 ms_srcimps = srcimps, ms_imps = the_imps,
1238 ms_hs_date = src_timestamp })
1240 -- Summarise a module, and pick up source and timestamp.
1241 summarise :: DynFlags
1242 -> Module -- Guaranteed a home-package module
1244 -> ModLocation -> Maybe ModSummary
1245 -> IO (Maybe ModSummary)
1246 summarise dflags mod is_boot location old_summary
1247 = do { -- Find the source file to summarise
1248 src_fn <- if is_boot then
1249 hiBootFilePath location
1251 case ml_hs_file location of
1252 Nothing -> noHsFileErr mod
1253 Just src_fn -> return src_fn
1255 -- Find its timestamp
1256 ; src_timestamp <- getModificationTime src_fn
1258 -- return the cached summary if the source didn't change
1259 ; case old_summary of {
1260 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1263 -- For now, we never pre-process hi-boot files
1264 { hspp_fn <- if is_boot then return src_fn
1265 else preprocess dflags src_fn
1267 ; buf <- hGetStringBuffer hspp_fn
1268 ; (srcimps,imps,mod_name) <- getImports dflags buf hspp_fn
1270 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1271 the_imps = filter (/= gHC_PRIM) imps
1273 ; when (mod_name /= mod) $
1274 throwDyn (ProgramError
1275 (showSDoc (text src_fn
1276 <> text ": file name does not match module name"
1277 <+> quotes (ppr mod))))
1279 ; let new_loc = location{ ml_hspp_file = Just hspp_fn,
1280 ml_hspp_buf = Just buf }
1281 ; return (Just (ModSummary mod is_boot new_loc
1282 srcimps the_imps src_timestamp))
1286 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1289 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1290 quotes (ppr mod) <+>
1291 text "is a package module")))
1293 multiRootsErr mod files
1294 = throwDyn (ProgramError (showSDoc (
1295 text "module" <+> quotes (ppr mod) <+>
1296 text "is defined in multiple files:" <+>
1297 sep (map text files))))