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 mkHomeModule, 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(..) )
44 import Interpreter ( HValue )
45 import HscMain ( hscExpr )
47 import PrelGHC ( unsafeCoerce# )
51 import Exception ( throwDyn )
54 import Time ( ClockTime )
55 import Directory ( getModificationTime, doesFileExist )
59 import Maybe ( catMaybes, fromMaybe, maybeToList )
64 cmInit :: GhciMode -> IO CmState
73 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
74 cmGetExpr cmstate dflags modname expr
75 = do (new_pcs, maybe_stuff) <-
76 hscExpr dflags hst hit pcs (mkHomeModule modname) expr
78 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
79 Just (bcos, print_unqual, ty) -> do
80 hValue <- linkExpr pls bcos
81 return (cmstate{ pcs=new_pcs },
82 Just (hValue, print_unqual, ty))
84 -- ToDo: check that the module we passed in is sane/exists?
86 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
87 PersistentCMState{ hst=hst, hit=hit } = pcms
89 -- The HValue should represent a value of type IO () (Perhaps IO a?)
90 cmRunExpr :: HValue -> IO ()
92 = do unsafeCoerce# hval :: IO ()
96 -- Persistent state just for CM, excluding link & compile subsystems
97 data PersistentCMState
99 hst :: HomeSymbolTable, -- home symbol table
100 hit :: HomeIfaceTable, -- home interface table
101 ui :: UnlinkedImage, -- the unlinked images
102 mg :: ModuleGraph, -- the module graph
103 gmode :: GhciMode -- NEVER CHANGES
106 emptyPCMS :: GhciMode -> PersistentCMState
108 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
109 ui = emptyUI, mg = emptyMG,
112 emptyHIT :: HomeIfaceTable
114 emptyHST :: HomeSymbolTable
119 -- Persistent state for the entire system
122 pcms :: PersistentCMState, -- CM's persistent state
123 pcs :: PersistentCompilerState, -- compile's persistent state
124 pls :: PersistentLinkerState -- link's persistent state
127 emptyCmState :: GhciMode -> IO CmState
129 = do let pcms = emptyPCMS gmode
130 pcs <- initPersistentCompilerState
132 return (CmState { pcms = pcms,
137 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
138 emptyUI :: UnlinkedImage
141 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
142 emptyMG :: ModuleGraph
147 Unload the compilation manager's state: everything it knows about the
148 current collection of modules in the Home package.
151 cmUnload :: CmState -> IO CmState
153 = do -- Throw away the old home dir cache
155 -- Throw away the HIT and the HST
156 return state{ pcms=pcms{ hst=new_hst, hit=new_hit } }
158 CmState{ pcms=pcms } = state
159 PersistentCMState{ hst=hst, hit=hit } = pcms
160 (new_hst, new_hit,[]) = retainInTopLevelEnvs [] (hst,hit,[])
163 The real business of the compilation manager: given a system state and
164 a module name, try and bring the module up to date, probably changing
165 the system state at the same time.
168 cmLoadModule :: CmState
170 -> IO (CmState, -- new state
171 Bool, -- was successful
172 [ModuleName]) -- list of modules loaded
174 cmLoadModule cmstate1 rootname
175 = do -- version 1's are the original, before downsweep
176 let pcms1 = pcms cmstate1
177 let pls1 = pls cmstate1
178 let pcs1 = pcs cmstate1
179 -- mg1 is the complete (home) set of summaries from the
180 -- previous pass of cmLoadModule, if there was one.
184 -- similarly, ui1 is the (complete) set of linkables from
185 -- the previous pass, if any.
188 let ghci_mode = gmode pcms1 -- this never changes
190 -- Do the downsweep to reestablish the module graph
191 -- then generate version 2's by retaining in HIT,HST,UI a
192 -- stable set S of modules, as defined below.
194 dflags <- getDynFlags
195 let verb = verbosity dflags
197 showPass dflags "Chasing dependencies"
198 when (verb >= 1 && ghci_mode == Batch) $
199 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
201 (mg2unsorted, a_root_is_Main) <- downsweep [rootname]
202 let mg2unsorted_names = map name_of_summary mg2unsorted
204 -- reachable_from follows source as well as normal imports
205 let reachable_from :: ModuleName -> [ModuleName]
206 reachable_from = downwards_closure_of_module mg2unsorted
208 -- should be cycle free; ignores 'import source's
209 let mg2 = topological_sort False mg2unsorted
210 -- ... whereas this takes them into account. Used for
211 -- backing out partially complete cycles following a failed
212 -- upsweep, and for removing from hst/hit all the modules
213 -- not in strict downwards closure, during calls to compile.
214 let mg2_with_srcimps = topological_sort True mg2unsorted
216 -- Figure out a stable set of modules which can be retained
217 -- the top level envs, to avoid upsweeping them. Goes to a
218 -- bit of trouble to avoid upsweeping module cycles.
220 -- Construct a set S of stable modules like this:
221 -- Travel upwards, over the sccified graph. For each scc
222 -- of modules ms, add ms to S only if:
223 -- 1. All home imports of ms are either in ms or S
224 -- 2. All m <- ms satisfy P, where
225 -- P | interactive = have old summary for m and it indicates
226 -- that the source is unchanged
227 -- | batch = linkable exists on disk, and is younger
230 (stable_mods, linkables_for_stable_mods)
231 <- preUpsweep ghci_mode ui1 mg1 mg2unsorted_names [] [] mg2_with_srcimps
232 let stable_old_summaries
233 = concatMap (findInSummaries mg1) stable_mods
236 putStrLn (showSDoc (text "STABLE MODULES:"
237 <+> sep (map (text.moduleNameUserString) stable_mods)))
241 = retainInTopLevelEnvs stable_mods (hst1, hit1, [])
243 = linkables_for_stable_mods
245 -- Now hst2, hit2, ui2 now hold the 'reduced system', just the set of
246 -- modules which are stable.
248 -- We could at this point detect cycles which aren't broken by
249 -- a source-import, and complain immediately, but it seems better
250 -- to let upsweep_mods do this, so at least some useful work gets
251 -- done before the upsweep is abandoned.
253 = filter (\scc -> any (`notElem` stable_mods)
254 (map name_of_summary (flattenSCC scc)))
257 --hPutStrLn stderr "after tsort:\n"
258 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
260 -- Because we don't take into account source imports when doing
261 -- the topological sort, there shouldn't be any cycles in mg2.
262 -- If there is, we complain and give up -- the user needs to
263 -- break the cycle using a boot file.
265 -- Now do the upsweep, calling compile for each module in
266 -- turn. Final result is version 3 of everything.
268 let threaded2 = CmThreaded pcs1 hst2 hit2
270 (upsweep_complete_success, threaded3, modsUpswept, newLis)
271 <- upsweep_mods ghci_mode dflags ui2 reachable_from
272 threaded2 upsweep_these
274 let ui3 = add_to_ui ui2 newLis
275 let (CmThreaded pcs3 hst3 hit3) = threaded3
277 -- At this point, modsUpswept and newLis should have the same
278 -- length, so there is one new (or old) linkable for each
279 -- mod which was processed (passed to compile).
281 -- Make modsDone be the summaries for each home module now
282 -- available; this should equal the domains of hst3 and hit3.
283 -- (NOT STRICTLY TRUE if an interactive session was started
284 -- with some object on disk ???)
285 -- Get in in a roughly top .. bottom order (hence reverse).
287 let modsDone = reverse modsUpswept ++ stable_old_summaries
289 -- Try and do linking in some form, depending on whether the
290 -- upsweep was completely or only partially successful.
292 if upsweep_complete_success
295 -- Easy; just relink it all.
296 do when (verb >= 2) $
297 hPutStrLn stderr "Upsweep completely successful."
299 <- link ghci_mode dflags a_root_is_Main ui3 pls1
302 -> panic "cmLoadModule: link failed (1)"
304 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
308 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
309 return (cmstate3, True,
310 map name_of_summary modsDone)
313 -- Tricky. We need to back out the effects of compiling any
314 -- half-done cycles, both so as to clean up the top level envs
315 -- and to avoid telling the interactive linker to link them.
316 do when (verb >= 2) $
317 hPutStrLn stderr "Upsweep partially successful."
320 = map name_of_summary modsDone
321 let mods_to_zap_names
322 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
323 let (hst4, hit4, ui4)
324 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
326 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
327 let mods_to_keep_names
328 = map name_of_summary mods_to_keep
329 -- we could get the relevant linkables by filtering newLis, but
330 -- it seems easier to drag them out of the updated, cleaned-up UI
331 let linkables_to_link
332 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
335 linkresult <- link ghci_mode dflags False linkables_to_link pls1
338 -> panic "cmLoadModule: link failed (2)"
340 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
341 ui=ui4, mg=mods_to_keep,
344 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
345 return (cmstate4, False,
350 -- Do a pre-upsweep without use of "compile", to establish a
351 -- (downward-closed) set of stable modules which can be retained
352 -- in the top-level environments. Also return linkables for those
353 -- modules determined to be stable, since (in Batch mode, at least)
354 -- there's no other way for them to get into UI.
355 preUpsweep :: GhciMode
356 -> [Linkable] -- linkables from previous cmLoadModule pass
357 -- should be [] in batch mode
358 -> [ModSummary] -- summaries from previous cmLoadModule pass
359 -- should be [] in batch mode
360 -> [ModuleName] -- names of all mods encountered in downsweep
361 -> [ModuleName] -- accumulating stable modules
362 -> [Linkable] -- their linkables, in batch mode
363 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
364 -> IO ([ModuleName], [Linkable])
365 -- stable modules and their linkables
367 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis []
368 = return (stable, lis)
369 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis (scc0:sccs)
370 = do let scc = flattenSCC scc0
371 scc_allhomeimps :: [ModuleName]
373 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
374 all_imports_in_scc_or_stable
375 = all in_stable_or_scc scc_allhomeimps
377 = map name_of_summary scc
379 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
380 m `elem` scc_names || m `elem` stable
382 (all_scc_stable, more_lis)
383 <- if not all_imports_in_scc_or_stable
384 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
387 <- mapM (is_stable ghci_mode old_lis old_summaries) scc
388 let (bools, liss) = unzip bools_n_lis
389 --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
390 return (and bools, concat liss)
391 if not all_scc_stable
392 then preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis sccs
393 else preUpsweep ghci_mode old_lis old_summaries all_home_mods
394 (scc_names++stable) (more_lis++lis) sccs
397 -- Helper for preUpsweep. Assuming that new_summary's imports are all
398 -- stable (in the sense of preUpsweep), determine if new_summary is itself
399 -- stable, and, if so, in batch mode, return its linkable.
400 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
401 findInSummaries old_summaries mod_name
402 = [s | s <- old_summaries, name_of_summary s == mod_name]
404 is_stable :: GhciMode
405 -> [Linkable] -> [ModSummary] -- OLD lis and summs, in Interactive mode
406 -> ModSummary -- this module
407 -> IO (Bool, [Linkable])
409 is_stable Interactive old_lis old_summaries new_summary
410 -- Only true if the old summary exists and
411 -- the new source date matches the old one.
412 = case found_old_summarys of
413 [] -> return (False, old_linkable)
415 -> case (ms_hs_date new_summary, ms_hs_date old_summary) of
416 (Just d1, Just d2) -> return (d1 == d2, old_linkable)
417 (_, _ ) -> return (False, old_linkable)
421 (findModuleLinkable_maybe old_lis (name_of_summary new_summary))
423 = findInSummaries old_summaries (name_of_summary new_summary)
425 is_stable Batch [] [] new_summary
426 -- Only true if we can find a linkable, and it is younger than
428 = case ms_hs_date new_summary of
429 Nothing -> return (False, []) -- no source date (?!)
431 -> case ml_obj_file (ms_location new_summary) of
432 Nothing -> return (False, []) -- no obj filename
434 -> do maybe_li <- maybe_getFileLinkable
435 (moduleName (ms_mod new_summary)) fn
437 Nothing -> return (False, []) -- no object file on disk
438 Just li -> return (linkableTime li >= hs_time, [li])
442 -- Return (names of) all those in modsDone who are part of a cycle
443 -- as defined by theGraph.
444 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
445 findPartiallyCompletedCycles modsDone theGraph
449 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
450 chew ((CyclicSCC vs):rest)
451 = let names_in_this_cycle = nub (map name_of_summary vs)
453 = nub ([done | done <- modsDone,
454 done `elem` names_in_this_cycle])
455 chewed_rest = chew rest
457 if not (null mods_in_this_cycle)
458 && length mods_in_this_cycle < length names_in_this_cycle
459 then mods_in_this_cycle ++ chewed_rest
463 -- Does this ModDetails export Main.main?
464 --exports_main :: ModDetails -> Bool
466 -- = isJust (lookupNameEnv (md_types md) mainName)
469 -- Add the given (LM-form) Linkables to the UI, overwriting previous
470 -- versions if they exist.
471 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
475 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
477 = li : filter (\li2 -> not (for_same_module li li2)) ui
479 for_same_module :: Linkable -> Linkable -> Bool
480 for_same_module li1 li2
481 = not (is_package_linkable li1)
482 && not (is_package_linkable li2)
483 && modname_of_linkable li1 == modname_of_linkable li2
486 data CmThreaded -- stuff threaded through individual module compilations
487 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
490 -- Compile multiple modules, stopping as soon as an error appears.
491 -- There better had not be any cyclic groups here -- we check for them.
492 upsweep_mods :: GhciMode
494 -> UnlinkedImage -- old linkables
495 -> (ModuleName -> [ModuleName]) -- to construct downward closures
496 -> CmThreaded -- PCS & HST & HIT
497 -> [SCC ModSummary] -- mods to do (the worklist)
498 -- ...... RETURNING ......
499 -> IO (Bool{-complete success?-},
501 [ModSummary], -- mods which succeeded
502 [Linkable]) -- new linkables
504 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
506 = return (True, threaded, [], [])
508 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
510 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
511 unwords (map (moduleNameUserString.name_of_summary) ms))
512 return (False, threaded, [], [])
514 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
515 ((AcyclicSCC mod):mods)
516 = do --case threaded of
517 -- CmThreaded pcsz hstz hitz
518 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
520 (threaded1, maybe_linkable)
521 <- upsweep_mod ghci_mode dflags oldUI threaded mod
522 (reachable_from (name_of_summary mod))
523 case maybe_linkable of
525 -> -- No errors; do the rest
526 do (restOK, threaded2, modOKs, linkables)
527 <- upsweep_mods ghci_mode dflags oldUI reachable_from
529 return (restOK, threaded2, mod:modOKs, linkable:linkables)
530 Nothing -- we got a compilation error; give up now
531 -> return (False, threaded1, [], [])
534 -- Compile a single module. Always produce a Linkable for it if
535 -- successful. If no compilation happened, return the old Linkable.
536 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
537 maybe_getFileLinkable mod_name obj_fn
538 = do obj_exist <- doesFileExist obj_fn
542 do let stub_fn = case splitFilename3 obj_fn of
543 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
544 stub_exist <- doesFileExist stub_fn
545 obj_time <- getModificationTime obj_fn
547 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
548 else return (Just (LM obj_time mod_name [DotO obj_fn]))
551 upsweep_mod :: GhciMode
557 -> IO (CmThreaded, Maybe Linkable)
559 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
561 let mod_name = name_of_summary summary1
562 let verb = verbosity dflags
565 if (ghci_mode == Batch)
566 then hPutStr stderr (progName ++ ": module "
567 ++ moduleNameUserString mod_name
569 else hPutStr stderr ("Compiling "
570 ++ moduleNameUserString mod_name
573 let (CmThreaded pcs1 hst1 hit1) = threaded1
574 let old_iface = lookupUFM hit1 mod_name
576 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
577 maybe_oldDisk_linkable
578 <- case ml_obj_file (ms_location summary1) of
579 Nothing -> return Nothing
580 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
582 -- The most recent of the old UI linkable or whatever we could
583 -- find on disk. Is returned as the linkable if compile
584 -- doesn't think we need to recompile.
585 let maybe_old_linkable
586 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
587 (Nothing, Nothing) -> Nothing
588 (Nothing, Just di) -> Just di
589 (Just ui, Nothing) -> Just ui
591 | linkableTime ui >= linkableTime di -> Just ui
592 | otherwise -> Just di
594 let compilation_mandatory
595 = case maybe_old_linkable of
597 Just li -> case ms_hs_date summary1 of
598 Nothing -> panic "compilation_mandatory:no src date"
599 Just src_date -> src_date >= linkableTime li
601 = not compilation_mandatory
603 (hst1_strictDC, hit1_strictDC, [])
604 = retainInTopLevelEnvs
605 (filter (/= (name_of_summary summary1)) reachable_from_here)
609 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
611 compresult <- compile ghci_mode summary1 source_unchanged
612 old_iface hst1_strictDC hit1_strictDC pcs1
616 -- Compilation "succeeded", but didn't return a new
617 -- linkable, meaning that compilation wasn't needed, and the
618 -- new details were manufactured from the old iface.
619 CompOK pcs2 new_details new_iface Nothing
620 -> do let hst2 = addToUFM hst1 mod_name new_details
621 hit2 = addToUFM hit1 mod_name new_iface
622 threaded2 = CmThreaded pcs2 hst2 hit2
624 if ghci_mode == Interactive && verb >= 1 then
625 -- if we're using an object file, tell the user
626 case maybe_old_linkable of
627 Just (LM _ _ objs@(DotO _:_))
628 -> do hPutStr stderr (showSDoc (space <>
629 parens (hsep (text "using":
631 [ text o | DotO o <- objs ]))))
632 when (verb > 1) $ hPutStrLn stderr ""
637 when (verb == 1) $ hPutStrLn stderr ""
638 return (threaded2, Just old_linkable)
640 -- Compilation really did happen, and succeeded. A new
641 -- details, iface and linkable are returned.
642 CompOK pcs2 new_details new_iface (Just new_linkable)
643 -> do let hst2 = addToUFM hst1 mod_name new_details
644 hit2 = addToUFM hit1 mod_name new_iface
645 threaded2 = CmThreaded pcs2 hst2 hit2
647 when (verb == 1) $ hPutStrLn stderr ""
648 return (threaded2, Just new_linkable)
650 -- Compilation failed. compile may still have updated
653 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
654 when (verb == 1) $ hPutStrLn stderr ""
655 return (threaded2, Nothing)
657 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
658 removeFromTopLevelEnvs :: [ModuleName]
659 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
660 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
661 removeFromTopLevelEnvs zap_these (hst, hit, ui)
662 = (delListFromUFM hst zap_these,
663 delListFromUFM hit zap_these,
664 filterModuleLinkables (`notElem` zap_these) ui
667 retainInTopLevelEnvs :: [ModuleName]
668 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
669 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
670 retainInTopLevelEnvs keep_these (hst, hit, ui)
671 = (retainInUFM hst keep_these,
672 retainInUFM hit keep_these,
673 filterModuleLinkables (`elem` keep_these) ui
676 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
677 retainInUFM ufm keys_to_keep
678 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
680 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
682 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
683 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
684 downwards_closure_of_module summaries root
685 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
686 toEdge summ = (name_of_summary summ, ms_allimps summ)
687 res = simple_transitive_closure (map toEdge summaries) [root]
689 --trace (showSDoc (text "DC of mod" <+> ppr root
690 -- <+> text "=" <+> ppr res)) (
694 -- Calculate transitive closures from a set of roots given an adjacency list
695 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
696 simple_transitive_closure graph set
697 = let set2 = nub (concatMap dsts set ++ set)
698 dsts node = fromMaybe [] (lookup node graph)
700 if length set == length set2
702 else simple_transitive_closure graph set2
705 -- Calculate SCCs of the module graph, with or without taking into
706 -- account source imports.
707 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
708 topological_sort include_source_imports summaries
710 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
712 = (summ, name_of_summary summ,
713 (if include_source_imports
714 then ms_srcimps summ else []) ++ ms_imps summ)
716 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
717 mash_edge (summ, m, m_imports)
718 = case lookup m key_map of
719 Nothing -> panic "reverse_topological_sort"
720 Just mk -> (summ, mk,
721 -- ignore imports not from the home package
722 catMaybes (map (flip lookup key_map) m_imports))
724 edges = map toEdge summaries
725 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
726 scc_input = map mash_edge edges
727 sccs = stronglyConnComp scc_input
732 -- Chase downwards from the specified root set, returning summaries
733 -- for all home modules encountered. Only follow source-import
734 -- links. Also returns a Bool to indicate whether any of the roots
736 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
738 = do rootSummaries <- mapM getRootSummary rootNm
740 = any ((=="Main").moduleNameUserString.name_of_summary)
743 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
744 return (all_summaries, a_root_is_Main)
746 getRootSummary :: FilePath -> IO ModSummary
748 | haskellish_file file
749 = do exists <- doesFileExist file
750 if exists then summariseFile file else do
751 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
753 = do exists <- doesFileExist hs_file
754 if exists then summariseFile hs_file else do
755 exists <- doesFileExist lhs_file
756 if exists then summariseFile lhs_file else do
757 getSummary (mkModuleName file)
759 hs_file = file ++ ".hs"
760 lhs_file = file ++ ".lhs"
762 getSummary :: ModuleName -> IO ModSummary
764 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
765 = do found <- findModule nm
767 -- Be sure not to use the mod and location passed in to
768 -- summarise for any other purpose -- summarise may change
769 -- the module names in them if name of module /= name of file,
770 -- and put the changed versions in the returned summary.
771 -- These will then conflict with the passed-in versions.
772 Just (mod, location) -> summarise mod location
773 Nothing -> throwDyn (OtherError
774 ("can't find module `"
775 ++ showSDoc (ppr nm) ++ "'"))
777 -- loop invariant: homeSummaries doesn't contain package modules
778 loop :: [ModSummary] -> IO [ModSummary]
780 = do let allImps :: [ModuleName]
781 allImps = (nub . concatMap ms_imps) homeSummaries
782 let allHome -- all modules currently in homeSummaries
783 = map (moduleName.ms_mod) homeSummaries
785 = filter (`notElem` allHome) allImps
787 <- mapM getSummary neededImps
789 = filter (isHomeModule.ms_mod) neededSummaries
790 if null newHomeSummaries
791 then return homeSummaries
792 else loop (newHomeSummaries ++ homeSummaries)
795 -----------------------------------------------------------------------------
796 -- Summarising modules
798 -- We have two types of summarisation:
800 -- * Summarise a file. This is used for the root module passed to
801 -- cmLoadModule. The file is read, and used to determine the root
802 -- module name. The module name may differ from the filename.
804 -- * Summarise a module. We are given a module name, and must provide
805 -- a summary. The finder is used to locate the file in which the module
808 summariseFile :: FilePath -> IO ModSummary
810 = do hspp_fn <- preprocess file
811 modsrc <- readFile hspp_fn
813 let (srcimps,imps,mod_name) = getImports modsrc
814 (path, basename, ext) = splitFilename3 file
817 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
820 <- case ml_hs_file location of
821 Nothing -> return Nothing
822 Just src_fn -> maybe_getModificationTime src_fn
824 return (ModSummary mod
825 location{ml_hspp_file=Just hspp_fn}
829 -- Summarise a module, and pick up source and interface timestamps.
830 summarise :: Module -> ModuleLocation -> IO ModSummary
831 summarise mod location
833 = do let hs_fn = unJust "summarise" (ml_hs_file location)
834 hspp_fn <- preprocess hs_fn
835 modsrc <- readFile hspp_fn
836 let (srcimps,imps,mod_name) = getImports modsrc
839 <- case ml_hs_file location of
840 Nothing -> return Nothing
841 Just src_fn -> maybe_getModificationTime src_fn
843 if mod_name == moduleName mod
845 else throwDyn (OtherError
846 (showSDoc (text "file name does not match module name: "
847 <+> ppr (moduleName mod) <+> text "vs"
850 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
855 = return (ModSummary mod location [] [] Nothing)
857 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
858 maybe_getModificationTime fn
859 = (do time <- getModificationTime fn
862 (\err -> return Nothing)