2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
8 ModuleGraph, ModSummary(..),
12 cmInit, -- :: GhciMode -> IO CmState
14 cmDepAnal, -- :: CmState -> [FilePath] -> IO ModuleGraph
16 cmLoadModules, -- :: CmState -> ModuleGraph
17 -- -> IO (CmState, Bool, [String])
19 cmUnload, -- :: CmState -> IO CmState
22 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24 cmSetContext, -- :: CmState -> [String] -> [String] -> IO CmState
25 cmGetContext, -- :: CmState -> IO ([String],[String])
27 cmGetInfo, -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
29 cmBrowseModule, -- :: CmState -> IO [TyThing]
32 cmRunStmt, -- :: CmState -> String -> IO (CmState, CmRunResult)
34 cmTypeOfExpr, -- :: CmState -> String -> IO (CmState, Maybe String)
35 cmKindOfType, -- :: CmState -> String -> IO (CmState, Maybe String)
36 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
39 cmCompileExpr, -- :: CmState -> String -> IO (CmState, Maybe HValue)
41 cmGetModInfo, -- :: CmState -> (ModuleGraph, HomePackageTable)
46 cmGetBindings, -- :: CmState -> [TyThing]
47 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
52 #include "HsVersions.h"
54 import Packages ( isHomeModule )
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,
63 ModuleEnv, lookupModuleEnv, mkModuleEnv,
64 moduleEnvElts, extendModuleEnvList, extendModuleEnv,
68 import LoadIface ( noIfaceErr )
70 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
71 import ErrUtils ( showPass )
72 import SysTools ( cleanTempFilesExcept )
73 import BasicTypes ( SuccessFlag(..), succeeded, failed )
77 import CmdLineOpts ( DynFlags(..), DynFlag(..), dopt_unset )
78 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 )
90 import Type ( tidyType )
91 import VarEnv ( emptyTidyEnv )
92 import BasicTypes ( Fixity )
93 import Linker ( HValue, unload, extendLinkEnv )
94 import GHC.Exts ( unsafeCoerce# )
96 import SrcLoc ( SrcLoc )
97 import Control.Exception as Exception ( Exception, try )
100 import EXCEPTION ( throwDyn )
103 import Directory ( getModificationTime, doesFileExist )
108 import Time ( ClockTime )
113 -- Persistent state for the entire system
116 cm_hsc :: HscEnv, -- Includes the home-package table
117 cm_mg :: ModuleGraph, -- The module graph
118 cm_ic :: InteractiveContext -- Command-line binding info
122 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
123 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
124 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
125 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
128 cmInit :: GhciMode -> DynFlags -> IO CmState
129 cmInit ghci_mode dflags
130 = do { hsc_env <- newHscEnv ghci_mode dflags
131 ; return (CmState { cm_hsc = hsc_env,
133 cm_ic = emptyInteractiveContext })}
135 discardCMInfo :: CmState -> CmState
136 -- Forget the compilation manager's state, including the home package table
137 -- but retain the persistent info in HscEnv
138 discardCMInfo cm_state
139 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
140 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
142 -------------------------------------------------------------------
143 -- The unlinked image
145 -- The compilation manager keeps a list of compiled, but as-yet unlinked
146 -- binaries (byte code or object code). Even when it links bytecode
147 -- it keeps the unlinked version so it can re-link it later without
150 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
152 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
153 findModuleLinkable_maybe lis mod
154 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
157 many -> pprPanic "findModuleLinkable" (ppr mod)
161 %************************************************************************
165 %************************************************************************
169 -----------------------------------------------------------------------------
170 -- Setting the context doesn't throw away any bindings; the bindings
171 -- we've built up in the InteractiveContext simply move to the new
172 -- module. They always shadow anything in scope in the current context.
176 -> [String] -- take the top-level scopes of these modules
177 -> [String] -- and the just the exports from these
179 cmSetContext cmstate toplevs exports = do
180 let old_ic = cm_ic cmstate
181 hsc_env = cm_hsc cmstate
182 hpt = hsc_HPT hsc_env
184 export_env <- mkExportEnv hsc_env (map mkModule exports)
185 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
187 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
188 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
189 ic_exports = exports,
190 ic_rn_gbl_env = all_env } }
192 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
194 = case lookupModuleEnv hpt (mkModule mod) of
195 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
196 Just details -> case hm_globals details of
197 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
198 Just env -> return env
200 cmGetContext :: CmState -> IO ([String],[String])
201 cmGetContext CmState{cm_ic=ic} =
202 return (ic_toplev_scope ic, ic_exports ic)
204 cmModuleIsInterpreted :: CmState -> String -> IO Bool
205 cmModuleIsInterpreted cmstate str
206 = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
207 Just details -> return (isJust (hm_globals details))
208 _not_a_home_module -> return False
210 -----------------------------------------------------------------------------
212 cmSetDFlags :: CmState -> DynFlags -> CmState
213 cmSetDFlags cm_state dflags
214 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
216 cmGetDFlags :: CmState -> DynFlags
217 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
219 -----------------------------------------------------------------------------
220 -- cmInfoThing: convert a String to a TyThing
222 -- A string may refer to more than one TyThing (eg. a constructor,
223 -- and type constructor), so we return a list of all the possible TyThings.
225 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
226 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
228 -- ---------------------------------------------------------------------------
229 -- cmBrowseModule: get all the TyThings defined in a module
231 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
232 cmBrowseModule cmstate str exports_only
233 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
234 (mkModule str) exports_only
236 Nothing -> return [] -- An error of some kind
241 -----------------------------------------------------------------------------
242 -- cmRunStmt: Run a statement/expr.
245 = CmRunOk [Name] -- names bound by this evaluation
247 | CmRunException Exception -- statement raised an exception
249 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
250 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
252 -- Turn off -fwarn-unused-bindings when running a statement, to hide
253 -- warnings about the implicit bindings we introduce.
254 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
255 hsc_env' = hsc_env{ hsc_dflags = dflags' }
257 maybe_stuff <- hscStmt hsc_env' icontext expr
260 Nothing -> return (cmstate, CmRunFailed)
261 Just (new_ic, names, hval) -> do
263 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
264 either_hvals <- sandboxIO thing_to_run
268 -- on error, keep the *old* interactive context,
269 -- so that 'it' is not bound to something
270 -- that doesn't exist.
271 return ( cmstate, CmRunException e )
274 -- Get the newly bound things, and bind them.
275 -- Don't need to delete any shadowed bindings;
276 -- the new ones override the old ones.
277 extendLinkEnv (zip names hvals)
279 return (cmstate{ cm_ic=new_ic },
283 -- We run the statement in a "sandbox" to protect the rest of the
284 -- system from anything the expression might do. For now, this
285 -- consists of just wrapping it in an exception handler, but see below
286 -- for another version.
288 sandboxIO :: IO a -> IO (Either Exception a)
289 sandboxIO thing = Exception.try thing
292 -- This version of sandboxIO runs the expression in a completely new
293 -- RTS main thread. It is disabled for now because ^C exceptions
294 -- won't be delivered to the new thread, instead they'll be delivered
295 -- to the (blocked) GHCi main thread.
297 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
299 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
301 st_thing <- newStablePtr (Exception.try thing)
302 alloca $ \ p_st_result -> do
303 stat <- rts_evalStableIO st_thing p_st_result
304 freeStablePtr st_thing
306 then do st_result <- peek p_st_result
307 result <- deRefStablePtr st_result
308 freeStablePtr st_result
309 return (Right result)
311 return (Left (fromIntegral stat))
313 foreign import "rts_evalStableIO" {- safe -}
314 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
315 -- more informative than the C type!
318 -----------------------------------------------------------------------------
319 -- cmTypeOfExpr: returns a string representing the type of an expression
321 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
322 cmTypeOfExpr cmstate expr
323 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
326 Nothing -> return Nothing
327 Just ty -> return (Just res_str)
329 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
330 unqual = icPrintUnqual (cm_ic cmstate)
331 tidy_ty = tidyType emptyTidyEnv ty
334 -----------------------------------------------------------------------------
335 -- cmKindOfType: returns a string representing the kind of a type
337 cmKindOfType :: CmState -> String -> IO (Maybe String)
338 cmKindOfType cmstate str
339 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
341 Nothing -> return Nothing
342 Just kind -> return (Just res_str)
344 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
345 unqual = icPrintUnqual (cm_ic cmstate)
347 -----------------------------------------------------------------------------
348 -- cmTypeOfName: returns a string representing the type of a name.
350 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
351 cmTypeOfName CmState{ cm_ic=ic } name
353 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
354 case lookupNameEnv (ic_type_env ic) name of
355 Nothing -> return Nothing
356 Just (AnId id) -> return (Just str)
358 unqual = icPrintUnqual ic
359 ty = tidyType emptyTidyEnv (idType id)
360 str = showSDocForUser unqual (ppr ty)
362 _ -> panic "cmTypeOfName"
364 -----------------------------------------------------------------------------
365 -- cmCompileExpr: compile an expression and deliver an HValue
367 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
368 cmCompileExpr cmstate expr
371 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
372 ("let __cmCompileExpr = "++expr)
375 Nothing -> return Nothing
376 Just (new_ic, names, hval) -> do
379 hvals <- (unsafeCoerce# hval) :: IO [HValue]
381 case (names,hvals) of
382 ([n],[hv]) -> return (Just hv)
383 _ -> panic "cmCompileExpr"
389 %************************************************************************
391 Loading and unloading
393 %************************************************************************
396 -----------------------------------------------------------------------------
397 -- Unload the compilation manager's state: everything it knows about the
398 -- current collection of modules in the Home package.
400 cmUnload :: CmState -> IO CmState
401 cmUnload state@CmState{ cm_hsc = hsc_env }
402 = do -- Throw away the old home dir cache
405 -- Unload everything the linker knows about
408 -- Start with a fresh CmState, but keep the PersistentCompilerState
409 return (discardCMInfo state)
411 cm_unload hsc_env linkables
412 = case hsc_mode hsc_env of
415 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
417 Interactive -> panic "unload: no interpreter"
421 -----------------------------------------------------------------------------
422 -- Trace dependency graph
424 -- This is a seperate pass so that the caller can back off and keep
425 -- the current state if the downsweep fails. Typically the caller
426 -- might go cmDepAnal
429 -- He wants to do the dependency analysis before the unload, so that
430 -- if the former fails he can use the later
432 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
433 cmDepAnal cmstate rootnames
434 = do showPass dflags "Chasing dependencies"
435 when (verbosity dflags >= 1 && gmode == Batch) $
436 hPutStrLn stderr (showSDoc (hcat [
437 text "Chasing modules from: ",
438 hcat (punctuate comma (map text rootnames))]))
439 downsweep dflags rootnames (cm_mg cmstate)
441 hsc_env = cm_hsc cmstate
442 dflags = hsc_dflags hsc_env
443 gmode = hsc_mode hsc_env
445 -----------------------------------------------------------------------------
446 -- The real business of the compilation manager: given a system state and
447 -- a module name, try and bring the module up to date, probably changing
448 -- the system state at the same time.
450 cmLoadModules :: CmState -- The HPT may not be as up to date
451 -> ModuleGraph -- Bang up to date
452 -> IO (CmState, -- new state
453 SuccessFlag, -- was successful
454 [String]) -- list of modules loaded
456 cmLoadModules cmstate1 mg2unsorted
457 = do -- version 1's are the original, before downsweep
458 let hsc_env = cm_hsc cmstate1
459 let hpt1 = hsc_HPT hsc_env
460 let ghci_mode = hsc_mode hsc_env -- this never changes
461 let dflags = hsc_dflags hsc_env -- this never changes
463 -- Do the downsweep to reestablish the module graph
464 let verb = verbosity dflags
466 -- Find out if we have a Main module
467 mb_main_mod <- readIORef v_MainModIs
469 main_mod = mb_main_mod `orElse` "Main"
471 = any ((==main_mod).moduleUserString.ms_mod)
474 let mg2unsorted_names = map ms_mod mg2unsorted
476 -- reachable_from follows source as well as normal imports
477 let reachable_from :: Module -> [Module]
478 reachable_from = downwards_closure_of_module mg2unsorted
480 -- should be cycle free; ignores 'import source's
481 let mg2 = topological_sort False mg2unsorted
482 -- ... whereas this takes them into account. Used for
483 -- backing out partially complete cycles following a failed
484 -- upsweep, and for removing from hpt all the modules
485 -- not in strict downwards closure, during calls to compile.
486 let mg2_with_srcimps = topological_sort True mg2unsorted
488 -- Sort out which linkables we wish to keep in the unlinked image.
489 -- See getValidLinkables below for details.
490 (valid_old_linkables, new_linkables)
491 <- getValidLinkables ghci_mode (hptLinkables hpt1)
492 mg2unsorted_names mg2_with_srcimps
494 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
496 let hpt2 = delListFromUFM hpt1 (map linkableModule new_linkables)
497 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
499 -- When (verb >= 2) $
500 -- putStrLn (showSDoc (text "Valid linkables:"
501 -- <+> ppr valid_linkables))
503 -- Figure out a stable set of modules which can be retained
504 -- the top level envs, to avoid upsweeping them. Goes to a
505 -- bit of trouble to avoid upsweeping module cycles.
507 -- Construct a set S of stable modules like this:
508 -- Travel upwards, over the sccified graph. For each scc
509 -- of modules ms, add ms to S only if:
510 -- 1. All home imports of ms are either in ms or S
511 -- 2. A valid old linkable exists for each module in ms
513 stable_mods <- preUpsweep valid_old_linkables
514 mg2unsorted_names [] mg2_with_srcimps
517 = concatMap (findInSummaries mg2unsorted) stable_mods
520 = filter (\m -> linkableModule m `elem` stable_mods)
524 hPutStrLn stderr (showSDoc (text "Stable modules:"
525 <+> sep (map (text.moduleUserString) stable_mods)))
527 -- Unload any modules which are going to be re-linked this
529 cm_unload hsc_env2 stable_linkables
531 -- we can now glom together our linkable sets
532 let valid_linkables = valid_old_linkables ++ new_linkables
534 -- We could at this point detect cycles which aren't broken by
535 -- a source-import, and complain immediately, but it seems better
536 -- to let upsweep_mods do this, so at least some useful work gets
537 -- done before the upsweep is abandoned.
539 = filter (\scc -> any (`notElem` stable_mods)
540 (map ms_mod (flattenSCC scc)))
543 --hPutStrLn stderr "after tsort:\n"
544 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
546 -- Because we don't take into account source imports when doing
547 -- the topological sort, there shouldn't be any cycles in mg2.
548 -- If there is, we complain and give up -- the user needs to
549 -- break the cycle using a boot file.
551 -- Now do the upsweep, calling compile for each module in
552 -- turn. Final result is version 3 of everything.
554 -- clean up between compilations
555 let cleanup = cleanTempFilesExcept dflags
556 (ppFilesFromSummaries (flattenSCCs mg2))
558 (upsweep_ok, hsc_env3, modsUpswept)
559 <- upsweep_mods hsc_env2 valid_linkables reachable_from
560 cleanup upsweep_these
562 -- At this point, modsUpswept and newLis should have the same
563 -- length, so there is one new (or old) linkable for each
564 -- mod which was processed (passed to compile).
566 -- Make modsDone be the summaries for each home module now
567 -- available; this should equal the domain of hpt3.
568 -- (NOT STRICTLY TRUE if an interactive session was started
569 -- with some object on disk ???)
570 -- Get in in a roughly top .. bottom order (hence reverse).
572 let modsDone = reverse modsUpswept ++ stable_summaries
574 -- Try and do linking in some form, depending on whether the
575 -- upsweep was completely or only partially successful.
577 if succeeded upsweep_ok
580 -- Easy; just relink it all.
581 do when (verb >= 2) $
582 hPutStrLn stderr "Upsweep completely successful."
584 -- clean up after ourselves
585 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
587 ofile <- readIORef v_Output_file
588 no_hs_main <- readIORef v_NoHsMain
590 -- Issue a warning for the confusing case where the user
591 -- said '-o foo' but we're not going to do any linking.
592 -- We attempt linking if either (a) one of the modules is
593 -- called Main, or (b) the user said -no-hs-main, indicating
594 -- that main() is going to come from somewhere else.
596 let do_linking = a_root_is_Main || no_hs_main
597 when (ghci_mode == Batch && isJust ofile && not do_linking
599 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
601 -- link everything together
602 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
604 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
605 cmLoadFinish Succeeded linkresult cmstate3
608 -- Tricky. We need to back out the effects of compiling any
609 -- half-done cycles, both so as to clean up the top level envs
610 -- and to avoid telling the interactive linker to link them.
611 do when (verb >= 2) $
612 hPutStrLn stderr "Upsweep partially successful."
615 = map ms_mod modsDone
616 let mods_to_zap_names
617 = findPartiallyCompletedCycles modsDone_names
620 = filter ((`notElem` mods_to_zap_names).ms_mod)
623 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
626 -- Clean up after ourselves
627 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
629 -- Link everything together
630 linkresult <- link ghci_mode dflags False hpt4
632 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
633 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
634 cmLoadFinish Failed linkresult cmstate3
637 -- Finish up after a cmLoad.
639 -- If the link failed, unload everything and return.
640 cmLoadFinish ok Failed cmstate
641 = do cm_unload (cm_hsc cmstate) []
642 return (discardCMInfo cmstate, Failed, [])
644 -- Empty the interactive context and set the module context to the topmost
645 -- newly loaded module, or the Prelude if none were loaded.
646 cmLoadFinish ok Succeeded cmstate
647 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
648 mods_loaded = map (moduleUserString.ms_mod)
651 return (new_cmstate, ok, mods_loaded)
653 -- used to fish out the preprocess output files for the purposes of
654 -- cleaning up. The preprocessed file *might* be the same as the
655 -- source file, but that doesn't do any harm.
656 ppFilesFromSummaries summaries
657 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
659 -----------------------------------------------------------------------------
662 -- For each module (or SCC of modules), we take:
664 -- - an on-disk linkable, if this is the first time around and one
667 -- - the old linkable, otherwise (and if one is available).
669 -- and we throw away the linkable if it is older than the source file.
670 -- In interactive mode, we also ignore the on-disk linkables unless
671 -- all of the dependents of this SCC also have on-disk linkables (we
672 -- can't have dynamically loaded objects that depend on interpreted
675 -- If a module has a valid linkable, then it may be STABLE (see below),
676 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
679 -- ToDo: this pass could be merged with the preUpsweep.
683 -> [Linkable] -- old linkables
684 -> [Module] -- all home modules
685 -> [SCC ModSummary] -- all modules in the program, dependency order
686 -> IO ( [Linkable], -- still-valid linkables
687 [Linkable] -- new linkables we just found
690 getValidLinkables mode old_linkables all_home_mods module_graph = do
691 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
693 return (partition_it ls [] [])
695 partition_it [] valid new = (valid,new)
696 partition_it ((l,b):ls) valid new
697 | b = partition_it ls valid (l:new)
698 | otherwise = partition_it ls (l:valid) new
701 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
703 scc = flattenSCC scc0
704 scc_names = map ms_mod scc
705 home_module m = m `elem` all_home_mods && m `notElem` scc_names
706 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
707 -- NB. ms_imps, not ms_allimps above. We don't want to
708 -- force a module's SOURCE imports to be already compiled for
709 -- its object linkable to be valid.
712 case findModuleLinkable_maybe (map fst new_linkables) m of
714 Just l -> isObjectLinkable l
716 objects_allowed = mode == Batch || all has_object scc_allhomeimps
720 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
722 -- since an scc can contain only all objects or no objects at all,
723 -- we have to check whether we got all objects or not, and re-do
724 -- the linkable check if not.
727 && not (all isObjectLinkable (map fst new_linkables'))
728 then foldM (getValidLinkable old_linkables False) [] scc
729 else return new_linkables'
731 return (new_linkables ++ new_linkables')
734 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
735 -> IO [(Linkable,Bool)]
736 -- True <=> linkable is new; i.e. freshly discovered on the disk
737 -- presumably generated 'on the side'
738 -- by a separate GHC run
739 getValidLinkable old_linkables objects_allowed new_linkables summary
740 -- 'objects_allowed' says whether we permit this module to
741 -- have a .o-file linkable. We only permit it if all the
742 -- modules it depends on also have .o files; a .o file can't
743 -- link to a bytecode module
744 = do let mod_name = ms_mod summary
747 <- if (not objects_allowed)
750 else findLinkable mod_name (ms_location summary)
752 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
755 case (old_linkable, maybe_disk_linkable) of
756 (Nothing, Nothing) -> []
758 -- new object linkable just appeared
759 (Nothing, Just l) -> up_to_date l True
762 | isObjectLinkable l -> []
763 -- object linkable disappeared! In case we need to
764 -- relink the module, disregard the old linkable and
765 -- just interpret the module from now on.
766 | otherwise -> up_to_date l False
767 -- old byte code linkable
770 | not (isObjectLinkable l) -> up_to_date l False
771 -- if the previous linkable was interpreted, then we
772 -- ignore a newly compiled version, because the version
773 -- numbers in the interface file will be out-of-sync with
774 -- our internal ones.
775 | linkableTime l' > linkableTime l -> up_to_date l' True
776 | linkableTime l' == linkableTime l -> up_to_date l False
778 -- on-disk linkable has been replaced by an older one!
779 -- again, disregard the previous one.
782 | linkableTime l < ms_hs_date summary = []
783 | otherwise = [(l,b)]
784 -- why '<' rather than '<=' above? If the filesystem stores
785 -- times to the nearset second, we may occasionally find that
786 -- the object & source have the same modification time,
787 -- especially if the source was automatically generated
788 -- and compiled. Using >= is slightly unsafe, but it matches
791 return (new_linkables' ++ new_linkables)
794 hptLinkables :: HomePackageTable -> [Linkable]
795 -- Get all the linkables from the home package table, one for each module
796 -- Once the HPT is up to date, these are the ones we should link
797 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
800 -----------------------------------------------------------------------------
801 -- Do a pre-upsweep without use of "compile", to establish a
802 -- (downward-closed) set of stable modules for which we won't call compile.
805 -- * has a valid linkable (see getValidLinkables above)
806 -- * depends only on stable modules
807 -- * has an interface in the HPT (interactive mode only)
809 preUpsweep :: [Linkable] -- new valid linkables
810 -> [Module] -- names of all mods encountered in downsweep
811 -> [Module] -- accumulating stable modules
812 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
813 -> IO [Module] -- stable modules
815 preUpsweep valid_lis all_home_mods stable [] = return stable
816 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
817 = do let scc = flattenSCC scc0
818 scc_allhomeimps :: [Module]
820 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
821 all_imports_in_scc_or_stable
822 = all in_stable_or_scc scc_allhomeimps
826 = m `elem` scc_names || m `elem` stable
828 -- now we check for valid linkables: each module in the SCC must
829 -- have a valid linkable (see getValidLinkables above).
830 has_valid_linkable new_summary
831 = isJust (findModuleLinkable_maybe valid_lis modname)
832 where modname = ms_mod new_summary
834 scc_is_stable = all_imports_in_scc_or_stable
835 && all has_valid_linkable scc
838 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
839 else preUpsweep valid_lis all_home_mods stable sccs
842 -- Helper for preUpsweep. Assuming that new_summary's imports are all
843 -- stable (in the sense of preUpsweep), determine if new_summary is itself
844 -- stable, and, if so, in batch mode, return its linkable.
845 findInSummaries :: [ModSummary] -> Module -> [ModSummary]
846 findInSummaries old_summaries mod_name
847 = [s | s <- old_summaries, ms_mod s == mod_name]
849 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
850 findModInSummaries old_summaries mod
851 = case [s | s <- old_summaries, ms_mod s == mod] of
855 -- Return (names of) all those in modsDone who are part of a cycle
856 -- as defined by theGraph.
857 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
858 findPartiallyCompletedCycles modsDone theGraph
862 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
863 chew ((CyclicSCC vs):rest)
864 = let names_in_this_cycle = nub (map ms_mod vs)
866 = nub ([done | done <- modsDone,
867 done `elem` names_in_this_cycle])
868 chewed_rest = chew rest
870 if notNull mods_in_this_cycle
871 && length mods_in_this_cycle < length names_in_this_cycle
872 then mods_in_this_cycle ++ chewed_rest
876 -- Compile multiple modules, stopping as soon as an error appears.
877 -- There better had not be any cyclic groups here -- we check for them.
878 upsweep_mods :: HscEnv -- Includes up-to-date HPT
879 -> [Linkable] -- Valid linkables
880 -> (Module -> [Module]) -- to construct downward closures
881 -> IO () -- how to clean up unwanted tmp files
882 -> [SCC ModSummary] -- mods to do (the worklist)
883 -- ...... RETURNING ......
885 HscEnv, -- With an updated HPT
886 [ModSummary]) -- Mods which succeeded
888 upsweep_mods hsc_env oldUI reachable_from cleanup
890 = return (Succeeded, hsc_env, [])
892 upsweep_mods hsc_env oldUI reachable_from cleanup
894 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
895 unwords (map (moduleUserString.ms_mod) ms))
896 return (Failed, hsc_env, [])
898 upsweep_mods hsc_env oldUI reachable_from cleanup
899 ((AcyclicSCC mod):mods)
900 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
901 -- show (map (moduleUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
903 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
904 (reachable_from (ms_mod mod))
906 cleanup -- Remove unwanted tmp files between compilations
908 if failed ok_flag then
909 return (Failed, hsc_env1, [])
911 (restOK, hsc_env2, modOKs)
912 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
913 return (restOK, hsc_env2, mod:modOKs)
916 -- Compile a single module. Always produce a Linkable for it if
917 -- successful. If no compilation happened, return the old Linkable.
918 upsweep_mod :: HscEnv
923 HscEnv) -- With updated HPT
925 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
927 let this_mod = ms_mod summary1
928 location = ms_location summary1
929 hpt1 = hsc_HPT hsc_env
931 let mb_old_iface = case lookupModuleEnv hpt1 this_mod of
932 Just mod_info -> Just (hm_iface mod_info)
935 let maybe_old_linkable = findModuleLinkable_maybe oldUI this_mod
936 source_unchanged = isJust maybe_old_linkable
938 reachable_only = filter (/= this_mod) reachable_inc_me
940 -- In interactive mode, all home modules below us *must* have an
941 -- interface in the HPT. We never demand-load home interfaces in
944 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
945 retainInTopLevelEnvs reachable_only hpt1
946 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
948 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
951 | Just l <- maybe_old_linkable, isObjectLinkable l = True
954 compresult <- compile hsc_env_strictDC this_mod location
955 (ms_hs_date summary1)
956 source_unchanged have_object mb_old_iface
960 -- Compilation "succeeded", and may or may not have returned a new
961 -- linkable (depending on whether compilation was actually performed
963 CompOK new_details new_globals new_iface maybe_new_linkable
965 new_linkable = maybe_new_linkable `orElse` old_linkable
966 new_info = HomeModInfo { hm_iface = new_iface,
967 hm_globals = new_globals,
968 hm_details = new_details,
969 hm_linkable = new_linkable }
970 hpt2 = extendModuleEnv hpt1 this_mod new_info
972 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
974 -- Compilation failed. Compile may still have updated the PCS, tho.
975 CompErrs -> return (Failed, hsc_env)
977 -- Filter modules in the HPT
978 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
979 retainInTopLevelEnvs keep_these hpt
980 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
982 maybeLookupUFM ufm u = case lookupUFM ufm u of
984 Just val -> [(u, val)]
986 -- Needed to clean up HPT so that we don't get duplicates in inst env
987 downwards_closure_of_module :: [ModSummary] -> Module -> [Module]
988 downwards_closure_of_module summaries root
989 = let toEdge :: ModSummary -> (Module,[Module])
990 toEdge summ = (ms_mod summ,
991 filter (`elem` all_mods) (ms_allimps summ))
993 all_mods = map ms_mod summaries
995 res = simple_transitive_closure (map toEdge summaries) [root]
997 -- trace (showSDoc (text "DC of mod" <+> ppr root
998 -- <+> text "=" <+> ppr res)) $
1001 -- Calculate transitive closures from a set of roots given an adjacency list
1002 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1003 simple_transitive_closure graph set
1004 = let set2 = nub (concatMap dsts set ++ set)
1005 dsts node = fromMaybe [] (lookup node graph)
1007 if length set == length set2
1009 else simple_transitive_closure graph set2
1012 -- Calculate SCCs of the module graph, with or without taking into
1013 -- account source imports.
1014 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1015 topological_sort include_source_imports summaries
1017 toEdge :: ModSummary -> (ModSummary,Module,[Module])
1019 = (summ, ms_mod summ,
1020 (if include_source_imports
1021 then ms_srcimps summ else []) ++ ms_imps summ)
1023 mash_edge :: (ModSummary,Module,[Module]) -> (ModSummary,Int,[Int])
1024 mash_edge (summ, m, m_imports)
1025 = case lookup m key_map of
1026 Nothing -> panic "reverse_topological_sort"
1027 Just mk -> (summ, mk,
1028 -- ignore imports not from the home package
1029 mapCatMaybes (flip lookup key_map) m_imports)
1031 edges = map toEdge summaries
1032 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(Module,Int)]
1033 scc_input = map mash_edge edges
1034 sccs = stronglyConnComp scc_input
1039 -----------------------------------------------------------------------------
1040 -- Downsweep (dependency analysis)
1042 -- Chase downwards from the specified root set, returning summaries
1043 -- for all home modules encountered. Only follow source-import
1046 -- We pass in the previous collection of summaries, which is used as a
1047 -- cache to avoid recalculating a module summary if the source is
1050 downsweep :: DynFlags -> [FilePath] -> [ModSummary] -> IO [ModSummary]
1051 downsweep dflags roots old_summaries
1052 = do rootSummaries <- mapM getRootSummary roots
1053 checkDuplicates rootSummaries
1055 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1056 (ms_imps m)) rootSummaries))
1057 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1059 isHomeModule dflags mod
1061 return all_summaries
1063 getRootSummary :: FilePath -> IO ModSummary
1065 | isHaskellSrcFilename file
1066 = do exists <- doesFileExist file
1067 if exists then summariseFile dflags file else do
1068 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1070 = do exists <- doesFileExist hs_file
1071 if exists then summariseFile dflags hs_file else do
1072 exists <- doesFileExist lhs_file
1073 if exists then summariseFile dflags lhs_file else do
1074 let mod_name = mkModule file
1075 maybe_summary <- getSummary (file, mod_name)
1076 case maybe_summary of
1077 Nothing -> packageModErr mod_name
1080 hs_file = file ++ ".hs"
1081 lhs_file = file ++ ".lhs"
1083 -- In a root module, the filename is allowed to diverge from the module
1084 -- name, so we have to check that there aren't multiple root files
1085 -- defining the same module (otherwise the duplicates will be silently
1086 -- ignored, leading to confusing behaviour).
1087 checkDuplicates :: [ModSummary] -> IO ()
1088 checkDuplicates summaries = mapM_ check summaries
1093 many -> multiRootsErr modl many
1094 where modl = ms_mod summ
1096 [ fromJust (ml_hs_file (ms_location summ'))
1097 | summ' <- summaries, ms_mod summ' == modl ]
1099 getSummary :: (FilePath,Module) -> IO (Maybe ModSummary)
1100 getSummary (currentMod,mod)
1101 = do found <- findModule dflags mod True{-explicit-}
1103 Found location pkg -> do
1104 let old_summary = findModInSummaries old_summaries mod
1105 summarise dflags mod location old_summary
1107 err -> throwDyn (noModError dflags currentMod mod err)
1109 -- loop invariant: env doesn't contain package modules
1110 loop :: [(FilePath,Module)] -> ModuleEnv ModSummary -> IO [ModSummary]
1111 loop [] env = return (moduleEnvElts env)
1113 = do -- imports for modules we don't already have
1114 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1117 needed_summaries <- mapM getSummary needed_imps
1119 -- get just the "home" modules
1120 let new_home_summaries = [ s | Just s <- needed_summaries ]
1122 -- loop, checking the new imports
1123 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1124 (ms_imps m)) new_home_summaries)
1125 loop new_imps (extendModuleEnvList env
1126 [ (ms_mod s, s) | s <- new_home_summaries ])
1128 -- ToDo: we don't have a proper line number for this error
1129 noModError dflags loc mod_nm err
1130 = ProgramError (showSDoc (hang (text loc <> colon) 4 $
1131 noIfaceErr dflags mod_nm err))
1133 -----------------------------------------------------------------------------
1134 -- Summarising modules
1136 -- We have two types of summarisation:
1138 -- * Summarise a file. This is used for the root module(s) passed to
1139 -- cmLoadModules. The file is read, and used to determine the root
1140 -- module name. The module name may differ from the filename.
1142 -- * Summarise a module. We are given a module name, and must provide
1143 -- a summary. The finder is used to locate the file in which the module
1146 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1147 summariseFile dflags file
1148 = do hspp_fn <- preprocess dflags file
1149 (srcimps,imps,mod) <- getImportsFromFile hspp_fn
1151 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1152 the_imps = filter (/= gHC_PRIM) imps
1154 location <- mkHomeModLocation mod file
1157 <- case ml_hs_file location of
1158 Nothing -> noHsFileErr mod
1159 Just src_fn -> getModificationTime src_fn
1161 return (ModSummary { ms_mod = mod,
1162 ms_location = location{ml_hspp_file=Just hspp_fn},
1163 ms_srcimps = srcimps, ms_imps = the_imps,
1164 ms_hs_date = src_timestamp })
1166 -- Summarise a module, and pick up source and timestamp.
1167 summarise :: DynFlags -> Module -> ModLocation -> Maybe ModSummary
1168 -> IO (Maybe ModSummary)
1169 summarise dflags mod location old_summary
1170 | not (isHomeModule dflags mod) = return Nothing
1172 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1174 case ml_hs_file location of {
1175 Nothing -> noHsFileErr mod;
1178 src_timestamp <- getModificationTime src_fn
1180 -- return the cached summary if the source didn't change
1181 case old_summary of {
1182 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1185 hspp_fn <- preprocess dflags hs_fn
1186 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1188 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1189 the_imps = filter (/= gHC_PRIM) imps
1191 when (mod_name /= mod) $
1192 throwDyn (ProgramError
1193 (showSDoc (text hs_fn
1194 <> text ": file name does not match module name"
1195 <+> quotes (ppr mod))))
1197 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1198 srcimps the_imps src_timestamp))
1204 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1207 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1208 quotes (ppr mod) <+>
1209 text "is a package module")))
1211 multiRootsErr mod files
1212 = throwDyn (ProgramError (showSDoc (
1213 text "module" <+> quotes (ppr mod) <+>
1214 text "is defined in multiple files:" <+>
1215 sep (map text files))))
1219 %************************************************************************
1223 %************************************************************************
1226 -- The ModLocation contains both the original source filename and the
1227 -- filename of the cleaned-up source file after all preprocessing has been
1228 -- done. The point is that the summariser will have to cpp/unlit/whatever
1229 -- all files anyway, and there's no point in doing this twice -- just
1230 -- park the result in a temp file, put the name of it in the location,
1231 -- and let @compile@ read from that file on the way back up.
1234 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1236 emptyMG :: ModuleGraph
1241 ms_mod :: Module, -- name, package
1242 ms_location :: ModLocation, -- location
1243 ms_srcimps :: [Module], -- source imports
1244 ms_imps :: [Module], -- non-source imports
1245 ms_hs_date :: ClockTime -- timestamp of summarised file
1248 instance Outputable ModSummary where
1250 = sep [text "ModSummary {",
1251 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1252 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1253 text "ms_imps =" <+> ppr (ms_imps ms),
1254 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1258 ms_allimps ms = ms_srcimps ms ++ ms_imps ms