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 ( ModuleName, moduleName,
21 isHomeModule, moduleEnvElts,
22 moduleNameUserString )
23 import CmStaticInfo ( GhciMode(..) )
26 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
27 PersistentCompilerState, ModDetails(..) )
28 import Name ( lookupNameEnv )
30 import PrelNames ( mainName )
31 import HscMain ( initPersistentCompilerState )
33 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
34 UniqFM, listToUFM, eltsUFM )
35 import Unique ( Uniquable )
36 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
37 import DriverFlags ( getDynFlags )
39 import DriverUtil ( splitFilename3 )
40 import ErrUtils ( showPass )
45 import CmdLineOpts ( DynFlags(..) )
48 import Interpreter ( HValue )
49 import HscMain ( hscExpr )
51 import PrelGHC ( unsafeCoerce# )
55 import Exception ( throwDyn )
58 import Time ( ClockTime )
59 import Directory ( getModificationTime, doesFileExist )
63 import Maybe ( catMaybes, fromMaybe, isJust, maybeToList )
68 cmInit :: GhciMode -> IO CmState
77 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
78 cmGetExpr cmstate dflags modname expr
79 = do (new_pcs, maybe_stuff) <-
80 hscExpr dflags hst hit pcs (mkHomeModule modname) expr
82 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
83 Just (uiexpr, print_unqual, ty) -> do
84 hValue <- linkExpr pls uiexpr
85 return (cmstate{ pcs=new_pcs },
86 Just (hValue, print_unqual, ty))
88 -- ToDo: check that the module we passed in is sane/exists?
90 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
91 PersistentCMState{ hst=hst, hit=hit } = pcms
93 -- The HValue should represent a value of type IO () (Perhaps IO a?)
94 cmRunExpr :: HValue -> IO ()
96 = do unsafeCoerce# hval :: IO ()
100 -- Persistent state just for CM, excluding link & compile subsystems
101 data PersistentCMState
102 = PersistentCMState {
103 hst :: HomeSymbolTable, -- home symbol table
104 hit :: HomeIfaceTable, -- home interface table
105 ui :: UnlinkedImage, -- the unlinked images
106 mg :: ModuleGraph, -- the module graph
107 gmode :: GhciMode -- NEVER CHANGES
110 emptyPCMS :: GhciMode -> PersistentCMState
112 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
113 ui = emptyUI, mg = emptyMG,
116 emptyHIT :: HomeIfaceTable
118 emptyHST :: HomeSymbolTable
123 -- Persistent state for the entire system
126 pcms :: PersistentCMState, -- CM's persistent state
127 pcs :: PersistentCompilerState, -- compile's persistent state
128 pls :: PersistentLinkerState -- link's persistent state
131 emptyCmState :: GhciMode -> IO CmState
133 = do let pcms = emptyPCMS gmode
134 pcs <- initPersistentCompilerState
136 return (CmState { pcms = pcms,
141 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
142 emptyUI :: UnlinkedImage
145 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
146 emptyMG :: ModuleGraph
151 Unload the compilation manager's state: everything it knows about the
152 current collection of modules in the Home package.
155 cmUnload :: CmState -> IO CmState
157 = do -- Throw away the old home dir cache
159 -- Throw away the HIT and the HST
160 return state{ pcms=pcms{ hst=new_hst, hit=new_hit } }
162 CmState{ pcms=pcms } = state
163 PersistentCMState{ hst=hst, hit=hit } = pcms
164 (new_hst, new_hit,[]) = retainInTopLevelEnvs [] (hst,hit,[])
167 The real business of the compilation manager: given a system state and
168 a module name, try and bring the module up to date, probably changing
169 the system state at the same time.
172 cmLoadModule :: CmState
174 -> IO (CmState, -- new state
175 Bool, -- was successful
176 [ModuleName]) -- list of modules loaded
178 cmLoadModule cmstate1 rootname
179 = do -- version 1's are the original, before downsweep
180 let pcms1 = pcms cmstate1
181 let pls1 = pls cmstate1
182 let pcs1 = pcs cmstate1
183 -- mg1 is the complete (home) set of summaries from the
184 -- previous pass of cmLoadModule, if there was one.
188 -- similarly, ui1 is the (complete) set of linkables from
189 -- the previous pass, if any.
192 let ghci_mode = gmode pcms1 -- this never changes
194 -- Do the downsweep to reestablish the module graph
195 -- then generate version 2's by retaining in HIT,HST,UI a
196 -- stable set S of modules, as defined below.
198 dflags <- getDynFlags
199 let verb = verbosity dflags
201 showPass dflags "Chasing dependencies"
202 when (verb >= 1 && ghci_mode == Batch) $
203 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
205 (mg2unsorted, a_root_is_Main) <- downsweep [rootname]
206 let mg2unsorted_names = map name_of_summary mg2unsorted
208 -- reachable_from follows source as well as normal imports
209 let reachable_from :: ModuleName -> [ModuleName]
210 reachable_from = downwards_closure_of_module mg2unsorted
212 -- should be cycle free; ignores 'import source's
213 let mg2 = topological_sort False mg2unsorted
214 -- ... whereas this takes them into account. Used for
215 -- backing out partially complete cycles following a failed
216 -- upsweep, and for removing from hst/hit all the modules
217 -- not in strict downwards closure, during calls to compile.
218 let mg2_with_srcimps = topological_sort True mg2unsorted
220 -- Figure out a stable set of modules which can be retained
221 -- the top level envs, to avoid upsweeping them. Goes to a
222 -- bit of trouble to avoid upsweeping module cycles.
224 -- Construct a set S of stable modules like this:
225 -- Travel upwards, over the sccified graph. For each scc
226 -- of modules ms, add ms to S only if:
227 -- 1. All home imports of ms are either in ms or S
228 -- 2. All m <- ms satisfy P, where
229 -- P | interactive = have old summary for m and it indicates
230 -- that the source is unchanged
231 -- | batch = linkable exists on disk, and is younger
234 (stable_mods, linkables_for_stable_mods)
235 <- preUpsweep ghci_mode ui1 mg1 mg2unsorted_names [] [] mg2_with_srcimps
236 let stable_old_summaries
237 = concatMap (findInSummaries mg1) stable_mods
240 putStrLn (showSDoc (text "STABLE MODULES:"
241 <+> sep (map (text.moduleNameUserString) stable_mods)))
245 = retainInTopLevelEnvs stable_mods (hst1, hit1, [])
247 = linkables_for_stable_mods
249 -- Now hst2, hit2, ui2 now hold the 'reduced system', just the set of
250 -- modules which are stable.
252 -- We could at this point detect cycles which aren't broken by
253 -- a source-import, and complain immediately, but it seems better
254 -- to let upsweep_mods do this, so at least some useful work gets
255 -- done before the upsweep is abandoned.
257 = filter (\scc -> any (`notElem` stable_mods)
258 (map name_of_summary (flattenSCC scc)))
261 --hPutStrLn stderr "after tsort:\n"
262 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
264 -- Because we don't take into account source imports when doing
265 -- the topological sort, there shouldn't be any cycles in mg2.
266 -- If there is, we complain and give up -- the user needs to
267 -- break the cycle using a boot file.
269 -- Now do the upsweep, calling compile for each module in
270 -- turn. Final result is version 3 of everything.
272 let threaded2 = CmThreaded pcs1 hst2 hit2
274 (upsweep_complete_success, threaded3, modsUpswept, newLis)
275 <- upsweep_mods ghci_mode dflags ui2 reachable_from
276 threaded2 upsweep_these
278 let ui3 = add_to_ui ui2 newLis
279 let (CmThreaded pcs3 hst3 hit3) = threaded3
281 -- At this point, modsUpswept and newLis should have the same
282 -- length, so there is one new (or old) linkable for each
283 -- mod which was processed (passed to compile).
285 -- Make modsDone be the summaries for each home module now
286 -- available; this should equal the domains of hst3 and hit3.
287 -- (NOT STRICTLY TRUE if an interactive session was started
288 -- with some object on disk ???)
289 -- Get in in a roughly top .. bottom order (hence reverse).
291 let modsDone = reverse modsUpswept ++ stable_old_summaries
293 -- Try and do linking in some form, depending on whether the
294 -- upsweep was completely or only partially successful.
296 if upsweep_complete_success
299 -- Easy; just relink it all.
300 do when (verb >= 2) $
301 hPutStrLn stderr "Upsweep completely successful."
303 <- link ghci_mode dflags a_root_is_Main ui3 pls1
306 -> panic "cmLoadModule: link failed (1)"
308 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
312 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
313 return (cmstate3, True,
314 map name_of_summary modsDone)
317 -- Tricky. We need to back out the effects of compiling any
318 -- half-done cycles, both so as to clean up the top level envs
319 -- and to avoid telling the interactive linker to link them.
320 do when (verb >= 2) $
321 hPutStrLn stderr "Upsweep partially successful."
324 = map name_of_summary modsDone
325 let mods_to_zap_names
326 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
327 let (hst4, hit4, ui4)
328 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
330 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
331 let mods_to_keep_names
332 = map name_of_summary mods_to_keep
333 -- we could get the relevant linkables by filtering newLis, but
334 -- it seems easier to drag them out of the updated, cleaned-up UI
335 let linkables_to_link
336 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
339 linkresult <- link ghci_mode dflags False linkables_to_link pls1
342 -> panic "cmLoadModule: link failed (2)"
344 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
345 ui=ui4, mg=mods_to_keep,
348 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
349 return (cmstate4, False,
354 -- Do a pre-upsweep without use of "compile", to establish a
355 -- (downward-closed) set of stable modules which can be retained
356 -- in the top-level environments. Also return linkables for those
357 -- modules determined to be stable, since (in Batch mode, at least)
358 -- there's no other way for them to get into UI.
359 preUpsweep :: GhciMode
360 -> [Linkable] -- linkables from previous cmLoadModule pass
361 -- should be [] in batch mode
362 -> [ModSummary] -- summaries from previous cmLoadModule pass
363 -- should be [] in batch mode
364 -> [ModuleName] -- names of all mods encountered in downsweep
365 -> [ModuleName] -- accumulating stable modules
366 -> [Linkable] -- their linkables, in batch mode
367 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
368 -> IO ([ModuleName], [Linkable])
369 -- stable modules and their linkables
371 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis []
372 = return (stable, lis)
373 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis (scc0:sccs)
374 = do let scc = flattenSCC scc0
375 scc_allhomeimps :: [ModuleName]
377 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
378 all_imports_in_scc_or_stable
379 = all in_stable_or_scc scc_allhomeimps
381 = map name_of_summary scc
383 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
384 m `elem` scc_names || m `elem` stable
386 (all_scc_stable, more_lis)
387 <- if not all_imports_in_scc_or_stable
388 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
391 <- mapM (is_stable ghci_mode old_lis old_summaries) scc
392 let (bools, liss) = unzip bools_n_lis
393 --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
394 return (and bools, concat liss)
395 if not all_scc_stable
396 then preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis sccs
397 else preUpsweep ghci_mode old_lis old_summaries all_home_mods
398 (scc_names++stable) (more_lis++lis) sccs
401 -- Helper for preUpsweep. Assuming that new_summary's imports are all
402 -- stable (in the sense of preUpsweep), determine if new_summary is itself
403 -- stable, and, if so, in batch mode, return its linkable.
404 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
405 findInSummaries old_summaries mod_name
406 = [s | s <- old_summaries, name_of_summary s == mod_name]
408 is_stable :: GhciMode
409 -> [Linkable] -> [ModSummary] -- OLD lis and summs, in Interactive mode
410 -> ModSummary -- this module
411 -> IO (Bool, [Linkable])
413 is_stable Interactive old_lis old_summaries new_summary
414 -- Only true if the old summary exists and
415 -- the new source date matches the old one.
416 = case found_old_summarys of
417 [] -> return (False, old_linkable)
419 -> case (ms_hs_date new_summary, ms_hs_date old_summary) of
420 (Just d1, Just d2) -> return (d1 == d2, old_linkable)
421 (_, _ ) -> return (False, old_linkable)
425 (findModuleLinkable_maybe old_lis (name_of_summary new_summary))
427 = findInSummaries old_summaries (name_of_summary new_summary)
429 is_stable Batch [] [] new_summary
430 -- Only true if we can find a linkable, and it is younger than
432 = case ms_hs_date new_summary of
433 Nothing -> return (False, []) -- no source date (?!)
435 -> case ml_obj_file (ms_location new_summary) of
436 Nothing -> return (False, []) -- no obj filename
438 -> do maybe_li <- maybe_getFileLinkable
439 (moduleName (ms_mod new_summary)) fn
441 Nothing -> return (False, []) -- no object file on disk
442 Just li -> return (linkableTime li >= hs_time, [li])
446 -- Return (names of) all those in modsDone who are part of a cycle
447 -- as defined by theGraph.
448 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
449 findPartiallyCompletedCycles modsDone theGraph
453 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
454 chew ((CyclicSCC vs):rest)
455 = let names_in_this_cycle = nub (map name_of_summary vs)
457 = nub ([done | done <- modsDone,
458 done `elem` names_in_this_cycle])
459 chewed_rest = chew rest
461 if not (null mods_in_this_cycle)
462 && length mods_in_this_cycle < length names_in_this_cycle
463 then mods_in_this_cycle ++ chewed_rest
467 -- Does this ModDetails export Main.main?
468 --exports_main :: ModDetails -> Bool
470 -- = isJust (lookupNameEnv (md_types md) mainName)
473 -- Add the given (LM-form) Linkables to the UI, overwriting previous
474 -- versions if they exist.
475 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
479 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
481 = li : filter (\li2 -> not (for_same_module li li2)) ui
483 for_same_module :: Linkable -> Linkable -> Bool
484 for_same_module li1 li2
485 = not (is_package_linkable li1)
486 && not (is_package_linkable li2)
487 && modname_of_linkable li1 == modname_of_linkable li2
490 data CmThreaded -- stuff threaded through individual module compilations
491 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
494 -- Compile multiple modules, stopping as soon as an error appears.
495 -- There better had not be any cyclic groups here -- we check for them.
496 upsweep_mods :: GhciMode
498 -> UnlinkedImage -- old linkables
499 -> (ModuleName -> [ModuleName]) -- to construct downward closures
500 -> CmThreaded -- PCS & HST & HIT
501 -> [SCC ModSummary] -- mods to do (the worklist)
502 -- ...... RETURNING ......
503 -> IO (Bool{-complete success?-},
505 [ModSummary], -- mods which succeeded
506 [Linkable]) -- new linkables
508 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
510 = return (True, threaded, [], [])
512 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
514 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
515 unwords (map (moduleNameUserString.name_of_summary) ms))
516 return (False, threaded, [], [])
518 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
519 ((AcyclicSCC mod):mods)
520 = do --case threaded of
521 -- CmThreaded pcsz hstz hitz
522 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
524 (threaded1, maybe_linkable)
525 <- upsweep_mod ghci_mode dflags oldUI threaded mod
526 (reachable_from (name_of_summary mod))
527 case maybe_linkable of
529 -> -- No errors; do the rest
530 do (restOK, threaded2, modOKs, linkables)
531 <- upsweep_mods ghci_mode dflags oldUI reachable_from
533 return (restOK, threaded2, mod:modOKs, linkable:linkables)
534 Nothing -- we got a compilation error; give up now
535 -> return (False, threaded1, [], [])
538 -- Compile a single module. Always produce a Linkable for it if
539 -- successful. If no compilation happened, return the old Linkable.
540 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
541 maybe_getFileLinkable mod_name obj_fn
542 = do obj_exist <- doesFileExist obj_fn
546 do let stub_fn = case splitFilename3 obj_fn of
547 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
548 stub_exist <- doesFileExist stub_fn
549 obj_time <- getModificationTime obj_fn
551 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
552 else return (Just (LM obj_time mod_name [DotO obj_fn]))
555 upsweep_mod :: GhciMode
561 -> IO (CmThreaded, Maybe Linkable)
563 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
565 let mod_name = name_of_summary summary1
566 let verb = verbosity dflags
569 if (ghci_mode == Batch)
570 then hPutStr stderr (progName ++ ": module "
571 ++ moduleNameUserString mod_name
573 else hPutStr stderr ("Compiling "
574 ++ moduleNameUserString mod_name
577 let (CmThreaded pcs1 hst1 hit1) = threaded1
578 let old_iface = lookupUFM hit1 mod_name
580 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
581 maybe_oldDisk_linkable
582 <- case ml_obj_file (ms_location summary1) of
583 Nothing -> return Nothing
584 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
586 -- The most recent of the old UI linkable or whatever we could
587 -- find on disk. Is returned as the linkable if compile
588 -- doesn't think we need to recompile.
589 let maybe_old_linkable
590 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
591 (Nothing, Nothing) -> Nothing
592 (Nothing, Just di) -> Just di
593 (Just ui, Nothing) -> Just ui
595 | linkableTime ui >= linkableTime di -> Just ui
596 | otherwise -> Just di
598 let compilation_mandatory
599 = case maybe_old_linkable of
601 Just li -> case ms_hs_date summary1 of
602 Nothing -> panic "compilation_mandatory:no src date"
603 Just src_date -> src_date >= linkableTime li
605 = not compilation_mandatory
607 (hst1_strictDC, hit1_strictDC, [])
608 = retainInTopLevelEnvs
609 (filter (/= (name_of_summary summary1)) reachable_from_here)
613 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
615 compresult <- compile ghci_mode summary1 source_unchanged
616 old_iface hst1_strictDC hit1_strictDC pcs1
620 -- Compilation "succeeded", but didn't return a new
621 -- linkable, meaning that compilation wasn't needed, and the
622 -- new details were manufactured from the old iface.
623 CompOK pcs2 new_details new_iface Nothing
624 -> do let hst2 = addToUFM hst1 mod_name new_details
625 hit2 = addToUFM hit1 mod_name new_iface
626 threaded2 = CmThreaded pcs2 hst2 hit2
628 if ghci_mode == Interactive && verb >= 1 then
629 -- if we're using an object file, tell the user
630 case maybe_old_linkable of
631 Just (LM _ _ objs@(DotO _:_))
632 -> do hPutStr stderr (showSDoc (space <>
633 parens (hsep (text "using":
635 [ text o | DotO o <- objs ]))))
636 when (verb > 1) $ hPutStrLn stderr ""
641 when (verb == 1) $ hPutStrLn stderr ""
642 return (threaded2, Just old_linkable)
644 -- Compilation really did happen, and succeeded. A new
645 -- details, iface and linkable are returned.
646 CompOK pcs2 new_details new_iface (Just new_linkable)
647 -> do let hst2 = addToUFM hst1 mod_name new_details
648 hit2 = addToUFM hit1 mod_name new_iface
649 threaded2 = CmThreaded pcs2 hst2 hit2
651 when (verb == 1) $ hPutStrLn stderr ""
652 return (threaded2, Just new_linkable)
654 -- Compilation failed. compile may still have updated
657 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
658 when (verb == 1) $ hPutStrLn stderr ""
659 return (threaded2, Nothing)
661 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
662 removeFromTopLevelEnvs :: [ModuleName]
663 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
664 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
665 removeFromTopLevelEnvs zap_these (hst, hit, ui)
666 = (delListFromUFM hst zap_these,
667 delListFromUFM hit zap_these,
668 filterModuleLinkables (`notElem` zap_these) ui
671 retainInTopLevelEnvs :: [ModuleName]
672 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
673 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
674 retainInTopLevelEnvs keep_these (hst, hit, ui)
675 = (retainInUFM hst keep_these,
676 retainInUFM hit keep_these,
677 filterModuleLinkables (`elem` keep_these) ui
680 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
681 retainInUFM ufm keys_to_keep
682 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
684 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
686 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
687 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
688 downwards_closure_of_module summaries root
689 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
690 toEdge summ = (name_of_summary summ, ms_allimps summ)
691 res = simple_transitive_closure (map toEdge summaries) [root]
693 --trace (showSDoc (text "DC of mod" <+> ppr root
694 -- <+> text "=" <+> ppr res)) (
698 -- Calculate transitive closures from a set of roots given an adjacency list
699 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
700 simple_transitive_closure graph set
701 = let set2 = nub (concatMap dsts set ++ set)
702 dsts node = fromMaybe [] (lookup node graph)
704 if length set == length set2
706 else simple_transitive_closure graph set2
709 -- Calculate SCCs of the module graph, with or without taking into
710 -- account source imports.
711 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
712 topological_sort include_source_imports summaries
714 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
716 = (summ, name_of_summary summ,
717 (if include_source_imports
718 then ms_srcimps summ else []) ++ ms_imps summ)
720 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
721 mash_edge (summ, m, m_imports)
722 = case lookup m key_map of
723 Nothing -> panic "reverse_topological_sort"
724 Just mk -> (summ, mk,
725 -- ignore imports not from the home package
726 catMaybes (map (flip lookup key_map) m_imports))
728 edges = map toEdge summaries
729 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
730 scc_input = map mash_edge edges
731 sccs = stronglyConnComp scc_input
736 -- Chase downwards from the specified root set, returning summaries
737 -- for all home modules encountered. Only follow source-import
738 -- links. Also returns a Bool to indicate whether any of the roots
740 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
742 = do rootSummaries <- mapM getRootSummary rootNm
744 = any ((=="Main").moduleNameUserString.name_of_summary)
747 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
748 return (all_summaries, a_root_is_Main)
750 getRootSummary :: FilePath -> IO ModSummary
752 | haskellish_file file
753 = do exists <- doesFileExist file
754 if exists then summariseFile file else do
755 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
757 = do exists <- doesFileExist hs_file
758 if exists then summariseFile hs_file else do
759 exists <- doesFileExist lhs_file
760 if exists then summariseFile lhs_file else do
761 getSummary (mkModuleName file)
763 hs_file = file ++ ".hs"
764 lhs_file = file ++ ".lhs"
766 getSummary :: ModuleName -> IO ModSummary
768 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
769 = do found <- findModule nm
771 -- Be sure not to use the mod and location passed in to
772 -- summarise for any other purpose -- summarise may change
773 -- the module names in them if name of module /= name of file,
774 -- and put the changed versions in the returned summary.
775 -- These will then conflict with the passed-in versions.
776 Just (mod, location) -> summarise mod location
777 Nothing -> throwDyn (OtherError
778 ("can't find module `"
779 ++ showSDoc (ppr nm) ++ "'"))
781 -- loop invariant: homeSummaries doesn't contain package modules
782 loop :: [ModSummary] -> IO [ModSummary]
784 = do let allImps :: [ModuleName]
785 allImps = (nub . concatMap ms_imps) homeSummaries
786 let allHome -- all modules currently in homeSummaries
787 = map (moduleName.ms_mod) homeSummaries
789 = filter (`notElem` allHome) allImps
791 <- mapM getSummary neededImps
793 = filter (isHomeModule.ms_mod) neededSummaries
794 if null newHomeSummaries
795 then return homeSummaries
796 else loop (newHomeSummaries ++ homeSummaries)
799 -----------------------------------------------------------------------------
800 -- Summarising modules
802 -- We have two types of summarisation:
804 -- * Summarise a file. This is used for the root module passed to
805 -- cmLoadModule. The file is read, and used to determine the root
806 -- module name. The module name may differ from the filename.
808 -- * Summarise a module. We are given a module name, and must provide
809 -- a summary. The finder is used to locate the file in which the module
812 summariseFile :: FilePath -> IO ModSummary
814 = do hspp_fn <- preprocess file
815 modsrc <- readFile hspp_fn
817 let (srcimps,imps,mod_name) = getImports modsrc
818 (path, basename, ext) = splitFilename3 file
821 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
824 <- case ml_hs_file location of
825 Nothing -> return Nothing
826 Just src_fn -> maybe_getModificationTime src_fn
828 return (ModSummary mod
829 location{ml_hspp_file=Just hspp_fn}
833 -- Summarise a module, and pick up source and interface timestamps.
834 summarise :: Module -> ModuleLocation -> IO ModSummary
835 summarise mod location
837 = do let hs_fn = unJust "summarise" (ml_hs_file location)
838 hspp_fn <- preprocess hs_fn
839 modsrc <- readFile hspp_fn
840 let (srcimps,imps,mod_name) = getImports modsrc
843 <- case ml_hs_file location of
844 Nothing -> return Nothing
845 Just src_fn -> maybe_getModificationTime src_fn
847 if mod_name == moduleName mod
849 else throwDyn (OtherError
850 (showSDoc (text "file name does not match module name: "
851 <+> ppr (moduleName mod) <+> text "vs"
854 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
859 = return (ModSummary mod location [] [] Nothing)
861 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
862 maybe_getModificationTime fn
863 = (do time <- getModificationTime fn
866 (\err -> return Nothing)