2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
9 ModuleGraph, ModSummary(..),
13 cmInit, -- :: GhciMode -> DynFlags -> IO CmState
15 cmDepAnal, -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
17 cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18 -- -> IO (CmState, Bool, [String])
20 cmUnload, -- :: CmState -> DynFlags -> IO CmState
23 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
25 cmSetContext, -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26 cmGetContext, -- :: CmState -> IO ([String],[String])
28 cmInfoThing, -- :: CmState -> DynFlags -> String
29 -- -> IO (CmState, [(TyThing,Fixity)])
31 cmBrowseModule, -- :: CmState -> IO [TyThing]
34 cmRunStmt, -- :: CmState -> DynFlags -> String
35 -- -> IO (CmState, CmRunResult)
37 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
38 -- -> IO (CmState, Maybe String)
40 cmKindOfType, -- :: CmState -> DynFlags -> String
41 -- -> IO (CmState, Maybe String)
43 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
46 cmCompileExpr, -- :: CmState -> DynFlags -> String
47 -- -> IO (CmState, Maybe HValue)
49 cmGetModInfo, -- :: CmState -> (ModuleGraph, HomePackageTable)
52 cmGetBindings, -- :: CmState -> [TyThing]
53 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
58 #include "HsVersions.h"
60 import DriverPipeline ( CompResult(..), preprocess, compile, link )
61 import HscMain ( newHscEnv )
62 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
66 import PrelNames ( gHC_PRIM_Name )
67 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
68 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
69 extendModuleEnvList, extendModuleEnv,
74 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
75 import ErrUtils ( showPass )
76 import SysTools ( cleanTempFilesExcept )
77 import BasicTypes ( SuccessFlag(..), succeeded, failed )
81 import CmdLineOpts ( DynFlags(..), getDynFlags )
82 import Maybes ( expectJust, orElse, mapCatMaybes )
84 import DATA_IOREF ( readIORef )
87 import HscMain ( hscThing, hscStmt, hscTcExpr, hscKcType )
88 import TcRnDriver ( mkExportEnv, getModuleContents )
89 import IfaceSyn ( IfaceDecl )
90 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
94 import Type ( tidyType )
95 import VarEnv ( emptyTidyEnv )
96 import BasicTypes ( Fixity )
97 import Linker ( HValue, unload, extendLinkEnv )
98 import GHC.Exts ( unsafeCoerce# )
100 import Control.Exception as Exception ( Exception, try )
103 import EXCEPTION ( throwDyn )
106 import Directory ( getModificationTime, doesFileExist )
111 import Time ( ClockTime )
116 -- Persistent state for the entire system
119 cm_hsc :: HscEnv, -- Includes the home-package table
120 cm_mg :: ModuleGraph, -- The module graph
121 cm_ic :: InteractiveContext -- Command-line binding info
125 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
126 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
127 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
128 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
131 cmInit :: GhciMode -> DynFlags -> IO CmState
132 cmInit ghci_mode dflags
133 = do { hsc_env <- newHscEnv ghci_mode dflags
134 ; return (CmState { cm_hsc = hsc_env,
136 cm_ic = emptyInteractiveContext })}
138 discardCMInfo :: CmState -> CmState
139 -- Forget the compilation manager's state, including the home package table
140 -- but retain the persistent info in HscEnv
141 discardCMInfo cm_state
142 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
143 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
145 -------------------------------------------------------------------
146 -- The unlinked image
148 -- The compilation manager keeps a list of compiled, but as-yet unlinked
149 -- binaries (byte code or object code). Even when it links bytecode
150 -- it keeps the unlinked version so it can re-link it later without
153 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
155 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
156 findModuleLinkable_maybe lis mod
157 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
160 many -> pprPanic "findModuleLinkable" (ppr mod)
164 %************************************************************************
168 %************************************************************************
172 -----------------------------------------------------------------------------
173 -- Setting the context doesn't throw away any bindings; the bindings
174 -- we've built up in the InteractiveContext simply move to the new
175 -- module. They always shadow anything in scope in the current context.
179 -> [String] -- take the top-level scopes of these modules
180 -> [String] -- and the just the exports from these
182 cmSetContext cmstate toplevs exports = do
183 let old_ic = cm_ic cmstate
184 hsc_env = cm_hsc cmstate
185 hpt = hsc_HPT hsc_env
187 export_env <- mkExportEnv hsc_env (map mkModuleName exports)
188 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
190 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
191 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
192 ic_exports = exports,
193 ic_rn_gbl_env = all_env } }
195 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
197 = case lookupModuleEnvByName hpt (mkModuleName mod) of
198 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
199 Just details -> case hm_globals details of
200 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
201 Just env -> return env
203 cmGetContext :: CmState -> IO ([String],[String])
204 cmGetContext CmState{cm_ic=ic} =
205 return (ic_toplev_scope ic, ic_exports ic)
207 cmModuleIsInterpreted :: CmState -> String -> IO Bool
208 cmModuleIsInterpreted cmstate str
209 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
210 Just details -> return (isJust (hm_globals details))
211 _not_a_home_module -> return False
213 -----------------------------------------------------------------------------
214 cmSetDFlags :: CmState -> DynFlags -> CmState
215 cmSetDFlags cm_state dflags
216 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
218 -----------------------------------------------------------------------------
219 -- cmInfoThing: convert a String to a TyThing
221 -- A string may refer to more than one TyThing (eg. a constructor,
222 -- and type constructor), so we return a list of all the possible TyThings.
224 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity)]
225 cmInfoThing cmstate id
226 = hscThing (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 (mkModuleName 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 maybe_stuff <- hscStmt hsc_env icontext expr
255 Nothing -> return (cmstate, CmRunFailed)
256 Just (new_ic, names, hval) -> do
258 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
259 either_hvals <- sandboxIO thing_to_run
263 -- on error, keep the *old* interactive context,
264 -- so that 'it' is not bound to something
265 -- that doesn't exist.
266 return ( cmstate, CmRunException e )
269 -- Get the newly bound things, and bind them.
270 -- Don't need to delete any shadowed bindings;
271 -- the new ones override the old ones.
272 extendLinkEnv (zip names hvals)
274 return (cmstate{ cm_ic=new_ic },
278 -- We run the statement in a "sandbox" to protect the rest of the
279 -- system from anything the expression might do. For now, this
280 -- consists of just wrapping it in an exception handler, but see below
281 -- for another version.
283 sandboxIO :: IO a -> IO (Either Exception a)
284 sandboxIO thing = Exception.try thing
287 -- This version of sandboxIO runs the expression in a completely new
288 -- RTS main thread. It is disabled for now because ^C exceptions
289 -- won't be delivered to the new thread, instead they'll be delivered
290 -- to the (blocked) GHCi main thread.
292 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
294 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
296 st_thing <- newStablePtr (Exception.try thing)
297 alloca $ \ p_st_result -> do
298 stat <- rts_evalStableIO st_thing p_st_result
299 freeStablePtr st_thing
301 then do st_result <- peek p_st_result
302 result <- deRefStablePtr st_result
303 freeStablePtr st_result
304 return (Right result)
306 return (Left (fromIntegral stat))
308 foreign import "rts_evalStableIO" {- safe -}
309 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
310 -- more informative than the C type!
313 -----------------------------------------------------------------------------
314 -- cmTypeOfExpr: returns a string representing the type of an expression
316 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
317 cmTypeOfExpr cmstate expr
318 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
321 Nothing -> return Nothing
322 Just ty -> return (Just res_str)
324 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
325 unqual = icPrintUnqual (cm_ic cmstate)
326 tidy_ty = tidyType emptyTidyEnv ty
329 -----------------------------------------------------------------------------
330 -- cmKindOfType: returns a string representing the kind of a type
332 cmKindOfType :: CmState -> String -> IO (Maybe String)
333 cmKindOfType cmstate str
334 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
336 Nothing -> return Nothing
337 Just kind -> return (Just res_str)
339 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
340 unqual = icPrintUnqual (cm_ic cmstate)
342 -----------------------------------------------------------------------------
343 -- cmTypeOfName: returns a string representing the type of a name.
345 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
346 cmTypeOfName CmState{ cm_ic=ic } name
348 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
349 case lookupNameEnv (ic_type_env ic) name of
350 Nothing -> return Nothing
351 Just (AnId id) -> return (Just str)
353 unqual = icPrintUnqual ic
354 ty = tidyType emptyTidyEnv (idType id)
355 str = showSDocForUser unqual (ppr ty)
357 _ -> panic "cmTypeOfName"
359 -----------------------------------------------------------------------------
360 -- cmCompileExpr: compile an expression and deliver an HValue
362 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
363 cmCompileExpr cmstate expr
366 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
367 ("let __cmCompileExpr = "++expr)
370 Nothing -> return Nothing
371 Just (new_ic, names, hval) -> do
374 hvals <- (unsafeCoerce# hval) :: IO [HValue]
376 case (names,hvals) of
377 ([n],[hv]) -> return (Just hv)
378 _ -> panic "cmCompileExpr"
384 %************************************************************************
386 Loading and unloading
388 %************************************************************************
391 -----------------------------------------------------------------------------
392 -- Unload the compilation manager's state: everything it knows about the
393 -- current collection of modules in the Home package.
395 cmUnload :: CmState -> IO CmState
396 cmUnload state@CmState{ cm_hsc = hsc_env }
397 = do -- Throw away the old home dir cache
400 -- Unload everything the linker knows about
403 -- Start with a fresh CmState, but keep the PersistentCompilerState
404 return (discardCMInfo state)
406 cm_unload hsc_env linkables
407 = case hsc_mode hsc_env of
410 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
412 Interactive -> panic "unload: no interpreter"
416 -----------------------------------------------------------------------------
417 -- Trace dependency graph
419 -- This is a seperate pass so that the caller can back off and keep
420 -- the current state if the downsweep fails. Typically the caller
421 -- might go cmDepAnal
424 -- He wants to do the dependency analysis before the unload, so that
425 -- if the former fails he can use the later
427 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
428 cmDepAnal cmstate rootnames
429 = do showPass dflags "Chasing dependencies"
430 when (verbosity dflags >= 1 && gmode == Batch) $
431 hPutStrLn stderr (showSDoc (hcat [
432 text "Chasing modules from: ",
433 hcat (punctuate comma (map text rootnames))]))
434 downsweep rootnames (cm_mg cmstate)
436 hsc_env = cm_hsc cmstate
437 dflags = hsc_dflags hsc_env
438 gmode = hsc_mode hsc_env
440 -----------------------------------------------------------------------------
441 -- The real business of the compilation manager: given a system state and
442 -- a module name, try and bring the module up to date, probably changing
443 -- the system state at the same time.
445 cmLoadModules :: CmState -- The HPT may not be as up to date
446 -> ModuleGraph -- Bang up to date
447 -> IO (CmState, -- new state
448 SuccessFlag, -- was successful
449 [String]) -- list of modules loaded
451 cmLoadModules cmstate1 mg2unsorted
452 = do -- version 1's are the original, before downsweep
453 let hsc_env = cm_hsc cmstate1
454 let hpt1 = hsc_HPT hsc_env
455 let ghci_mode = hsc_mode hsc_env -- this never changes
456 let dflags = hsc_dflags hsc_env -- this never changes
458 -- Do the downsweep to reestablish the module graph
459 let verb = verbosity dflags
461 -- Find out if we have a Main module
462 mb_main_mod <- readIORef v_MainModIs
464 main_mod = mb_main_mod `orElse` "Main"
466 = any ((==main_mod).moduleNameUserString.modSummaryName)
469 let mg2unsorted_names = map modSummaryName mg2unsorted
471 -- reachable_from follows source as well as normal imports
472 let reachable_from :: ModuleName -> [ModuleName]
473 reachable_from = downwards_closure_of_module mg2unsorted
475 -- should be cycle free; ignores 'import source's
476 let mg2 = topological_sort False mg2unsorted
477 -- ... whereas this takes them into account. Used for
478 -- backing out partially complete cycles following a failed
479 -- upsweep, and for removing from hpt all the modules
480 -- not in strict downwards closure, during calls to compile.
481 let mg2_with_srcimps = topological_sort True mg2unsorted
483 -- Sort out which linkables we wish to keep in the unlinked image.
484 -- See getValidLinkables below for details.
485 (valid_old_linkables, new_linkables)
486 <- getValidLinkables ghci_mode (hptLinkables hpt1)
487 mg2unsorted_names mg2_with_srcimps
489 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
491 -- Uniq of ModuleName is the same as Module, fortunately...
492 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
493 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
495 -- When (verb >= 2) $
496 -- putStrLn (showSDoc (text "Valid linkables:"
497 -- <+> ppr valid_linkables))
499 -- Figure out a stable set of modules which can be retained
500 -- the top level envs, to avoid upsweeping them. Goes to a
501 -- bit of trouble to avoid upsweeping module cycles.
503 -- Construct a set S of stable modules like this:
504 -- Travel upwards, over the sccified graph. For each scc
505 -- of modules ms, add ms to S only if:
506 -- 1. All home imports of ms are either in ms or S
507 -- 2. A valid old linkable exists for each module in ms
509 stable_mods <- preUpsweep valid_old_linkables
510 mg2unsorted_names [] mg2_with_srcimps
513 = concatMap (findInSummaries mg2unsorted) stable_mods
516 = filter (\m -> linkableModName m `elem` stable_mods)
520 hPutStrLn stderr (showSDoc (text "Stable modules:"
521 <+> sep (map (text.moduleNameUserString) stable_mods)))
523 -- Unload any modules which are going to be re-linked this
525 cm_unload hsc_env2 stable_linkables
527 -- we can now glom together our linkable sets
528 let valid_linkables = valid_old_linkables ++ new_linkables
530 -- We could at this point detect cycles which aren't broken by
531 -- a source-import, and complain immediately, but it seems better
532 -- to let upsweep_mods do this, so at least some useful work gets
533 -- done before the upsweep is abandoned.
535 = filter (\scc -> any (`notElem` stable_mods)
536 (map modSummaryName (flattenSCC scc)))
539 --hPutStrLn stderr "after tsort:\n"
540 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
542 -- Because we don't take into account source imports when doing
543 -- the topological sort, there shouldn't be any cycles in mg2.
544 -- If there is, we complain and give up -- the user needs to
545 -- break the cycle using a boot file.
547 -- Now do the upsweep, calling compile for each module in
548 -- turn. Final result is version 3 of everything.
550 -- clean up between compilations
551 let cleanup = cleanTempFilesExcept verb
552 (ppFilesFromSummaries (flattenSCCs mg2))
554 (upsweep_ok, hsc_env3, modsUpswept)
555 <- upsweep_mods hsc_env2 valid_linkables reachable_from
556 cleanup upsweep_these
558 -- At this point, modsUpswept and newLis should have the same
559 -- length, so there is one new (or old) linkable for each
560 -- mod which was processed (passed to compile).
562 -- Make modsDone be the summaries for each home module now
563 -- available; this should equal the domain of hpt3.
564 -- (NOT STRICTLY TRUE if an interactive session was started
565 -- with some object on disk ???)
566 -- Get in in a roughly top .. bottom order (hence reverse).
568 let modsDone = reverse modsUpswept ++ stable_summaries
570 -- Try and do linking in some form, depending on whether the
571 -- upsweep was completely or only partially successful.
573 if succeeded upsweep_ok
576 -- Easy; just relink it all.
577 do when (verb >= 2) $
578 hPutStrLn stderr "Upsweep completely successful."
580 -- clean up after ourselves
581 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
583 ofile <- readIORef v_Output_file
584 no_hs_main <- readIORef v_NoHsMain
586 -- Issue a warning for the confusing case where the user
587 -- said '-o foo' but we're not going to do any linking.
588 -- We attempt linking if either (a) one of the modules is
589 -- called Main, or (b) the user said -no-hs-main, indicating
590 -- that main() is going to come from somewhere else.
592 let do_linking = a_root_is_Main || no_hs_main
593 when (ghci_mode == Batch && isJust ofile && not do_linking
595 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
597 -- link everything together
598 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
600 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
601 cmLoadFinish Succeeded linkresult cmstate3
604 -- Tricky. We need to back out the effects of compiling any
605 -- half-done cycles, both so as to clean up the top level envs
606 -- and to avoid telling the interactive linker to link them.
607 do when (verb >= 2) $
608 hPutStrLn stderr "Upsweep partially successful."
611 = map modSummaryName modsDone
612 let mods_to_zap_names
613 = findPartiallyCompletedCycles modsDone_names
616 = filter ((`notElem` mods_to_zap_names).modSummaryName)
619 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
622 -- Clean up after ourselves
623 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
625 -- Link everything together
626 linkresult <- link ghci_mode dflags False hpt4
628 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
629 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
630 cmLoadFinish Failed linkresult cmstate3
633 -- Finish up after a cmLoad.
635 -- If the link failed, unload everything and return.
636 cmLoadFinish ok Failed cmstate
637 = do cm_unload (cm_hsc cmstate) []
638 return (discardCMInfo cmstate, Failed, [])
640 -- Empty the interactive context and set the module context to the topmost
641 -- newly loaded module, or the Prelude if none were loaded.
642 cmLoadFinish ok Succeeded cmstate
643 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
644 mods_loaded = map (moduleNameUserString.modSummaryName)
647 return (new_cmstate, ok, mods_loaded)
649 -- used to fish out the preprocess output files for the purposes of
650 -- cleaning up. The preprocessed file *might* be the same as the
651 -- source file, but that doesn't do any harm.
652 ppFilesFromSummaries summaries
653 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
655 -----------------------------------------------------------------------------
658 -- For each module (or SCC of modules), we take:
660 -- - an on-disk linkable, if this is the first time around and one
663 -- - the old linkable, otherwise (and if one is available).
665 -- and we throw away the linkable if it is older than the source file.
666 -- In interactive mode, we also ignore the on-disk linkables unless
667 -- all of the dependents of this SCC also have on-disk linkables (we
668 -- can't have dynamically loaded objects that depend on interpreted
671 -- If a module has a valid linkable, then it may be STABLE (see below),
672 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
675 -- ToDo: this pass could be merged with the preUpsweep.
679 -> [Linkable] -- old linkables
680 -> [ModuleName] -- all home modules
681 -> [SCC ModSummary] -- all modules in the program, dependency order
682 -> IO ( [Linkable], -- still-valid linkables
683 [Linkable] -- new linkables we just found
686 getValidLinkables mode old_linkables all_home_mods module_graph = do
687 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
689 return (partition_it ls [] [])
691 partition_it [] valid new = (valid,new)
692 partition_it ((l,b):ls) valid new
693 | b = partition_it ls valid (l:new)
694 | otherwise = partition_it ls (l:valid) new
697 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
699 scc = flattenSCC scc0
700 scc_names = map modSummaryName scc
701 home_module m = m `elem` all_home_mods && m `notElem` scc_names
702 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
703 -- NB. ms_imps, not ms_allimps above. We don't want to
704 -- force a module's SOURCE imports to be already compiled for
705 -- its object linkable to be valid.
708 case findModuleLinkable_maybe (map fst new_linkables) m of
710 Just l -> isObjectLinkable l
712 objects_allowed = mode == Batch || all has_object scc_allhomeimps
716 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
718 -- since an scc can contain only all objects or no objects at all,
719 -- we have to check whether we got all objects or not, and re-do
720 -- the linkable check if not.
723 && not (all isObjectLinkable (map fst new_linkables'))
724 then foldM (getValidLinkable old_linkables False) [] scc
725 else return new_linkables'
727 return (new_linkables ++ new_linkables')
730 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
731 -> IO [(Linkable,Bool)]
732 -- True <=> linkable is new; i.e. freshly discovered on the disk
733 -- presumably generated 'on the side'
734 -- by a separate GHC run
735 getValidLinkable old_linkables objects_allowed new_linkables summary
736 -- 'objects_allowed' says whether we permit this module to
737 -- have a .o-file linkable. We only permit it if all the
738 -- modules it depends on also have .o files; a .o file can't
739 -- link to a bytecode module
740 = do let mod_name = modSummaryName summary
743 <- if (not objects_allowed)
746 else findLinkable mod_name (ms_location summary)
748 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
751 case (old_linkable, maybe_disk_linkable) of
752 (Nothing, Nothing) -> []
754 -- new object linkable just appeared
755 (Nothing, Just l) -> up_to_date l True
758 | isObjectLinkable l -> []
759 -- object linkable disappeared! In case we need to
760 -- relink the module, disregard the old linkable and
761 -- just interpret the module from now on.
762 | otherwise -> up_to_date l False
763 -- old byte code linkable
766 | not (isObjectLinkable l) -> up_to_date l False
767 -- if the previous linkable was interpreted, then we
768 -- ignore a newly compiled version, because the version
769 -- numbers in the interface file will be out-of-sync with
770 -- our internal ones.
771 | linkableTime l' > linkableTime l -> up_to_date l' True
772 | linkableTime l' == linkableTime l -> up_to_date l False
774 -- on-disk linkable has been replaced by an older one!
775 -- again, disregard the previous one.
778 | linkableTime l < ms_hs_date summary = []
779 | otherwise = [(l,b)]
780 -- why '<' rather than '<=' above? If the filesystem stores
781 -- times to the nearset second, we may occasionally find that
782 -- the object & source have the same modification time,
783 -- especially if the source was automatically generated
784 -- and compiled. Using >= is slightly unsafe, but it matches
787 return (new_linkables' ++ new_linkables)
790 hptLinkables :: HomePackageTable -> [Linkable]
791 -- Get all the linkables from the home package table, one for each module
792 -- Once the HPT is up to date, these are the ones we should link
793 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
796 -----------------------------------------------------------------------------
797 -- Do a pre-upsweep without use of "compile", to establish a
798 -- (downward-closed) set of stable modules for which we won't call compile.
801 -- * has a valid linkable (see getValidLinkables above)
802 -- * depends only on stable modules
803 -- * has an interface in the HPT (interactive mode only)
805 preUpsweep :: [Linkable] -- new valid linkables
806 -> [ModuleName] -- names of all mods encountered in downsweep
807 -> [ModuleName] -- accumulating stable modules
808 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
809 -> IO [ModuleName] -- stable modules
811 preUpsweep valid_lis all_home_mods stable [] = return stable
812 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
813 = do let scc = flattenSCC scc0
814 scc_allhomeimps :: [ModuleName]
816 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
817 all_imports_in_scc_or_stable
818 = all in_stable_or_scc scc_allhomeimps
820 = map modSummaryName scc
822 = m `elem` scc_names || m `elem` stable
824 -- now we check for valid linkables: each module in the SCC must
825 -- have a valid linkable (see getValidLinkables above).
826 has_valid_linkable new_summary
827 = isJust (findModuleLinkable_maybe valid_lis modname)
828 where modname = modSummaryName new_summary
830 scc_is_stable = all_imports_in_scc_or_stable
831 && all has_valid_linkable scc
834 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
835 else preUpsweep valid_lis all_home_mods stable sccs
838 -- Helper for preUpsweep. Assuming that new_summary's imports are all
839 -- stable (in the sense of preUpsweep), determine if new_summary is itself
840 -- stable, and, if so, in batch mode, return its linkable.
841 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
842 findInSummaries old_summaries mod_name
843 = [s | s <- old_summaries, modSummaryName s == mod_name]
845 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
846 findModInSummaries old_summaries mod
847 = case [s | s <- old_summaries, ms_mod s == mod] of
851 -- Return (names of) all those in modsDone who are part of a cycle
852 -- as defined by theGraph.
853 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
854 findPartiallyCompletedCycles modsDone theGraph
858 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
859 chew ((CyclicSCC vs):rest)
860 = let names_in_this_cycle = nub (map modSummaryName vs)
862 = nub ([done | done <- modsDone,
863 done `elem` names_in_this_cycle])
864 chewed_rest = chew rest
866 if notNull mods_in_this_cycle
867 && length mods_in_this_cycle < length names_in_this_cycle
868 then mods_in_this_cycle ++ chewed_rest
872 -- Compile multiple modules, stopping as soon as an error appears.
873 -- There better had not be any cyclic groups here -- we check for them.
874 upsweep_mods :: HscEnv -- Includes up-to-date HPT
875 -> [Linkable] -- Valid linkables
876 -> (ModuleName -> [ModuleName]) -- to construct downward closures
877 -> IO () -- how to clean up unwanted tmp files
878 -> [SCC ModSummary] -- mods to do (the worklist)
879 -- ...... RETURNING ......
881 HscEnv, -- With an updated HPT
882 [ModSummary]) -- Mods which succeeded
884 upsweep_mods hsc_env oldUI reachable_from cleanup
886 = return (Succeeded, hsc_env, [])
888 upsweep_mods hsc_env oldUI reachable_from cleanup
890 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
891 unwords (map (moduleNameUserString.modSummaryName) ms))
892 return (Failed, hsc_env, [])
894 upsweep_mods hsc_env oldUI reachable_from cleanup
895 ((AcyclicSCC mod):mods)
896 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
897 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
899 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
900 (reachable_from (modSummaryName mod))
902 cleanup -- Remove unwanted tmp files between compilations
904 if failed ok_flag then
905 return (Failed, hsc_env1, [])
907 (restOK, hsc_env2, modOKs)
908 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
909 return (restOK, hsc_env2, mod:modOKs)
912 -- Compile a single module. Always produce a Linkable for it if
913 -- successful. If no compilation happened, return the old Linkable.
914 upsweep_mod :: HscEnv
919 HscEnv) -- With updated HPT
921 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
923 let this_mod = ms_mod summary1
924 location = ms_location summary1
925 mod_name = moduleName this_mod
926 hpt1 = hsc_HPT hsc_env
928 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
929 Just mod_info -> Just (hm_iface mod_info)
932 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
933 source_unchanged = isJust maybe_old_linkable
935 reachable_only = filter (/= mod_name) reachable_inc_me
937 -- In interactive mode, all home modules below us *must* have an
938 -- interface in the HPT. We never demand-load home interfaces in
941 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
942 retainInTopLevelEnvs reachable_only hpt1
943 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
945 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
948 | Just l <- maybe_old_linkable, isObjectLinkable l = True
951 compresult <- compile hsc_env_strictDC this_mod location
952 source_unchanged have_object mb_old_iface
956 -- Compilation "succeeded", and may or may not have returned a new
957 -- linkable (depending on whether compilation was actually performed
959 CompOK new_details new_globals new_iface maybe_new_linkable
961 new_linkable = maybe_new_linkable `orElse` old_linkable
962 new_info = HomeModInfo { hm_iface = new_iface,
963 hm_globals = new_globals,
964 hm_details = new_details,
965 hm_linkable = new_linkable }
966 hpt2 = extendModuleEnv hpt1 this_mod new_info
968 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
970 -- Compilation failed. Compile may still have updated the PCS, tho.
971 CompErrs -> return (Failed, hsc_env)
973 -- Filter modules in the HPT
974 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
975 retainInTopLevelEnvs keep_these hpt
976 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
978 maybeLookupUFM ufm u = case lookupUFM ufm u of
980 Just val -> [(u, val)]
982 -- Needed to clean up HPT so that we don't get duplicates in inst env
983 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
984 downwards_closure_of_module summaries root
985 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
986 toEdge summ = (modSummaryName summ,
987 filter (`elem` all_mods) (ms_allimps summ))
989 all_mods = map modSummaryName summaries
991 res = simple_transitive_closure (map toEdge summaries) [root]
993 -- trace (showSDoc (text "DC of mod" <+> ppr root
994 -- <+> text "=" <+> ppr res)) $
997 -- Calculate transitive closures from a set of roots given an adjacency list
998 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
999 simple_transitive_closure graph set
1000 = let set2 = nub (concatMap dsts set ++ set)
1001 dsts node = fromMaybe [] (lookup node graph)
1003 if length set == length set2
1005 else simple_transitive_closure graph set2
1008 -- Calculate SCCs of the module graph, with or without taking into
1009 -- account source imports.
1010 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1011 topological_sort include_source_imports summaries
1013 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1015 = (summ, modSummaryName summ,
1016 (if include_source_imports
1017 then ms_srcimps summ else []) ++ ms_imps summ)
1019 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1020 mash_edge (summ, m, m_imports)
1021 = case lookup m key_map of
1022 Nothing -> panic "reverse_topological_sort"
1023 Just mk -> (summ, mk,
1024 -- ignore imports not from the home package
1025 mapCatMaybes (flip lookup key_map) m_imports)
1027 edges = map toEdge summaries
1028 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1029 scc_input = map mash_edge edges
1030 sccs = stronglyConnComp scc_input
1035 -----------------------------------------------------------------------------
1036 -- Downsweep (dependency analysis)
1038 -- Chase downwards from the specified root set, returning summaries
1039 -- for all home modules encountered. Only follow source-import
1042 -- We pass in the previous collection of summaries, which is used as a
1043 -- cache to avoid recalculating a module summary if the source is
1046 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1047 downsweep roots old_summaries
1048 = do rootSummaries <- mapM getRootSummary roots
1049 checkDuplicates rootSummaries
1051 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1052 (ms_imps m)) rootSummaries))
1053 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1054 let mod = ms_mod s, isHomeModule mod
1056 return all_summaries
1058 getRootSummary :: FilePath -> IO ModSummary
1060 | isHaskellSrcFilename file
1061 = do exists <- doesFileExist file
1062 if exists then summariseFile file else do
1063 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1065 = do exists <- doesFileExist hs_file
1066 if exists then summariseFile hs_file else do
1067 exists <- doesFileExist lhs_file
1068 if exists then summariseFile lhs_file else do
1069 let mod_name = mkModuleName file
1070 maybe_summary <- getSummary (file, mod_name)
1071 case maybe_summary of
1072 Nothing -> packageModErr mod_name
1075 hs_file = file ++ ".hs"
1076 lhs_file = file ++ ".lhs"
1078 -- In a root module, the filename is allowed to diverge from the module
1079 -- name, so we have to check that there aren't multiple root files
1080 -- defining the same module (otherwise the duplicates will be silently
1081 -- ignored, leading to confusing behaviour).
1082 checkDuplicates :: [ModSummary] -> IO ()
1083 checkDuplicates summaries = mapM_ check summaries
1088 many -> multiRootsErr modl many
1089 where modl = ms_mod summ
1091 [ fromJust (ml_hs_file (ms_location summ'))
1092 | summ' <- summaries, ms_mod summ' == modl ]
1094 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1095 getSummary (currentMod,nm)
1096 = do found <- findModule nm
1098 Right (mod, location) -> do
1099 let old_summary = findModInSummaries old_summaries mod
1100 summarise mod location old_summary
1103 dflags <- getDynFlags
1104 throwDyn (noModError dflags currentMod nm files)
1106 -- loop invariant: env doesn't contain package modules
1107 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1108 loop [] env = return (moduleEnvElts env)
1110 = do -- imports for modules we don't already have
1111 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1114 needed_summaries <- mapM getSummary needed_imps
1116 -- get just the "home" modules
1117 let new_home_summaries = [ s | Just s <- needed_summaries ]
1119 -- loop, checking the new imports
1120 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1121 (ms_imps m)) new_home_summaries)
1122 loop new_imps (extendModuleEnvList env
1123 [ (ms_mod s, s) | s <- new_home_summaries ])
1125 -- ToDo: we don't have a proper line number for this error
1126 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1127 hang (text loc <> colon) 4 $
1128 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1132 | verbosity dflags < 3 =
1133 text "(use -v to see a list of the files searched for)"
1135 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1137 -----------------------------------------------------------------------------
1138 -- Summarising modules
1140 -- We have two types of summarisation:
1142 -- * Summarise a file. This is used for the root module(s) passed to
1143 -- cmLoadModules. The file is read, and used to determine the root
1144 -- module name. The module name may differ from the filename.
1146 -- * Summarise a module. We are given a module name, and must provide
1147 -- a summary. The finder is used to locate the file in which the module
1150 summariseFile :: FilePath -> IO ModSummary
1152 = do hspp_fn <- preprocess file
1153 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1155 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1156 the_imps = filter (/= gHC_PRIM_Name) imps
1158 (mod, location) <- mkHomeModLocation mod_name file
1161 <- case ml_hs_file location of
1162 Nothing -> noHsFileErr mod_name
1163 Just src_fn -> getModificationTime src_fn
1165 return (ModSummary { ms_mod = mod,
1166 ms_location = location{ml_hspp_file=Just hspp_fn},
1167 ms_srcimps = srcimps, ms_imps = the_imps,
1168 ms_hs_date = src_timestamp })
1170 -- Summarise a module, and pick up source and timestamp.
1171 summarise :: Module -> ModLocation -> Maybe ModSummary
1172 -> IO (Maybe ModSummary)
1173 summarise mod location old_summary
1174 | not (isHomeModule mod) = return Nothing
1176 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1178 case ml_hs_file location of {
1179 Nothing -> noHsFileErr mod;
1182 src_timestamp <- getModificationTime src_fn
1184 -- return the cached summary if the source didn't change
1185 case old_summary of {
1186 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1189 hspp_fn <- preprocess hs_fn
1190 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1192 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1193 the_imps = filter (/= gHC_PRIM_Name) imps
1195 when (mod_name /= moduleName mod) $
1196 throwDyn (ProgramError
1197 (showSDoc (text hs_fn
1198 <> text ": file name does not match module name"
1199 <+> quotes (ppr (moduleName mod)))))
1201 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1202 srcimps the_imps src_timestamp))
1208 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1211 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1212 quotes (ppr mod) <+>
1213 text "is a package module")))
1215 multiRootsErr mod files
1216 = throwDyn (ProgramError (showSDoc (
1217 text "module" <+> quotes (ppr mod) <+>
1218 text "is defined in multiple files:" <+>
1219 sep (map text files))))
1223 %************************************************************************
1227 %************************************************************************
1230 -- The ModLocation contains both the original source filename and the
1231 -- filename of the cleaned-up source file after all preprocessing has been
1232 -- done. The point is that the summariser will have to cpp/unlit/whatever
1233 -- all files anyway, and there's no point in doing this twice -- just
1234 -- park the result in a temp file, put the name of it in the location,
1235 -- and let @compile@ read from that file on the way back up.
1238 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1240 emptyMG :: ModuleGraph
1245 ms_mod :: Module, -- name, package
1246 ms_location :: ModLocation, -- location
1247 ms_srcimps :: [ModuleName], -- source imports
1248 ms_imps :: [ModuleName], -- non-source imports
1249 ms_hs_date :: ClockTime -- timestamp of summarised file
1252 instance Outputable ModSummary where
1254 = sep [text "ModSummary {",
1255 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1256 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1257 text "ms_imps =" <+> ppr (ms_imps ms),
1258 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1262 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1264 modSummaryName :: ModSummary -> ModuleName
1265 modSummaryName = moduleName . ms_mod