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(..) )
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
71 -> Bool -- True <=> wrap in 'print' to get an IO-typed result
74 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
75 cmGetExpr cmstate dflags wrap_io mod expr
76 = do (new_pcs, maybe_stuff) <-
77 hscExpr dflags wrap_io hst hit pcs mod expr
79 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
80 Just (bcos, print_unqual, ty) -> do
81 hValue <- linkExpr pls bcos
82 return (cmstate{ pcs=new_pcs },
83 Just (hValue, print_unqual, ty))
85 -- ToDo: check that the module we passed in is sane/exists?
87 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
88 PersistentCMState{ hst=hst, hit=hit } = pcms
90 -- The HValue should represent a value of type IO () (Perhaps IO a?)
91 cmRunExpr :: HValue -> IO ()
93 = do unsafeCoerce# hval :: IO ()
97 -- Persistent state just for CM, excluding link & compile subsystems
98 data PersistentCMState
100 hst :: HomeSymbolTable, -- home symbol table
101 hit :: HomeIfaceTable, -- home interface table
102 ui :: UnlinkedImage, -- the unlinked images
103 mg :: ModuleGraph, -- the module graph
104 gmode :: GhciMode -- NEVER CHANGES
107 emptyPCMS :: GhciMode -> PersistentCMState
109 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
110 ui = emptyUI, mg = emptyMG,
113 emptyHIT :: HomeIfaceTable
115 emptyHST :: HomeSymbolTable
120 -- Persistent state for the entire system
123 pcms :: PersistentCMState, -- CM's persistent state
124 pcs :: PersistentCompilerState, -- compile's persistent state
125 pls :: PersistentLinkerState -- link's persistent state
128 emptyCmState :: GhciMode -> IO CmState
130 = do let pcms = emptyPCMS gmode
131 pcs <- initPersistentCompilerState
133 return (CmState { pcms = pcms,
138 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
139 emptyUI :: UnlinkedImage
142 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
143 emptyMG :: ModuleGraph
148 Unload the compilation manager's state: everything it knows about the
149 current collection of modules in the Home package.
152 cmUnload :: CmState -> IO CmState
154 = do -- Throw away the old home dir cache
156 -- Throw away the HIT and the HST
157 return state{ pcms=pcms{ hst=new_hst, hit=new_hit } }
159 CmState{ pcms=pcms } = state
160 PersistentCMState{ hst=hst, hit=hit } = pcms
161 (new_hst, new_hit,[]) = retainInTopLevelEnvs [] (hst,hit,[])
164 The real business of the compilation manager: given a system state and
165 a module name, try and bring the module up to date, probably changing
166 the system state at the same time.
169 cmLoadModule :: CmState
171 -> IO (CmState, -- new state
172 Bool, -- was successful
173 [Module]) -- list of modules loaded
175 cmLoadModule cmstate1 rootname
176 = do -- version 1's are the original, before downsweep
177 let pcms1 = pcms cmstate1
178 let pls1 = pls cmstate1
179 let pcs1 = pcs cmstate1
180 -- mg1 is the complete (home) set of summaries from the
181 -- previous pass of cmLoadModule, if there was one.
185 -- similarly, ui1 is the (complete) set of linkables from
186 -- the previous pass, if any.
189 let ghci_mode = gmode pcms1 -- this never changes
191 -- Do the downsweep to reestablish the module graph
192 -- then generate version 2's by retaining in HIT,HST,UI a
193 -- stable set S of modules, as defined below.
195 dflags <- getDynFlags
196 let verb = verbosity dflags
198 showPass dflags "Chasing dependencies"
199 when (verb >= 1 && ghci_mode == Batch) $
200 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
202 (mg2unsorted, a_root_is_Main) <- downsweep [rootname]
203 let mg2unsorted_names = map name_of_summary mg2unsorted
205 -- reachable_from follows source as well as normal imports
206 let reachable_from :: ModuleName -> [ModuleName]
207 reachable_from = downwards_closure_of_module mg2unsorted
209 -- should be cycle free; ignores 'import source's
210 let mg2 = topological_sort False mg2unsorted
211 -- ... whereas this takes them into account. Used for
212 -- backing out partially complete cycles following a failed
213 -- upsweep, and for removing from hst/hit all the modules
214 -- not in strict downwards closure, during calls to compile.
215 let mg2_with_srcimps = topological_sort True mg2unsorted
217 -- Figure out a stable set of modules which can be retained
218 -- the top level envs, to avoid upsweeping them. Goes to a
219 -- bit of trouble to avoid upsweeping module cycles.
221 -- Construct a set S of stable modules like this:
222 -- Travel upwards, over the sccified graph. For each scc
223 -- of modules ms, add ms to S only if:
224 -- 1. All home imports of ms are either in ms or S
225 -- 2. All m <- ms satisfy P, where
226 -- P | interactive = have old summary for m and it indicates
227 -- that the source is unchanged
228 -- | batch = linkable exists on disk, and is younger
231 (stable_mods, linkables_for_stable_mods)
232 <- preUpsweep ghci_mode ui1 mg1 mg2unsorted_names [] [] mg2_with_srcimps
233 let stable_old_summaries
234 = concatMap (findInSummaries mg1) stable_mods
237 putStrLn (showSDoc (text "STABLE MODULES:"
238 <+> sep (map (text.moduleNameUserString) stable_mods)))
242 = retainInTopLevelEnvs stable_mods (hst1, hit1, [])
244 = linkables_for_stable_mods
246 -- Now hst2, hit2, ui2 now hold the 'reduced system', just the set of
247 -- modules which are stable.
249 -- We could at this point detect cycles which aren't broken by
250 -- a source-import, and complain immediately, but it seems better
251 -- to let upsweep_mods do this, so at least some useful work gets
252 -- done before the upsweep is abandoned.
254 = filter (\scc -> any (`notElem` stable_mods)
255 (map name_of_summary (flattenSCC scc)))
258 --hPutStrLn stderr "after tsort:\n"
259 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
261 -- Because we don't take into account source imports when doing
262 -- the topological sort, there shouldn't be any cycles in mg2.
263 -- If there is, we complain and give up -- the user needs to
264 -- break the cycle using a boot file.
266 -- Now do the upsweep, calling compile for each module in
267 -- turn. Final result is version 3 of everything.
269 let threaded2 = CmThreaded pcs1 hst2 hit2
271 (upsweep_complete_success, threaded3, modsUpswept, newLis)
272 <- upsweep_mods ghci_mode dflags ui2 reachable_from
273 threaded2 upsweep_these
275 let ui3 = add_to_ui ui2 newLis
276 let (CmThreaded pcs3 hst3 hit3) = threaded3
278 -- At this point, modsUpswept and newLis should have the same
279 -- length, so there is one new (or old) linkable for each
280 -- mod which was processed (passed to compile).
282 -- Make modsDone be the summaries for each home module now
283 -- available; this should equal the domains of hst3 and hit3.
284 -- (NOT STRICTLY TRUE if an interactive session was started
285 -- with some object on disk ???)
286 -- Get in in a roughly top .. bottom order (hence reverse).
288 let modsDone = reverse modsUpswept ++ stable_old_summaries
290 -- Try and do linking in some form, depending on whether the
291 -- upsweep was completely or only partially successful.
293 if upsweep_complete_success
296 -- Easy; just relink it all.
297 do when (verb >= 2) $
298 hPutStrLn stderr "Upsweep completely successful."
300 <- link ghci_mode dflags a_root_is_Main ui3 pls1
303 -> panic "cmLoadModule: link failed (1)"
305 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
309 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
310 return (cmstate3, True,
314 -- Tricky. We need to back out the effects of compiling any
315 -- half-done cycles, both so as to clean up the top level envs
316 -- and to avoid telling the interactive linker to link them.
317 do when (verb >= 2) $
318 hPutStrLn stderr "Upsweep partially successful."
321 = map name_of_summary modsDone
322 let mods_to_zap_names
323 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
324 let (hst4, hit4, ui4)
325 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
327 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
328 let mods_to_keep_names
329 = map name_of_summary mods_to_keep
330 -- we could get the relevant linkables by filtering newLis, but
331 -- it seems easier to drag them out of the updated, cleaned-up UI
332 let linkables_to_link
333 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
336 linkresult <- link ghci_mode dflags False linkables_to_link pls1
339 -> panic "cmLoadModule: link failed (2)"
341 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
342 ui=ui4, mg=mods_to_keep,
345 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
346 return (cmstate4, False,
347 map ms_mod mods_to_keep)
351 -- Do a pre-upsweep without use of "compile", to establish a
352 -- (downward-closed) set of stable modules which can be retained
353 -- in the top-level environments. Also return linkables for those
354 -- modules determined to be stable, since (in Batch mode, at least)
355 -- there's no other way for them to get into UI.
356 preUpsweep :: GhciMode
357 -> [Linkable] -- linkables from previous cmLoadModule pass
358 -- should be [] in batch mode
359 -> [ModSummary] -- summaries from previous cmLoadModule pass
360 -- should be [] in batch mode
361 -> [ModuleName] -- names of all mods encountered in downsweep
362 -> [ModuleName] -- accumulating stable modules
363 -> [Linkable] -- their linkables, in batch mode
364 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
365 -> IO ([ModuleName], [Linkable])
366 -- stable modules and their linkables
368 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis []
369 = return (stable, lis)
370 preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis (scc0:sccs)
371 = do let scc = flattenSCC scc0
372 scc_allhomeimps :: [ModuleName]
374 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
375 all_imports_in_scc_or_stable
376 = all in_stable_or_scc scc_allhomeimps
378 = map name_of_summary scc
380 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
381 m `elem` scc_names || m `elem` stable
383 (all_scc_stable, more_lis)
384 <- if not all_imports_in_scc_or_stable
385 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
388 <- mapM (is_stable ghci_mode old_lis old_summaries) scc
389 let (bools, liss) = unzip bools_n_lis
390 --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
391 return (and bools, concat liss)
392 if not all_scc_stable
393 then preUpsweep ghci_mode old_lis old_summaries all_home_mods stable lis sccs
394 else preUpsweep ghci_mode old_lis old_summaries all_home_mods
395 (scc_names++stable) (more_lis++lis) sccs
398 -- Helper for preUpsweep. Assuming that new_summary's imports are all
399 -- stable (in the sense of preUpsweep), determine if new_summary is itself
400 -- stable, and, if so, in batch mode, return its linkable.
401 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
402 findInSummaries old_summaries mod_name
403 = [s | s <- old_summaries, name_of_summary s == mod_name]
405 is_stable :: GhciMode
406 -> [Linkable] -> [ModSummary] -- OLD lis and summs, in Interactive mode
407 -> ModSummary -- this module
408 -> IO (Bool, [Linkable])
410 is_stable Interactive old_lis old_summaries new_summary
411 -- Only true if the old summary exists and
412 -- the new source date matches the old one.
413 = case found_old_summarys of
414 [] -> return (False, old_linkable)
416 -> case (ms_hs_date new_summary, ms_hs_date old_summary) of
417 (Just d1, Just d2) -> return (d1 == d2, old_linkable)
418 (_, _ ) -> return (False, old_linkable)
422 (findModuleLinkable_maybe old_lis (name_of_summary new_summary))
424 = findInSummaries old_summaries (name_of_summary new_summary)
426 is_stable Batch [] [] new_summary
427 -- Only true if we can find a linkable, and it is younger than
429 = case ms_hs_date new_summary of
430 Nothing -> return (False, []) -- no source date (?!)
432 -> case ml_obj_file (ms_location new_summary) of
433 Nothing -> return (False, []) -- no obj filename
435 -> do maybe_li <- maybe_getFileLinkable
436 (moduleName (ms_mod new_summary)) fn
438 Nothing -> return (False, []) -- no object file on disk
439 Just li -> return (linkableTime li >= hs_time, [li])
443 -- Return (names of) all those in modsDone who are part of a cycle
444 -- as defined by theGraph.
445 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
446 findPartiallyCompletedCycles modsDone theGraph
450 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
451 chew ((CyclicSCC vs):rest)
452 = let names_in_this_cycle = nub (map name_of_summary vs)
454 = nub ([done | done <- modsDone,
455 done `elem` names_in_this_cycle])
456 chewed_rest = chew rest
458 if not (null mods_in_this_cycle)
459 && length mods_in_this_cycle < length names_in_this_cycle
460 then mods_in_this_cycle ++ chewed_rest
464 -- Does this ModDetails export Main.main?
465 --exports_main :: ModDetails -> Bool
467 -- = isJust (lookupNameEnv (md_types md) mainName)
470 -- Add the given (LM-form) Linkables to the UI, overwriting previous
471 -- versions if they exist.
472 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
476 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
478 = li : filter (\li2 -> not (for_same_module li li2)) ui
480 for_same_module :: Linkable -> Linkable -> Bool
481 for_same_module li1 li2
482 = not (is_package_linkable li1)
483 && not (is_package_linkable li2)
484 && modname_of_linkable li1 == modname_of_linkable li2
487 data CmThreaded -- stuff threaded through individual module compilations
488 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
491 -- Compile multiple modules, stopping as soon as an error appears.
492 -- There better had not be any cyclic groups here -- we check for them.
493 upsweep_mods :: GhciMode
495 -> UnlinkedImage -- old linkables
496 -> (ModuleName -> [ModuleName]) -- to construct downward closures
497 -> CmThreaded -- PCS & HST & HIT
498 -> [SCC ModSummary] -- mods to do (the worklist)
499 -- ...... RETURNING ......
500 -> IO (Bool{-complete success?-},
502 [ModSummary], -- mods which succeeded
503 [Linkable]) -- new linkables
505 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
507 = return (True, threaded, [], [])
509 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
511 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
512 unwords (map (moduleNameUserString.name_of_summary) ms))
513 return (False, threaded, [], [])
515 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
516 ((AcyclicSCC mod):mods)
517 = do --case threaded of
518 -- CmThreaded pcsz hstz hitz
519 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
521 (threaded1, maybe_linkable)
522 <- upsweep_mod ghci_mode dflags oldUI threaded mod
523 (reachable_from (name_of_summary mod))
524 case maybe_linkable of
526 -> -- No errors; do the rest
527 do (restOK, threaded2, modOKs, linkables)
528 <- upsweep_mods ghci_mode dflags oldUI reachable_from
530 return (restOK, threaded2, mod:modOKs, linkable:linkables)
531 Nothing -- we got a compilation error; give up now
532 -> return (False, threaded1, [], [])
535 -- Compile a single module. Always produce a Linkable for it if
536 -- successful. If no compilation happened, return the old Linkable.
537 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
538 maybe_getFileLinkable mod_name obj_fn
539 = do obj_exist <- doesFileExist obj_fn
543 do let stub_fn = case splitFilename3 obj_fn of
544 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
545 stub_exist <- doesFileExist stub_fn
546 obj_time <- getModificationTime obj_fn
548 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
549 else return (Just (LM obj_time mod_name [DotO obj_fn]))
552 upsweep_mod :: GhciMode
558 -> IO (CmThreaded, Maybe Linkable)
560 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
562 let mod_name = name_of_summary summary1
563 let verb = verbosity dflags
566 if (ghci_mode == Batch)
567 then hPutStr stderr (progName ++ ": module "
568 ++ moduleNameUserString mod_name
570 else hPutStr stderr ("Compiling "
571 ++ moduleNameUserString mod_name
574 let (CmThreaded pcs1 hst1 hit1) = threaded1
575 let old_iface = lookupUFM hit1 mod_name
577 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
578 maybe_oldDisk_linkable
579 <- case ml_obj_file (ms_location summary1) of
580 Nothing -> return Nothing
581 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
583 -- The most recent of the old UI linkable or whatever we could
584 -- find on disk. Is returned as the linkable if compile
585 -- doesn't think we need to recompile.
586 let maybe_old_linkable
587 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
588 (Nothing, Nothing) -> Nothing
589 (Nothing, Just di) -> Just di
590 (Just ui, Nothing) -> Just ui
592 | linkableTime ui >= linkableTime di -> Just ui
593 | otherwise -> Just di
595 let compilation_mandatory
596 = case maybe_old_linkable of
598 Just li -> case ms_hs_date summary1 of
599 Nothing -> panic "compilation_mandatory:no src date"
600 Just src_date -> src_date >= linkableTime li
602 = not compilation_mandatory
604 (hst1_strictDC, hit1_strictDC, [])
605 = retainInTopLevelEnvs
606 (filter (/= (name_of_summary summary1)) reachable_from_here)
610 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
612 compresult <- compile ghci_mode summary1 source_unchanged
613 old_iface hst1_strictDC hit1_strictDC pcs1
617 -- Compilation "succeeded", but didn't return a new
618 -- linkable, meaning that compilation wasn't needed, and the
619 -- new details were manufactured from the old iface.
620 CompOK pcs2 new_details new_iface Nothing
621 -> do let hst2 = addToUFM hst1 mod_name new_details
622 hit2 = addToUFM hit1 mod_name new_iface
623 threaded2 = CmThreaded pcs2 hst2 hit2
625 if ghci_mode == Interactive && verb >= 1 then
626 -- if we're using an object file, tell the user
627 case maybe_old_linkable of
628 Just (LM _ _ objs@(DotO _:_))
629 -> do hPutStr stderr (showSDoc (space <>
630 parens (hsep (text "using":
632 [ text o | DotO o <- objs ]))))
633 when (verb > 1) $ hPutStrLn stderr ""
638 when (verb == 1) $ hPutStrLn stderr ""
639 return (threaded2, Just old_linkable)
641 -- Compilation really did happen, and succeeded. A new
642 -- details, iface and linkable are returned.
643 CompOK pcs2 new_details new_iface (Just new_linkable)
644 -> do let hst2 = addToUFM hst1 mod_name new_details
645 hit2 = addToUFM hit1 mod_name new_iface
646 threaded2 = CmThreaded pcs2 hst2 hit2
648 when (verb == 1) $ hPutStrLn stderr ""
649 return (threaded2, Just new_linkable)
651 -- Compilation failed. compile may still have updated
654 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
655 when (verb == 1) $ hPutStrLn stderr ""
656 return (threaded2, Nothing)
658 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
659 removeFromTopLevelEnvs :: [ModuleName]
660 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
661 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
662 removeFromTopLevelEnvs zap_these (hst, hit, ui)
663 = (delListFromUFM hst zap_these,
664 delListFromUFM hit zap_these,
665 filterModuleLinkables (`notElem` zap_these) ui
668 retainInTopLevelEnvs :: [ModuleName]
669 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
670 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
671 retainInTopLevelEnvs keep_these (hst, hit, ui)
672 = (retainInUFM hst keep_these,
673 retainInUFM hit keep_these,
674 filterModuleLinkables (`elem` keep_these) ui
677 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
678 retainInUFM ufm keys_to_keep
679 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
681 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
683 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
684 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
685 downwards_closure_of_module summaries root
686 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
687 toEdge summ = (name_of_summary summ, ms_allimps summ)
688 res = simple_transitive_closure (map toEdge summaries) [root]
690 --trace (showSDoc (text "DC of mod" <+> ppr root
691 -- <+> text "=" <+> ppr res)) (
695 -- Calculate transitive closures from a set of roots given an adjacency list
696 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
697 simple_transitive_closure graph set
698 = let set2 = nub (concatMap dsts set ++ set)
699 dsts node = fromMaybe [] (lookup node graph)
701 if length set == length set2
703 else simple_transitive_closure graph set2
706 -- Calculate SCCs of the module graph, with or without taking into
707 -- account source imports.
708 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
709 topological_sort include_source_imports summaries
711 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
713 = (summ, name_of_summary summ,
714 (if include_source_imports
715 then ms_srcimps summ else []) ++ ms_imps summ)
717 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
718 mash_edge (summ, m, m_imports)
719 = case lookup m key_map of
720 Nothing -> panic "reverse_topological_sort"
721 Just mk -> (summ, mk,
722 -- ignore imports not from the home package
723 catMaybes (map (flip lookup key_map) m_imports))
725 edges = map toEdge summaries
726 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
727 scc_input = map mash_edge edges
728 sccs = stronglyConnComp scc_input
733 -- Chase downwards from the specified root set, returning summaries
734 -- for all home modules encountered. Only follow source-import
735 -- links. Also returns a Bool to indicate whether any of the roots
737 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
739 = do rootSummaries <- mapM getRootSummary rootNm
741 = any ((=="Main").moduleNameUserString.name_of_summary)
744 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
745 return (all_summaries, a_root_is_Main)
747 getRootSummary :: FilePath -> IO ModSummary
749 | haskellish_file file
750 = do exists <- doesFileExist file
751 if exists then summariseFile file else do
752 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
754 = do exists <- doesFileExist hs_file
755 if exists then summariseFile hs_file else do
756 exists <- doesFileExist lhs_file
757 if exists then summariseFile lhs_file else do
758 getSummary (mkModuleName file)
760 hs_file = file ++ ".hs"
761 lhs_file = file ++ ".lhs"
763 getSummary :: ModuleName -> IO ModSummary
765 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
766 = do found <- findModule nm
768 -- Be sure not to use the mod and location passed in to
769 -- summarise for any other purpose -- summarise may change
770 -- the module names in them if name of module /= name of file,
771 -- and put the changed versions in the returned summary.
772 -- These will then conflict with the passed-in versions.
773 Just (mod, location) -> summarise mod location
774 Nothing -> throwDyn (OtherError
775 ("can't find module `"
776 ++ showSDoc (ppr nm) ++ "'"))
778 -- loop invariant: homeSummaries doesn't contain package modules
779 loop :: [ModSummary] -> IO [ModSummary]
781 = do let allImps :: [ModuleName]
782 allImps = (nub . concatMap ms_imps) homeSummaries
783 let allHome -- all modules currently in homeSummaries
784 = map (moduleName.ms_mod) homeSummaries
786 = filter (`notElem` allHome) allImps
788 <- mapM getSummary neededImps
790 = filter (isHomeModule.ms_mod) neededSummaries
791 if null newHomeSummaries
792 then return homeSummaries
793 else loop (newHomeSummaries ++ homeSummaries)
796 -----------------------------------------------------------------------------
797 -- Summarising modules
799 -- We have two types of summarisation:
801 -- * Summarise a file. This is used for the root module passed to
802 -- cmLoadModule. The file is read, and used to determine the root
803 -- module name. The module name may differ from the filename.
805 -- * Summarise a module. We are given a module name, and must provide
806 -- a summary. The finder is used to locate the file in which the module
809 summariseFile :: FilePath -> IO ModSummary
811 = do hspp_fn <- preprocess file
812 modsrc <- readFile hspp_fn
814 let (srcimps,imps,mod_name) = getImports modsrc
815 (path, basename, ext) = splitFilename3 file
818 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
821 <- case ml_hs_file location of
822 Nothing -> return Nothing
823 Just src_fn -> maybe_getModificationTime src_fn
825 return (ModSummary mod
826 location{ml_hspp_file=Just hspp_fn}
830 -- Summarise a module, and pick up source and interface timestamps.
831 summarise :: Module -> ModuleLocation -> IO ModSummary
832 summarise mod location
834 = do let hs_fn = unJust "summarise" (ml_hs_file location)
835 hspp_fn <- preprocess hs_fn
836 modsrc <- readFile hspp_fn
837 let (srcimps,imps,mod_name) = getImports modsrc
840 <- case ml_hs_file location of
841 Nothing -> return Nothing
842 Just src_fn -> maybe_getModificationTime src_fn
844 if mod_name == moduleName mod
846 else throwDyn (OtherError
847 (showSDoc (text "file name does not match module name: "
848 <+> ppr (moduleName mod) <+> text "vs"
851 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
856 = return (ModSummary mod location [] [] Nothing)
858 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
859 maybe_getModificationTime fn
860 = (do time <- getModificationTime fn
863 (\err -> return Nothing)