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 )
74 import StringBuffer ( hGetStringBuffer )
78 import CmdLineOpts ( DynFlags(..), DynFlag(..), dopt_unset )
79 import Maybes ( expectJust, orElse, mapCatMaybes )
81 import DATA_IOREF ( readIORef )
84 import HscMain ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
85 import TcRnDriver ( mkExportEnv, getModuleContents )
86 import IfaceSyn ( IfaceDecl )
87 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
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 )
101 import EXCEPTION ( throwDyn )
104 import Directory ( getModificationTime, doesFileExist )
109 import Time ( ClockTime )
114 -- Persistent state for the entire system
117 cm_hsc :: HscEnv, -- Includes the home-package table
118 cm_mg :: ModuleGraph, -- The module graph
119 cm_ic :: InteractiveContext -- Command-line binding info
123 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
124 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
125 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
126 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
129 cmInit :: GhciMode -> DynFlags -> IO CmState
130 cmInit ghci_mode dflags
131 = do { hsc_env <- newHscEnv ghci_mode dflags
132 ; return (CmState { cm_hsc = hsc_env,
134 cm_ic = emptyInteractiveContext })}
136 discardCMInfo :: CmState -> CmState
137 -- Forget the compilation manager's state, including the home package table
138 -- but retain the persistent info in HscEnv
139 discardCMInfo cm_state
140 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
141 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
143 -------------------------------------------------------------------
144 -- The unlinked image
146 -- The compilation manager keeps a list of compiled, but as-yet unlinked
147 -- binaries (byte code or object code). Even when it links bytecode
148 -- it keeps the unlinked version so it can re-link it later without
151 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
153 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
154 findModuleLinkable_maybe lis mod
155 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
158 many -> pprPanic "findModuleLinkable" (ppr mod)
162 %************************************************************************
166 %************************************************************************
170 -----------------------------------------------------------------------------
171 -- Setting the context doesn't throw away any bindings; the bindings
172 -- we've built up in the InteractiveContext simply move to the new
173 -- module. They always shadow anything in scope in the current context.
177 -> [String] -- take the top-level scopes of these modules
178 -> [String] -- and the just the exports from these
180 cmSetContext cmstate toplevs exports = do
181 let old_ic = cm_ic cmstate
182 hsc_env = cm_hsc cmstate
183 hpt = hsc_HPT hsc_env
185 export_env <- mkExportEnv hsc_env (map mkModule exports)
186 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
188 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
189 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
190 ic_exports = exports,
191 ic_rn_gbl_env = all_env } }
193 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
195 = case lookupModuleEnv hpt (mkModule mod) of
196 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
197 Just details -> case hm_globals details of
198 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
199 Just env -> return env
201 cmGetContext :: CmState -> IO ([String],[String])
202 cmGetContext CmState{cm_ic=ic} =
203 return (ic_toplev_scope ic, ic_exports ic)
205 cmModuleIsInterpreted :: CmState -> String -> IO Bool
206 cmModuleIsInterpreted cmstate str
207 = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
208 Just details -> return (isJust (hm_globals details))
209 _not_a_home_module -> return False
211 -----------------------------------------------------------------------------
213 cmSetDFlags :: CmState -> DynFlags -> CmState
214 cmSetDFlags cm_state dflags
215 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
217 cmGetDFlags :: CmState -> DynFlags
218 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
220 -----------------------------------------------------------------------------
221 -- cmInfoThing: convert a String to a TyThing
223 -- A string may refer to more than one TyThing (eg. a constructor,
224 -- and type constructor), so we return a list of all the possible TyThings.
226 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
227 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
229 -- ---------------------------------------------------------------------------
230 -- cmBrowseModule: get all the TyThings defined in a module
232 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
233 cmBrowseModule cmstate str exports_only
234 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
235 (mkModule str) exports_only
237 Nothing -> return [] -- An error of some kind
242 -----------------------------------------------------------------------------
243 -- cmRunStmt: Run a statement/expr.
246 = CmRunOk [Name] -- names bound by this evaluation
248 | CmRunException Exception -- statement raised an exception
250 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
251 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
253 -- Turn off -fwarn-unused-bindings when running a statement, to hide
254 -- warnings about the implicit bindings we introduce.
255 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
256 hsc_env' = hsc_env{ hsc_dflags = dflags' }
258 maybe_stuff <- hscStmt hsc_env' icontext expr
261 Nothing -> return (cmstate, CmRunFailed)
262 Just (new_ic, names, hval) -> do
264 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
265 either_hvals <- sandboxIO thing_to_run
269 -- on error, keep the *old* interactive context,
270 -- so that 'it' is not bound to something
271 -- that doesn't exist.
272 return ( cmstate, CmRunException e )
275 -- Get the newly bound things, and bind them.
276 -- Don't need to delete any shadowed bindings;
277 -- the new ones override the old ones.
278 extendLinkEnv (zip names hvals)
280 return (cmstate{ cm_ic=new_ic },
284 -- We run the statement in a "sandbox" to protect the rest of the
285 -- system from anything the expression might do. For now, this
286 -- consists of just wrapping it in an exception handler, but see below
287 -- for another version.
289 sandboxIO :: IO a -> IO (Either Exception a)
290 sandboxIO thing = Exception.try thing
293 -- This version of sandboxIO runs the expression in a completely new
294 -- RTS main thread. It is disabled for now because ^C exceptions
295 -- won't be delivered to the new thread, instead they'll be delivered
296 -- to the (blocked) GHCi main thread.
298 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
300 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
302 st_thing <- newStablePtr (Exception.try thing)
303 alloca $ \ p_st_result -> do
304 stat <- rts_evalStableIO st_thing p_st_result
305 freeStablePtr st_thing
307 then do st_result <- peek p_st_result
308 result <- deRefStablePtr st_result
309 freeStablePtr st_result
310 return (Right result)
312 return (Left (fromIntegral stat))
314 foreign import "rts_evalStableIO" {- safe -}
315 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
316 -- more informative than the C type!
319 -----------------------------------------------------------------------------
320 -- cmTypeOfExpr: returns a string representing the type of an expression
322 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
323 cmTypeOfExpr cmstate expr
324 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
327 Nothing -> return Nothing
328 Just ty -> return (Just res_str)
330 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
331 unqual = icPrintUnqual (cm_ic cmstate)
332 tidy_ty = tidyType emptyTidyEnv ty
335 -----------------------------------------------------------------------------
336 -- cmKindOfType: returns a string representing the kind of a type
338 cmKindOfType :: CmState -> String -> IO (Maybe String)
339 cmKindOfType cmstate str
340 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
342 Nothing -> return Nothing
343 Just kind -> return (Just res_str)
345 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
346 unqual = icPrintUnqual (cm_ic cmstate)
348 -----------------------------------------------------------------------------
349 -- cmTypeOfName: returns a string representing the type of a name.
351 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
352 cmTypeOfName CmState{ cm_ic=ic } name
354 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
355 case lookupNameEnv (ic_type_env ic) name of
356 Nothing -> return Nothing
357 Just (AnId id) -> return (Just str)
359 unqual = icPrintUnqual ic
360 ty = tidyType emptyTidyEnv (idType id)
361 str = showSDocForUser unqual (ppr ty)
363 _ -> panic "cmTypeOfName"
365 -----------------------------------------------------------------------------
366 -- cmCompileExpr: compile an expression and deliver an HValue
368 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
369 cmCompileExpr cmstate expr
372 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
373 ("let __cmCompileExpr = "++expr)
376 Nothing -> return Nothing
377 Just (new_ic, names, hval) -> do
380 hvals <- (unsafeCoerce# hval) :: IO [HValue]
382 case (names,hvals) of
383 ([n],[hv]) -> return (Just hv)
384 _ -> panic "cmCompileExpr"
390 %************************************************************************
392 Loading and unloading
394 %************************************************************************
397 -----------------------------------------------------------------------------
398 -- Unload the compilation manager's state: everything it knows about the
399 -- current collection of modules in the Home package.
401 cmUnload :: CmState -> IO CmState
402 cmUnload state@CmState{ cm_hsc = hsc_env }
403 = do -- Throw away the old home dir cache
406 -- Unload everything the linker knows about
409 -- Start with a fresh CmState, but keep the PersistentCompilerState
410 return (discardCMInfo state)
412 cm_unload hsc_env linkables
413 = case hsc_mode hsc_env of
416 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
418 Interactive -> panic "unload: no interpreter"
422 -----------------------------------------------------------------------------
423 -- Trace dependency graph
425 -- This is a seperate pass so that the caller can back off and keep
426 -- the current state if the downsweep fails. Typically the caller
427 -- might go cmDepAnal
430 -- He wants to do the dependency analysis before the unload, so that
431 -- if the former fails he can use the later
433 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
434 cmDepAnal cmstate rootnames
435 = do showPass dflags "Chasing dependencies"
436 when (verbosity dflags >= 1 && gmode == Batch) $
437 hPutStrLn stderr (showSDoc (hcat [
438 text "Chasing modules from: ",
439 hcat (punctuate comma (map text rootnames))]))
440 downsweep dflags rootnames (cm_mg cmstate)
442 hsc_env = cm_hsc cmstate
443 dflags = hsc_dflags hsc_env
444 gmode = hsc_mode hsc_env
446 -----------------------------------------------------------------------------
447 -- The real business of the compilation manager: given a system state and
448 -- a module name, try and bring the module up to date, probably changing
449 -- the system state at the same time.
451 cmLoadModules :: CmState -- The HPT may not be as up to date
452 -> ModuleGraph -- Bang up to date
453 -> IO (CmState, -- new state
454 SuccessFlag, -- was successful
455 [String]) -- list of modules loaded
457 cmLoadModules cmstate1 mg2unsorted
458 = do -- version 1's are the original, before downsweep
459 let hsc_env = cm_hsc cmstate1
460 let hpt1 = hsc_HPT hsc_env
461 let ghci_mode = hsc_mode hsc_env -- this never changes
462 let dflags = hsc_dflags hsc_env -- this never changes
464 -- Do the downsweep to reestablish the module graph
465 let verb = verbosity dflags
467 -- Find out if we have a Main module
468 mb_main_mod <- readIORef v_MainModIs
470 main_mod = mb_main_mod `orElse` "Main"
472 = any ((==main_mod).moduleUserString.ms_mod)
475 let mg2unsorted_names = map ms_mod mg2unsorted
477 -- reachable_from follows source as well as normal imports
478 let reachable_from :: Module -> [Module]
479 reachable_from = downwards_closure_of_module mg2unsorted
481 -- should be cycle free; ignores 'import source's
482 let mg2 = topological_sort False mg2unsorted
483 -- ... whereas this takes them into account. Used for
484 -- backing out partially complete cycles following a failed
485 -- upsweep, and for removing from hpt all the modules
486 -- not in strict downwards closure, during calls to compile.
487 let mg2_with_srcimps = topological_sort True mg2unsorted
489 -- Sort out which linkables we wish to keep in the unlinked image.
490 -- See getValidLinkables below for details.
491 (valid_old_linkables, new_linkables)
492 <- getValidLinkables ghci_mode (hptLinkables hpt1)
493 mg2unsorted_names mg2_with_srcimps
495 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
497 let hpt2 = delListFromUFM hpt1 (map linkableModule new_linkables)
498 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
500 -- When (verb >= 2) $
501 -- putStrLn (showSDoc (text "Valid linkables:"
502 -- <+> ppr valid_linkables))
504 -- Figure out a stable set of modules which can be retained
505 -- the top level envs, to avoid upsweeping them. Goes to a
506 -- bit of trouble to avoid upsweeping module cycles.
508 -- Construct a set S of stable modules like this:
509 -- Travel upwards, over the sccified graph. For each scc
510 -- of modules ms, add ms to S only if:
511 -- 1. All home imports of ms are either in ms or S
512 -- 2. A valid old linkable exists for each module in ms
514 stable_mods <- preUpsweep valid_old_linkables
515 mg2unsorted_names [] mg2_with_srcimps
518 = concatMap (findInSummaries mg2unsorted) stable_mods
521 = filter (\m -> linkableModule m `elem` stable_mods)
525 hPutStrLn stderr (showSDoc (text "Stable modules:"
526 <+> sep (map (text.moduleUserString) stable_mods)))
528 -- Unload any modules which are going to be re-linked this
530 cm_unload hsc_env2 stable_linkables
532 -- we can now glom together our linkable sets
533 let valid_linkables = valid_old_linkables ++ new_linkables
535 -- We could at this point detect cycles which aren't broken by
536 -- a source-import, and complain immediately, but it seems better
537 -- to let upsweep_mods do this, so at least some useful work gets
538 -- done before the upsweep is abandoned.
540 = filter (\scc -> any (`notElem` stable_mods)
541 (map ms_mod (flattenSCC scc)))
544 --hPutStrLn stderr "after tsort:\n"
545 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
547 -- Because we don't take into account source imports when doing
548 -- the topological sort, there shouldn't be any cycles in mg2.
549 -- If there is, we complain and give up -- the user needs to
550 -- break the cycle using a boot file.
552 -- Now do the upsweep, calling compile for each module in
553 -- turn. Final result is version 3 of everything.
555 -- clean up between compilations
556 let cleanup = cleanTempFilesExcept dflags
557 (ppFilesFromSummaries (flattenSCCs mg2))
559 (upsweep_ok, hsc_env3, modsUpswept)
560 <- upsweep_mods hsc_env2 valid_linkables reachable_from
561 cleanup upsweep_these
563 -- At this point, modsUpswept and newLis should have the same
564 -- length, so there is one new (or old) linkable for each
565 -- mod which was processed (passed to compile).
567 -- Make modsDone be the summaries for each home module now
568 -- available; this should equal the domain of hpt3.
569 -- (NOT STRICTLY TRUE if an interactive session was started
570 -- with some object on disk ???)
571 -- Get in in a roughly top .. bottom order (hence reverse).
573 let modsDone = reverse modsUpswept ++ stable_summaries
575 -- Try and do linking in some form, depending on whether the
576 -- upsweep was completely or only partially successful.
578 if succeeded upsweep_ok
581 -- Easy; just relink it all.
582 do when (verb >= 2) $
583 hPutStrLn stderr "Upsweep completely successful."
585 -- clean up after ourselves
586 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
588 ofile <- readIORef v_Output_file
589 no_hs_main <- readIORef v_NoHsMain
591 -- Issue a warning for the confusing case where the user
592 -- said '-o foo' but we're not going to do any linking.
593 -- We attempt linking if either (a) one of the modules is
594 -- called Main, or (b) the user said -no-hs-main, indicating
595 -- that main() is going to come from somewhere else.
597 let do_linking = a_root_is_Main || no_hs_main
598 when (ghci_mode == Batch && isJust ofile && not do_linking
600 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
602 -- link everything together
603 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
605 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
606 cmLoadFinish Succeeded linkresult cmstate3
609 -- Tricky. We need to back out the effects of compiling any
610 -- half-done cycles, both so as to clean up the top level envs
611 -- and to avoid telling the interactive linker to link them.
612 do when (verb >= 2) $
613 hPutStrLn stderr "Upsweep partially successful."
616 = map ms_mod modsDone
617 let mods_to_zap_names
618 = findPartiallyCompletedCycles modsDone_names
621 = filter ((`notElem` mods_to_zap_names).ms_mod)
624 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
627 -- Clean up after ourselves
628 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
630 -- Link everything together
631 linkresult <- link ghci_mode dflags False hpt4
633 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
634 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
635 cmLoadFinish Failed linkresult cmstate3
638 -- Finish up after a cmLoad.
640 -- If the link failed, unload everything and return.
641 cmLoadFinish ok Failed cmstate
642 = do cm_unload (cm_hsc cmstate) []
643 return (discardCMInfo cmstate, Failed, [])
645 -- Empty the interactive context and set the module context to the topmost
646 -- newly loaded module, or the Prelude if none were loaded.
647 cmLoadFinish ok Succeeded cmstate
648 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
649 mods_loaded = map (moduleUserString.ms_mod)
652 return (new_cmstate, ok, mods_loaded)
654 -- used to fish out the preprocess output files for the purposes of
655 -- cleaning up. The preprocessed file *might* be the same as the
656 -- source file, but that doesn't do any harm.
657 ppFilesFromSummaries summaries
658 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
660 -----------------------------------------------------------------------------
663 -- For each module (or SCC of modules), we take:
665 -- - an on-disk linkable, if this is the first time around and one
668 -- - the old linkable, otherwise (and if one is available).
670 -- and we throw away the linkable if it is older than the source file.
671 -- In interactive mode, we also ignore the on-disk linkables unless
672 -- all of the dependents of this SCC also have on-disk linkables (we
673 -- can't have dynamically loaded objects that depend on interpreted
676 -- If a module has a valid linkable, then it may be STABLE (see below),
677 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
680 -- ToDo: this pass could be merged with the preUpsweep.
684 -> [Linkable] -- old linkables
685 -> [Module] -- all home modules
686 -> [SCC ModSummary] -- all modules in the program, dependency order
687 -> IO ( [Linkable], -- still-valid linkables
688 [Linkable] -- new linkables we just found
691 getValidLinkables mode old_linkables all_home_mods module_graph = do
692 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
694 return (partition_it ls [] [])
696 partition_it [] valid new = (valid,new)
697 partition_it ((l,b):ls) valid new
698 | b = partition_it ls valid (l:new)
699 | otherwise = partition_it ls (l:valid) new
702 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
704 scc = flattenSCC scc0
705 scc_names = map ms_mod scc
706 home_module m = m `elem` all_home_mods && m `notElem` scc_names
707 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
708 -- NB. ms_imps, not ms_allimps above. We don't want to
709 -- force a module's SOURCE imports to be already compiled for
710 -- its object linkable to be valid.
713 case findModuleLinkable_maybe (map fst new_linkables) m of
715 Just l -> isObjectLinkable l
717 objects_allowed = mode == Batch || all has_object scc_allhomeimps
721 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
723 -- since an scc can contain only all objects or no objects at all,
724 -- we have to check whether we got all objects or not, and re-do
725 -- the linkable check if not.
728 && not (all isObjectLinkable (map fst new_linkables'))
729 then foldM (getValidLinkable old_linkables False) [] scc
730 else return new_linkables'
732 return (new_linkables ++ new_linkables')
735 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
736 -> IO [(Linkable,Bool)]
737 -- True <=> linkable is new; i.e. freshly discovered on the disk
738 -- presumably generated 'on the side'
739 -- by a separate GHC run
740 getValidLinkable old_linkables objects_allowed new_linkables summary
741 -- 'objects_allowed' says whether we permit this module to
742 -- have a .o-file linkable. We only permit it if all the
743 -- modules it depends on also have .o files; a .o file can't
744 -- link to a bytecode module
745 = do let mod_name = ms_mod summary
748 <- if (not objects_allowed)
751 else findLinkable mod_name (ms_location summary)
753 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
756 case (old_linkable, maybe_disk_linkable) of
757 (Nothing, Nothing) -> []
759 -- new object linkable just appeared
760 (Nothing, Just l) -> up_to_date l True
763 | isObjectLinkable l -> []
764 -- object linkable disappeared! In case we need to
765 -- relink the module, disregard the old linkable and
766 -- just interpret the module from now on.
767 | otherwise -> up_to_date l False
768 -- old byte code linkable
771 | not (isObjectLinkable l) -> up_to_date l False
772 -- if the previous linkable was interpreted, then we
773 -- ignore a newly compiled version, because the version
774 -- numbers in the interface file will be out-of-sync with
775 -- our internal ones.
776 | linkableTime l' > linkableTime l -> up_to_date l' True
777 | linkableTime l' == linkableTime l -> up_to_date l False
779 -- on-disk linkable has been replaced by an older one!
780 -- again, disregard the previous one.
783 | linkableTime l < ms_hs_date summary = []
784 | otherwise = [(l,b)]
785 -- why '<' rather than '<=' above? If the filesystem stores
786 -- times to the nearset second, we may occasionally find that
787 -- the object & source have the same modification time,
788 -- especially if the source was automatically generated
789 -- and compiled. Using >= is slightly unsafe, but it matches
792 return (new_linkables' ++ new_linkables)
795 hptLinkables :: HomePackageTable -> [Linkable]
796 -- Get all the linkables from the home package table, one for each module
797 -- Once the HPT is up to date, these are the ones we should link
798 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
801 -----------------------------------------------------------------------------
802 -- Do a pre-upsweep without use of "compile", to establish a
803 -- (downward-closed) set of stable modules for which we won't call compile.
806 -- * has a valid linkable (see getValidLinkables above)
807 -- * depends only on stable modules
808 -- * has an interface in the HPT (interactive mode only)
810 preUpsweep :: [Linkable] -- new valid linkables
811 -> [Module] -- names of all mods encountered in downsweep
812 -> [Module] -- accumulating stable modules
813 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
814 -> IO [Module] -- stable modules
816 preUpsweep valid_lis all_home_mods stable [] = return stable
817 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
818 = do let scc = flattenSCC scc0
819 scc_allhomeimps :: [Module]
821 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
822 all_imports_in_scc_or_stable
823 = all in_stable_or_scc scc_allhomeimps
827 = m `elem` scc_names || m `elem` stable
829 -- now we check for valid linkables: each module in the SCC must
830 -- have a valid linkable (see getValidLinkables above).
831 has_valid_linkable new_summary
832 = isJust (findModuleLinkable_maybe valid_lis modname)
833 where modname = ms_mod new_summary
835 scc_is_stable = all_imports_in_scc_or_stable
836 && all has_valid_linkable scc
839 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
840 else preUpsweep valid_lis all_home_mods stable sccs
843 -- Helper for preUpsweep. Assuming that new_summary's imports are all
844 -- stable (in the sense of preUpsweep), determine if new_summary is itself
845 -- stable, and, if so, in batch mode, return its linkable.
846 findInSummaries :: [ModSummary] -> Module -> [ModSummary]
847 findInSummaries old_summaries mod_name
848 = [s | s <- old_summaries, ms_mod s == mod_name]
850 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
851 findModInSummaries old_summaries mod
852 = case [s | s <- old_summaries, ms_mod s == mod] of
856 -- Return (names of) all those in modsDone who are part of a cycle
857 -- as defined by theGraph.
858 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
859 findPartiallyCompletedCycles modsDone theGraph
863 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
864 chew ((CyclicSCC vs):rest)
865 = let names_in_this_cycle = nub (map ms_mod vs)
867 = nub ([done | done <- modsDone,
868 done `elem` names_in_this_cycle])
869 chewed_rest = chew rest
871 if notNull mods_in_this_cycle
872 && length mods_in_this_cycle < length names_in_this_cycle
873 then mods_in_this_cycle ++ chewed_rest
877 -- Compile multiple modules, stopping as soon as an error appears.
878 -- There better had not be any cyclic groups here -- we check for them.
879 upsweep_mods :: HscEnv -- Includes up-to-date HPT
880 -> [Linkable] -- Valid linkables
881 -> (Module -> [Module]) -- to construct downward closures
882 -> IO () -- how to clean up unwanted tmp files
883 -> [SCC ModSummary] -- mods to do (the worklist)
884 -- ...... RETURNING ......
886 HscEnv, -- With an updated HPT
887 [ModSummary]) -- Mods which succeeded
889 upsweep_mods hsc_env oldUI reachable_from cleanup
891 = return (Succeeded, hsc_env, [])
893 upsweep_mods hsc_env oldUI reachable_from cleanup
895 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
896 unwords (map (moduleUserString.ms_mod) ms))
897 return (Failed, hsc_env, [])
899 upsweep_mods hsc_env oldUI reachable_from cleanup
900 ((AcyclicSCC mod):mods)
901 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
902 -- show (map (moduleUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
904 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
905 (reachable_from (ms_mod mod))
907 cleanup -- Remove unwanted tmp files between compilations
909 if failed ok_flag then
910 return (Failed, hsc_env1, [])
912 (restOK, hsc_env2, modOKs)
913 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
914 return (restOK, hsc_env2, mod:modOKs)
917 -- Compile a single module. Always produce a Linkable for it if
918 -- successful. If no compilation happened, return the old Linkable.
919 upsweep_mod :: HscEnv
924 HscEnv) -- With updated HPT
926 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
928 let this_mod = ms_mod summary1
929 location = ms_location summary1
930 hpt1 = hsc_HPT hsc_env
932 let mb_old_iface = case lookupModuleEnv hpt1 this_mod of
933 Just mod_info -> Just (hm_iface mod_info)
936 let maybe_old_linkable = findModuleLinkable_maybe oldUI this_mod
937 source_unchanged = isJust maybe_old_linkable
939 reachable_only = filter (/= this_mod) reachable_inc_me
941 -- In interactive mode, all home modules below us *must* have an
942 -- interface in the HPT. We never demand-load home interfaces in
945 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
946 retainInTopLevelEnvs reachable_only hpt1
947 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
949 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
952 | Just l <- maybe_old_linkable, isObjectLinkable l = True
955 compresult <- compile hsc_env_strictDC this_mod location
956 (ms_hs_date summary1)
957 source_unchanged have_object mb_old_iface
961 -- Compilation "succeeded", and may or may not have returned a new
962 -- linkable (depending on whether compilation was actually performed
964 CompOK new_details new_globals new_iface maybe_new_linkable
966 new_linkable = maybe_new_linkable `orElse` old_linkable
967 new_info = HomeModInfo { hm_iface = new_iface,
968 hm_globals = new_globals,
969 hm_details = new_details,
970 hm_linkable = new_linkable }
971 hpt2 = extendModuleEnv hpt1 this_mod new_info
973 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
975 -- Compilation failed. Compile may still have updated the PCS, tho.
976 CompErrs -> return (Failed, hsc_env)
978 -- Filter modules in the HPT
979 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
980 retainInTopLevelEnvs keep_these hpt
981 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
983 maybeLookupUFM ufm u = case lookupUFM ufm u of
985 Just val -> [(u, val)]
987 -- Needed to clean up HPT so that we don't get duplicates in inst env
988 downwards_closure_of_module :: [ModSummary] -> Module -> [Module]
989 downwards_closure_of_module summaries root
990 = let toEdge :: ModSummary -> (Module,[Module])
991 toEdge summ = (ms_mod summ,
992 filter (`elem` all_mods) (ms_allimps summ))
994 all_mods = map ms_mod summaries
996 res = simple_transitive_closure (map toEdge summaries) [root]
998 -- trace (showSDoc (text "DC of mod" <+> ppr root
999 -- <+> text "=" <+> ppr res)) $
1002 -- Calculate transitive closures from a set of roots given an adjacency list
1003 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1004 simple_transitive_closure graph set
1005 = let set2 = nub (concatMap dsts set ++ set)
1006 dsts node = fromMaybe [] (lookup node graph)
1008 if length set == length set2
1010 else simple_transitive_closure graph set2
1013 -- Calculate SCCs of the module graph, with or without taking into
1014 -- account source imports.
1015 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1016 topological_sort include_source_imports summaries
1018 toEdge :: ModSummary -> (ModSummary,Module,[Module])
1020 = (summ, ms_mod summ,
1021 (if include_source_imports
1022 then ms_srcimps summ else []) ++ ms_imps summ)
1024 mash_edge :: (ModSummary,Module,[Module]) -> (ModSummary,Int,[Int])
1025 mash_edge (summ, m, m_imports)
1026 = case lookup m key_map of
1027 Nothing -> panic "reverse_topological_sort"
1028 Just mk -> (summ, mk,
1029 -- ignore imports not from the home package
1030 mapCatMaybes (flip lookup key_map) m_imports)
1032 edges = map toEdge summaries
1033 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(Module,Int)]
1034 scc_input = map mash_edge edges
1035 sccs = stronglyConnComp scc_input
1040 -----------------------------------------------------------------------------
1041 -- Downsweep (dependency analysis)
1043 -- Chase downwards from the specified root set, returning summaries
1044 -- for all home modules encountered. Only follow source-import
1047 -- We pass in the previous collection of summaries, which is used as a
1048 -- cache to avoid recalculating a module summary if the source is
1051 downsweep :: DynFlags -> [FilePath] -> [ModSummary] -> IO [ModSummary]
1052 downsweep dflags roots old_summaries
1053 = do rootSummaries <- mapM getRootSummary roots
1054 checkDuplicates rootSummaries
1056 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1057 (ms_imps m)) rootSummaries))
1058 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1060 isHomeModule dflags mod
1062 return all_summaries
1064 getRootSummary :: FilePath -> IO ModSummary
1066 | isHaskellSrcFilename file
1067 = do exists <- doesFileExist file
1068 if exists then summariseFile dflags file else do
1069 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1071 = do exists <- doesFileExist hs_file
1072 if exists then summariseFile dflags hs_file else do
1073 exists <- doesFileExist lhs_file
1074 if exists then summariseFile dflags lhs_file else do
1075 let mod_name = mkModule file
1076 maybe_summary <- getSummary (file, mod_name)
1077 case maybe_summary of
1078 Nothing -> packageModErr mod_name
1081 hs_file = file ++ ".hs"
1082 lhs_file = file ++ ".lhs"
1084 -- In a root module, the filename is allowed to diverge from the module
1085 -- name, so we have to check that there aren't multiple root files
1086 -- defining the same module (otherwise the duplicates will be silently
1087 -- ignored, leading to confusing behaviour).
1088 checkDuplicates :: [ModSummary] -> IO ()
1089 checkDuplicates summaries = mapM_ check summaries
1094 many -> multiRootsErr modl many
1095 where modl = ms_mod summ
1097 [ fromJust (ml_hs_file (ms_location summ'))
1098 | summ' <- summaries, ms_mod summ' == modl ]
1100 getSummary :: (FilePath,Module) -> IO (Maybe ModSummary)
1101 getSummary (currentMod,mod)
1102 = do found <- findModule dflags mod True{-explicit-}
1104 Found location pkg -> do
1105 let old_summary = findModInSummaries old_summaries mod
1106 summarise dflags mod location old_summary
1108 err -> throwDyn (noModError dflags currentMod mod err)
1110 -- loop invariant: env doesn't contain package modules
1111 loop :: [(FilePath,Module)] -> ModuleEnv ModSummary -> IO [ModSummary]
1112 loop [] env = return (moduleEnvElts env)
1114 = do -- imports for modules we don't already have
1115 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1118 needed_summaries <- mapM getSummary needed_imps
1120 -- get just the "home" modules
1121 let new_home_summaries = [ s | Just s <- needed_summaries ]
1123 -- loop, checking the new imports
1124 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1125 (ms_imps m)) new_home_summaries)
1126 loop new_imps (extendModuleEnvList env
1127 [ (ms_mod s, s) | s <- new_home_summaries ])
1129 -- ToDo: we don't have a proper line number for this error
1130 noModError dflags loc mod_nm err
1131 = ProgramError (showSDoc (hang (text loc <> colon) 4 $
1132 noIfaceErr dflags mod_nm err))
1134 -----------------------------------------------------------------------------
1135 -- Summarising modules
1137 -- We have two types of summarisation:
1139 -- * Summarise a file. This is used for the root module(s) passed to
1140 -- cmLoadModules. The file is read, and used to determine the root
1141 -- module name. The module name may differ from the filename.
1143 -- * Summarise a module. We are given a module name, and must provide
1144 -- a summary. The finder is used to locate the file in which the module
1147 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1148 summariseFile dflags file
1149 = do hspp_fn <- preprocess dflags file
1151 -- Read the file into a buffer. We're going to cache
1152 -- this buffer in the ModLocation (ml_hspp_buf) so that it
1153 -- doesn't have to be slurped again when hscMain parses the
1155 buf <- hGetStringBuffer hspp_fn
1156 (srcimps,imps,mod) <- getImports dflags buf hspp_fn
1158 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1159 the_imps = filter (/= gHC_PRIM) imps
1161 location <- mkHomeModLocation mod file
1164 <- case ml_hs_file location of
1165 Nothing -> noHsFileErr mod
1166 Just src_fn -> getModificationTime src_fn
1168 return (ModSummary { ms_mod = mod,
1169 ms_location = location{ ml_hspp_file = Just hspp_fn,
1170 ml_hspp_buf = Just buf },
1171 ms_srcimps = srcimps, ms_imps = the_imps,
1172 ms_hs_date = src_timestamp })
1174 -- Summarise a module, and pick up source and timestamp.
1175 summarise :: DynFlags -> Module -> ModLocation -> Maybe ModSummary
1176 -> IO (Maybe ModSummary)
1177 summarise dflags mod location old_summary
1178 | not (isHomeModule dflags mod) = return Nothing
1180 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1182 case ml_hs_file location of {
1183 Nothing -> noHsFileErr mod;
1186 src_timestamp <- getModificationTime src_fn
1188 -- return the cached summary if the source didn't change
1189 case old_summary of {
1190 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1193 hspp_fn <- preprocess dflags hs_fn
1195 buf <- hGetStringBuffer hspp_fn
1196 (srcimps,imps,mod_name) <- getImports dflags buf hspp_fn
1198 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1199 the_imps = filter (/= gHC_PRIM) imps
1201 when (mod_name /= mod) $
1202 throwDyn (ProgramError
1203 (showSDoc (text hs_fn
1204 <> text ": file name does not match module name"
1205 <+> quotes (ppr mod))))
1207 return (Just (ModSummary mod location{ ml_hspp_file = Just hspp_fn,
1208 ml_hspp_buf = Just buf }
1209 srcimps the_imps src_timestamp))
1215 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1218 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1219 quotes (ppr mod) <+>
1220 text "is a package module")))
1222 multiRootsErr mod files
1223 = throwDyn (ProgramError (showSDoc (
1224 text "module" <+> quotes (ppr mod) <+>
1225 text "is defined in multiple files:" <+>
1226 sep (map text files))))
1230 %************************************************************************
1234 %************************************************************************
1237 -- The ModLocation contains both the original source filename and the
1238 -- filename of the cleaned-up source file after all preprocessing has been
1239 -- done. The point is that the summariser will have to cpp/unlit/whatever
1240 -- all files anyway, and there's no point in doing this twice -- just
1241 -- park the result in a temp file, put the name of it in the location,
1242 -- and let @compile@ read from that file on the way back up.
1245 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1247 emptyMG :: ModuleGraph
1252 ms_mod :: Module, -- name, package
1253 ms_location :: ModLocation, -- location
1254 ms_srcimps :: [Module], -- source imports
1255 ms_imps :: [Module], -- non-source imports
1256 ms_hs_date :: ClockTime -- timestamp of summarised file
1259 instance Outputable ModSummary where
1261 = sep [text "ModSummary {",
1262 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1263 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1264 text "ms_imps =" <+> ppr (ms_imps ms),
1265 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1269 ms_allimps ms = ms_srcimps ms ++ ms_imps ms