2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule, cmUnload,
11 CmState, emptyCmState -- abstract
15 #include "HsVersions.h"
20 import Module ( Module, ModuleName, moduleName, isHomeModule,
21 mkModuleName, moduleNameUserString )
22 import CmStaticInfo ( GhciMode(..) )
25 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
26 PersistentCompilerState, ModDetails(..) )
27 import HscMain ( initPersistentCompilerState )
29 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
31 import Unique ( Uniquable )
32 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
33 import DriverFlags ( getDynFlags )
35 import DriverUtil ( splitFilename3 )
36 import ErrUtils ( showPass )
41 import CmdLineOpts ( DynFlags(..) )
45 import Interpreter ( HValue )
46 import HscMain ( hscExpr )
48 import PrelGHC ( unsafeCoerce# )
52 import Exception ( throwDyn )
55 import Time ( ClockTime )
56 import Directory ( getModificationTime, doesFileExist )
60 import Maybe ( catMaybes, fromMaybe, isJust, fromJust )
65 cmInit :: GhciMode -> IO CmState
72 -> Bool -- True <=> wrap in 'print' to get an IO-typed result
75 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
76 cmGetExpr cmstate dflags wrap_io mod expr
77 = do (new_pcs, maybe_stuff) <-
78 hscExpr dflags wrap_io hst hit pcs mod expr
80 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
81 Just (bcos, print_unqual, ty) -> do
82 hValue <- linkExpr pls bcos
83 return (cmstate{ pcs=new_pcs },
84 Just (hValue, print_unqual, ty))
86 -- ToDo: check that the module we passed in is sane/exists?
88 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
90 -- The HValue should represent a value of type IO () (Perhaps IO a?)
91 cmRunExpr :: HValue -> IO ()
93 = do unsafeCoerce# hval :: IO ()
97 emptyHIT :: HomeIfaceTable
99 emptyHST :: HomeSymbolTable
102 -- Persistent state for the entire system
105 hst :: HomeSymbolTable, -- home symbol table
106 hit :: HomeIfaceTable, -- home interface table
107 ui :: UnlinkedImage, -- the unlinked images
108 mg :: ModuleGraph, -- the module graph
109 gmode :: GhciMode, -- NEVER CHANGES
111 pcs :: PersistentCompilerState, -- compile's persistent state
112 pls :: PersistentLinkerState -- link's persistent state
115 emptyCmState :: GhciMode -> IO CmState
117 = do pcs <- initPersistentCompilerState
119 return (CmState { hst = emptyHST,
128 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
129 emptyUI :: UnlinkedImage
132 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
133 emptyMG :: ModuleGraph
138 Unload the compilation manager's state: everything it knows about the
139 current collection of modules in the Home package.
142 cmUnload :: CmState -> IO CmState
144 = do -- Throw away the old home dir cache
146 -- Throw away the HIT and the HST
147 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
149 CmState{ hst=hst, hit=hit } = state
150 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
153 The real business of the compilation manager: given a system state and
154 a module name, try and bring the module up to date, probably changing
155 the system state at the same time.
158 cmLoadModule :: CmState
160 -> IO (CmState, -- new state
161 Bool, -- was successful
162 [Module]) -- list of modules loaded
164 cmLoadModule cmstate1 rootname
165 = do -- version 1's are the original, before downsweep
166 let pls1 = pls cmstate1
167 let pcs1 = pcs cmstate1
168 let hst1 = hst cmstate1
169 let hit1 = hit cmstate1
170 -- similarly, ui1 is the (complete) set of linkables from
171 -- the previous pass, if any.
172 let ui1 = ui cmstate1
173 let mg1 = mg cmstate1
175 let ghci_mode = gmode cmstate1 -- this never changes
177 -- Do the downsweep to reestablish the module graph
178 -- then generate version 2's by retaining in HIT,HST,UI a
179 -- stable set S of modules, as defined below.
181 dflags <- getDynFlags
182 let verb = verbosity dflags
184 showPass dflags "Chasing dependencies"
185 when (verb >= 1 && ghci_mode == Batch) $
186 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
188 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
189 let mg2unsorted_names = map name_of_summary mg2unsorted
191 -- reachable_from follows source as well as normal imports
192 let reachable_from :: ModuleName -> [ModuleName]
193 reachable_from = downwards_closure_of_module mg2unsorted
195 -- should be cycle free; ignores 'import source's
196 let mg2 = topological_sort False mg2unsorted
197 -- ... whereas this takes them into account. Used for
198 -- backing out partially complete cycles following a failed
199 -- upsweep, and for removing from hst/hit all the modules
200 -- not in strict downwards closure, during calls to compile.
201 let mg2_with_srcimps = topological_sort True mg2unsorted
203 -- Sort out which linkables we wish to keep in the unlinked image.
204 -- For each module, we take:
206 -- - the old in-core linkable, if available
207 -- - an on-disk linkable, if available
209 -- and we take the youngest of these, provided it is younger than the
212 -- If a module has a valid linkable, then it may be STABLE (see below),
213 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
215 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
218 -- Figure out a stable set of modules which can be retained
219 -- the top level envs, to avoid upsweeping them. Goes to a
220 -- bit of trouble to avoid upsweeping module cycles.
222 -- Construct a set S of stable modules like this:
223 -- Travel upwards, over the sccified graph. For each scc
224 -- of modules ms, add ms to S only if:
225 -- 1. All home imports of ms are either in ms or S
226 -- 2. A valid linkable exists for each module in ms
229 <- preUpsweep valid_linkables ui1 mg2unsorted_names
233 = concatMap (findInSummaries mg2unsorted) stable_mods
236 = filter (\m -> linkableModName m `elem` stable_mods)
240 putStrLn (showSDoc (text "STABLE MODULES:"
241 <+> sep (map (text.moduleNameUserString) stable_mods)))
243 -- unload any modules which aren't going to be re-linked this
245 pls2 <- unload ghci_mode dflags stable_linkables pls1
247 -- We could at this point detect cycles which aren't broken by
248 -- a source-import, and complain immediately, but it seems better
249 -- to let upsweep_mods do this, so at least some useful work gets
250 -- done before the upsweep is abandoned.
252 = filter (\scc -> any (`notElem` stable_mods)
253 (map name_of_summary (flattenSCC scc)))
256 --hPutStrLn stderr "after tsort:\n"
257 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
259 -- Because we don't take into account source imports when doing
260 -- the topological sort, there shouldn't be any cycles in mg2.
261 -- If there is, we complain and give up -- the user needs to
262 -- break the cycle using a boot file.
264 -- Now do the upsweep, calling compile for each module in
265 -- turn. Final result is version 3 of everything.
267 let threaded2 = CmThreaded pcs1 hst1 hit1
269 (upsweep_complete_success, threaded3, modsUpswept, newLis)
270 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
271 threaded2 upsweep_these
273 let ui3 = add_to_ui valid_linkables newLis
274 let (CmThreaded pcs3 hst3 hit3) = threaded3
276 -- At this point, modsUpswept and newLis should have the same
277 -- length, so there is one new (or old) linkable for each
278 -- mod which was processed (passed to compile).
280 -- Make modsDone be the summaries for each home module now
281 -- available; this should equal the domains of hst3 and hit3.
282 -- (NOT STRICTLY TRUE if an interactive session was started
283 -- with some object on disk ???)
284 -- Get in in a roughly top .. bottom order (hence reverse).
286 let modsDone = reverse modsUpswept ++ stable_summaries
288 -- Try and do linking in some form, depending on whether the
289 -- upsweep was completely or only partially successful.
291 if upsweep_complete_success
294 -- Easy; just relink it all.
295 do when (verb >= 2) $
296 hPutStrLn stderr "Upsweep completely successful."
298 <- link ghci_mode dflags a_root_is_Main ui3 pls2
301 -> panic "cmLoadModule: link failed (1)"
304 = CmState { hst=hst3, hit=hit3,
308 return (cmstate3, True,
312 -- Tricky. We need to back out the effects of compiling any
313 -- half-done cycles, both so as to clean up the top level envs
314 -- and to avoid telling the interactive linker to link them.
315 do when (verb >= 2) $
316 hPutStrLn stderr "Upsweep partially successful."
319 = map name_of_summary modsDone
320 let mods_to_zap_names
321 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
322 let (hst4, hit4, ui4)
323 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
325 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
326 let mods_to_keep_names
327 = map name_of_summary mods_to_keep
328 -- we could get the relevant linkables by filtering newLis, but
329 -- it seems easier to drag them out of the updated, cleaned-up UI
330 let linkables_to_link
331 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
334 linkresult <- link ghci_mode dflags False linkables_to_link pls2
337 -> panic "cmLoadModule: link failed (2)"
340 = CmState { hst=hst4, hit=hit4,
341 ui=ui4, mg=mods_to_keep,
342 gmode=ghci_mode, pcs=pcs3, pls=pls3 }
343 return (cmstate4, False,
344 map ms_mod mods_to_keep)
347 -----------------------------------------------------------------------------
351 :: [Linkable] -- old linkables
352 -> [ModuleName] -- all home modules
353 -> [SCC ModSummary] -- all modules in the program, dependency order
354 -> IO [Linkable] -- still-valid linkables
356 getValidLinkables old_linkables all_home_mods module_graph
357 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
359 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
361 scc = flattenSCC scc0
362 scc_names = map name_of_summary scc
363 home_module m = m `elem` all_home_mods && m `notElem` scc_names
364 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
366 has_object m = case findModuleLinkable_maybe new_linkables m of
368 Just l -> isObjectLinkable l
370 objects_allowed = all has_object scc_allhomeimps
374 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
376 -- since an scc can contain only all objects or no objects at all,
377 -- we have to check whether we got all objects or not, and re-do
378 -- the linkable check if not.
380 <- if objects_allowed && not (all isObjectLinkable these_linkables)
381 then foldM (getValidLinkable old_linkables False) [] scc
382 else return these_linkables
384 return (adjusted_linkables ++ new_linkables)
387 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
389 getValidLinkable old_linkables objects_allowed new_linkables summary
391 let mod_name = name_of_summary summary
394 <- if (not objects_allowed)
396 else case ml_obj_file (ms_location summary) of
397 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
398 Nothing -> return Nothing
400 -- find an old in-core linkable if we have one. (forget about
401 -- on-disk linkables for now, we'll check again whether there's
402 -- one here below, just in case a new one has popped up recently).
403 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
406 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
409 -- The most recent of the old UI linkable or whatever we could
410 -- find on disk is returned as the linkable if compile
411 -- doesn't think we need to recompile.
413 = case (maybe_old_linkable, maybe_disk_linkable) of
414 (Nothing, Nothing) -> []
415 (Nothing, Just di) -> [di]
416 (Just ui, Nothing) -> [ui]
418 | linkableTime ui >= linkableTime di -> [ui]
421 -- only linkables newer than the source code are valid
422 let maybe_src_date = ms_hs_date summary
425 = case maybe_src_date of
426 Nothing -> panic "valid_linkable_list"
428 -> filter (\li -> linkableTime li > src_date) linkable_list
430 return (valid_linkable_list ++ new_linkables)
433 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
434 maybe_getFileLinkable mod_name obj_fn
435 = do obj_exist <- doesFileExist obj_fn
439 do let stub_fn = case splitFilename3 obj_fn of
440 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
441 stub_exist <- doesFileExist stub_fn
442 obj_time <- getModificationTime obj_fn
444 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
445 else return (Just (LM obj_time mod_name [DotO obj_fn]))
448 -----------------------------------------------------------------------------
449 -- Do a pre-upsweep without use of "compile", to establish a
450 -- (downward-closed) set of stable modules for which we won't call compile.
452 preUpsweep :: [Linkable] -- new valid linkables
453 -> [Linkable] -- old linkables
454 -> [ModuleName] -- names of all mods encountered in downsweep
455 -> [ModuleName] -- accumulating stable modules
456 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
457 -> IO [ModuleName] -- stable modules
459 preUpsweep valid_lis old_lis all_home_mods stable []
461 preUpsweep valid_lis old_lis all_home_mods stable (scc0:sccs)
462 = do let scc = flattenSCC scc0
463 scc_allhomeimps :: [ModuleName]
465 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
466 all_imports_in_scc_or_stable
467 = all in_stable_or_scc scc_allhomeimps
469 = map name_of_summary scc
471 = m `elem` scc_names || m `elem` stable
473 -- now we check for valid linkables: each module in the SCC must
474 -- have a valid linkable (see getValidLinkables above), and the
475 -- newest linkable must be the same as the previous linkable for
476 -- this module (if one exists).
477 has_valid_linkable new_summary
478 = case findModuleLinkable_maybe valid_lis modname of
480 Just l -> case findModuleLinkable_maybe old_lis modname of
482 Just m -> linkableTime l == linkableTime m
483 where modname = name_of_summary new_summary
485 scc_is_stable = all_imports_in_scc_or_stable
486 && all has_valid_linkable scc
489 then preUpsweep valid_lis old_lis all_home_mods
490 (scc_names++stable) sccs
491 else preUpsweep valid_lis old_lis all_home_mods
497 -- Helper for preUpsweep. Assuming that new_summary's imports are all
498 -- stable (in the sense of preUpsweep), determine if new_summary is itself
499 -- stable, and, if so, in batch mode, return its linkable.
500 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
501 findInSummaries old_summaries mod_name
502 = [s | s <- old_summaries, name_of_summary s == mod_name]
504 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
505 findModInSummaries old_summaries mod
506 = case [s | s <- old_summaries, ms_mod s == mod] of
510 -- Return (names of) all those in modsDone who are part of a cycle
511 -- as defined by theGraph.
512 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
513 findPartiallyCompletedCycles modsDone theGraph
517 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
518 chew ((CyclicSCC vs):rest)
519 = let names_in_this_cycle = nub (map name_of_summary vs)
521 = nub ([done | done <- modsDone,
522 done `elem` names_in_this_cycle])
523 chewed_rest = chew rest
525 if not (null mods_in_this_cycle)
526 && length mods_in_this_cycle < length names_in_this_cycle
527 then mods_in_this_cycle ++ chewed_rest
531 -- Add the given (LM-form) Linkables to the UI, overwriting previous
532 -- versions if they exist.
533 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
535 = filter (not_in lis) ui ++ lis
537 not_in :: [Linkable] -> Linkable -> Bool
539 = all (\l -> linkableModName l /= mod) lis
540 where mod = linkableModName li
543 data CmThreaded -- stuff threaded through individual module compilations
544 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
547 -- Compile multiple modules, stopping as soon as an error appears.
548 -- There better had not be any cyclic groups here -- we check for them.
549 upsweep_mods :: GhciMode
551 -> UnlinkedImage -- valid linkables
552 -> (ModuleName -> [ModuleName]) -- to construct downward closures
553 -> CmThreaded -- PCS & HST & HIT
554 -> [SCC ModSummary] -- mods to do (the worklist)
555 -- ...... RETURNING ......
556 -> IO (Bool{-complete success?-},
558 [ModSummary], -- mods which succeeded
559 [Linkable]) -- new linkables
561 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
563 = return (True, threaded, [], [])
565 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
567 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
568 unwords (map (moduleNameUserString.name_of_summary) ms))
569 return (False, threaded, [], [])
571 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
572 ((AcyclicSCC mod):mods)
573 = do --case threaded of
574 -- CmThreaded pcsz hstz hitz
575 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
577 (threaded1, maybe_linkable)
578 <- upsweep_mod ghci_mode dflags oldUI threaded mod
579 (reachable_from (name_of_summary mod))
580 case maybe_linkable of
582 -> -- No errors; do the rest
583 do (restOK, threaded2, modOKs, linkables)
584 <- upsweep_mods ghci_mode dflags oldUI reachable_from
586 return (restOK, threaded2, mod:modOKs, linkable:linkables)
587 Nothing -- we got a compilation error; give up now
588 -> return (False, threaded1, [], [])
591 -- Compile a single module. Always produce a Linkable for it if
592 -- successful. If no compilation happened, return the old Linkable.
593 upsweep_mod :: GhciMode
599 -> IO (CmThreaded, Maybe Linkable)
601 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
603 let mod_name = name_of_summary summary1
604 let verb = verbosity dflags
607 if (ghci_mode == Batch)
608 then hPutStr stderr (progName ++ ": module "
609 ++ moduleNameUserString mod_name
611 else hPutStr stderr ("Compiling "
612 ++ moduleNameUserString mod_name
615 let (CmThreaded pcs1 hst1 hit1) = threaded1
616 let old_iface = lookupUFM hit1 mod_name
618 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
620 source_unchanged = isJust maybe_old_linkable
622 (hst1_strictDC, hit1_strictDC)
623 = retainInTopLevelEnvs
624 (filter (/= (name_of_summary summary1)) reachable_from_here)
628 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
630 compresult <- compile ghci_mode summary1 source_unchanged
631 old_iface hst1_strictDC hit1_strictDC pcs1
635 -- Compilation "succeeded", but didn't return a new
636 -- linkable, meaning that compilation wasn't needed, and the
637 -- new details were manufactured from the old iface.
638 CompOK pcs2 new_details new_iface Nothing
639 -> do let hst2 = addToUFM hst1 mod_name new_details
640 hit2 = addToUFM hit1 mod_name new_iface
641 threaded2 = CmThreaded pcs2 hst2 hit2
643 if ghci_mode == Interactive && verb >= 1 then
644 -- if we're using an object file, tell the user
646 (LM _ _ objs@(DotO _:_))
647 -> do hPutStrLn stderr (showSDoc (space <>
648 parens (hsep (text "using":
650 [ text o | DotO o <- objs ]))))
655 return (threaded2, Just old_linkable)
657 -- Compilation really did happen, and succeeded. A new
658 -- details, iface and linkable are returned.
659 CompOK pcs2 new_details new_iface (Just new_linkable)
660 -> do let hst2 = addToUFM hst1 mod_name new_details
661 hit2 = addToUFM hit1 mod_name new_iface
662 threaded2 = CmThreaded pcs2 hst2 hit2
664 return (threaded2, Just new_linkable)
666 -- Compilation failed. compile may still have updated
669 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
670 return (threaded2, Nothing)
672 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
673 removeFromTopLevelEnvs :: [ModuleName]
674 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
675 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
676 removeFromTopLevelEnvs zap_these (hst, hit, ui)
677 = (delListFromUFM hst zap_these,
678 delListFromUFM hit zap_these,
679 filterModuleLinkables (`notElem` zap_these) ui
682 retainInTopLevelEnvs :: [ModuleName]
683 -> (HomeSymbolTable, HomeIfaceTable)
684 -> (HomeSymbolTable, HomeIfaceTable)
685 retainInTopLevelEnvs keep_these (hst, hit)
686 = (retainInUFM hst keep_these,
687 retainInUFM hit keep_these
690 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
691 retainInUFM ufm keys_to_keep
692 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
694 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
696 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
697 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
698 downwards_closure_of_module summaries root
699 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
700 toEdge summ = (name_of_summary summ, ms_allimps summ)
701 res = simple_transitive_closure (map toEdge summaries) [root]
703 --trace (showSDoc (text "DC of mod" <+> ppr root
704 -- <+> text "=" <+> ppr res)) (
708 -- Calculate transitive closures from a set of roots given an adjacency list
709 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
710 simple_transitive_closure graph set
711 = let set2 = nub (concatMap dsts set ++ set)
712 dsts node = fromMaybe [] (lookup node graph)
714 if length set == length set2
716 else simple_transitive_closure graph set2
719 -- Calculate SCCs of the module graph, with or without taking into
720 -- account source imports.
721 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
722 topological_sort include_source_imports summaries
724 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
726 = (summ, name_of_summary summ,
727 (if include_source_imports
728 then ms_srcimps summ else []) ++ ms_imps summ)
730 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
731 mash_edge (summ, m, m_imports)
732 = case lookup m key_map of
733 Nothing -> panic "reverse_topological_sort"
734 Just mk -> (summ, mk,
735 -- ignore imports not from the home package
736 catMaybes (map (flip lookup key_map) m_imports))
738 edges = map toEdge summaries
739 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
740 scc_input = map mash_edge edges
741 sccs = stronglyConnComp scc_input
746 -- Chase downwards from the specified root set, returning summaries
747 -- for all home modules encountered. Only follow source-import
748 -- links. Also returns a Bool to indicate whether any of the roots
750 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
751 downsweep rootNm old_summaries
752 = do rootSummaries <- mapM getRootSummary rootNm
754 = any ((=="Main").moduleNameUserString.name_of_summary)
757 <- loop (concat (map ms_imps rootSummaries))
758 (filter (isHomeModule.ms_mod) rootSummaries)
759 return (all_summaries, a_root_is_Main)
761 getRootSummary :: FilePath -> IO ModSummary
763 | haskellish_file file
764 = do exists <- doesFileExist file
765 if exists then summariseFile file else do
766 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
768 = do exists <- doesFileExist hs_file
769 if exists then summariseFile hs_file else do
770 exists <- doesFileExist lhs_file
771 if exists then summariseFile lhs_file else do
772 getSummary (mkModuleName file)
774 hs_file = file ++ ".hs"
775 lhs_file = file ++ ".lhs"
777 getSummary :: ModuleName -> IO ModSummary
779 = do found <- findModule nm
781 Just (mod, location) -> do
782 let old_summary = findModInSummaries old_summaries mod
783 new_summary <- summarise mod location old_summary
785 Nothing -> return (fromJust old_summary)
788 Nothing -> throwDyn (OtherError
789 ("can't find module `"
790 ++ showSDoc (ppr nm) ++ "'"))
792 -- loop invariant: home_summaries doesn't contain package modules
793 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
794 loop [] home_summaries = return home_summaries
795 loop imps home_summaries
796 = do -- all modules currently in homeSummaries
797 let all_home = map (moduleName.ms_mod) home_summaries
799 -- imports for modules we don't already have
800 let needed_imps = filter (`notElem` all_home) imps
803 needed_summaries <- mapM getSummary needed_imps
805 -- get just the "home" modules
806 let new_home_summaries
807 = filter (isHomeModule.ms_mod) needed_summaries
809 -- loop, checking the new imports
810 let new_imps = concat (map ms_imps new_home_summaries)
811 loop new_imps (new_home_summaries ++ home_summaries)
813 -----------------------------------------------------------------------------
814 -- Summarising modules
816 -- We have two types of summarisation:
818 -- * Summarise a file. This is used for the root module passed to
819 -- cmLoadModule. The file is read, and used to determine the root
820 -- module name. The module name may differ from the filename.
822 -- * Summarise a module. We are given a module name, and must provide
823 -- a summary. The finder is used to locate the file in which the module
826 summariseFile :: FilePath -> IO ModSummary
828 = do hspp_fn <- preprocess file
829 modsrc <- readFile hspp_fn
831 let (srcimps,imps,mod_name) = getImports modsrc
832 (path, basename, ext) = splitFilename3 file
835 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
838 <- case ml_hs_file location of
839 Nothing -> return Nothing
840 Just src_fn -> maybe_getModificationTime src_fn
842 return (ModSummary mod
843 location{ml_hspp_file=Just hspp_fn}
847 -- Summarise a module, and pick up source and timestamp.
848 summarise :: Module -> ModuleLocation -> Maybe ModSummary
849 -> IO (Maybe ModSummary)
850 summarise mod location old_summary
852 = do let hs_fn = unJust "summarise" (ml_hs_file location)
855 <- case ml_hs_file location of
856 Nothing -> return Nothing
857 Just src_fn -> maybe_getModificationTime src_fn
859 -- return the cached summary if the source didn't change
860 case old_summary of {
861 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
864 hspp_fn <- preprocess hs_fn
865 modsrc <- readFile hspp_fn
866 let (srcimps,imps,mod_name) = getImports modsrc
869 <- case ml_hs_file location of
870 Nothing -> return Nothing
871 Just src_fn -> maybe_getModificationTime src_fn
873 when (mod_name /= moduleName mod) $
875 (showSDoc (text "file name does not match module name: "
876 <+> ppr (moduleName mod) <+> text "vs"
879 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
881 maybe_src_timestamp))
885 = return (Just (ModSummary mod location [] [] Nothing))
887 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
888 maybe_getModificationTime fn
889 = (do time <- getModificationTime fn
892 (\err -> return Nothing)