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, maybeToList, isJust )
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{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
89 PersistentCMState{ hst=hst, hit=hit } = pcms
91 -- The HValue should represent a value of type IO () (Perhaps IO a?)
92 cmRunExpr :: HValue -> IO ()
94 = do unsafeCoerce# hval :: IO ()
98 -- Persistent state just for CM, excluding link & compile subsystems
99 data PersistentCMState
100 = PersistentCMState {
101 hst :: HomeSymbolTable, -- home symbol table
102 hit :: HomeIfaceTable, -- home interface table
103 ui :: UnlinkedImage, -- the unlinked images
104 mg :: ModuleGraph, -- the module graph
105 gmode :: GhciMode -- NEVER CHANGES
108 emptyPCMS :: GhciMode -> PersistentCMState
110 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
111 ui = emptyUI, mg = emptyMG,
114 emptyHIT :: HomeIfaceTable
116 emptyHST :: HomeSymbolTable
121 -- Persistent state for the entire system
124 pcms :: PersistentCMState, -- CM's persistent state
125 pcs :: PersistentCompilerState, -- compile's persistent state
126 pls :: PersistentLinkerState -- link's persistent state
129 emptyCmState :: GhciMode -> IO CmState
131 = do let pcms = emptyPCMS gmode
132 pcs <- initPersistentCompilerState
134 return (CmState { pcms = pcms,
139 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
140 emptyUI :: UnlinkedImage
143 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
144 emptyMG :: ModuleGraph
149 Unload the compilation manager's state: everything it knows about the
150 current collection of modules in the Home package.
153 cmUnload :: CmState -> IO CmState
155 = do -- Throw away the old home dir cache
157 -- Throw away the HIT and the HST
158 return state{ pcms=pcms{ hst=new_hst, hit=new_hit } }
160 CmState{ pcms=pcms } = state
161 PersistentCMState{ hst=hst, hit=hit } = pcms
162 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
165 The real business of the compilation manager: given a system state and
166 a module name, try and bring the module up to date, probably changing
167 the system state at the same time.
170 cmLoadModule :: CmState
172 -> IO (CmState, -- new state
173 Bool, -- was successful
174 [Module]) -- list of modules loaded
176 cmLoadModule cmstate1 rootname
177 = do -- version 1's are the original, before downsweep
178 let pcms1 = pcms cmstate1
179 let pls1 = pls cmstate1
180 let pcs1 = pcs cmstate1
181 -- mg1 is the complete (home) set of summaries from the
182 -- previous pass of cmLoadModule, if there was one.
186 -- similarly, ui1 is the (complete) set of linkables from
187 -- the previous pass, if any.
190 let ghci_mode = gmode pcms1 -- this never changes
192 -- Do the downsweep to reestablish the module graph
193 -- then generate version 2's by retaining in HIT,HST,UI a
194 -- stable set S of modules, as defined below.
196 dflags <- getDynFlags
197 let verb = verbosity dflags
199 showPass dflags "Chasing dependencies"
200 when (verb >= 1 && ghci_mode == Batch) $
201 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
203 (mg2unsorted, a_root_is_Main) <- downsweep [rootname]
204 let mg2unsorted_names = map name_of_summary mg2unsorted
206 -- reachable_from follows source as well as normal imports
207 let reachable_from :: ModuleName -> [ModuleName]
208 reachable_from = downwards_closure_of_module mg2unsorted
210 -- should be cycle free; ignores 'import source's
211 let mg2 = topological_sort False mg2unsorted
212 -- ... whereas this takes them into account. Used for
213 -- backing out partially complete cycles following a failed
214 -- upsweep, and for removing from hst/hit all the modules
215 -- not in strict downwards closure, during calls to compile.
216 let mg2_with_srcimps = topological_sort True mg2unsorted
218 -- Sort out which linkables we wish to keep in the unlinked image.
219 -- For each module, we take:
221 -- - the old in-core linkable, if available
222 -- - an on-disk linkable, if available
224 -- and we take the youngest of these, provided it is younger than the
227 -- If a module has a valid linkable, then it may be STABLE (see below),
228 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
230 valid_linkables <- getValidLinkables ui1 mg2unsorted
232 -- Figure out a stable set of modules which can be retained
233 -- the top level envs, to avoid upsweeping them. Goes to a
234 -- bit of trouble to avoid upsweeping module cycles.
236 -- Construct a set S of stable modules like this:
237 -- Travel upwards, over the sccified graph. For each scc
238 -- of modules ms, add ms to S only if:
239 -- 1. All home imports of ms are either in ms or S
240 -- 2. A valid linkable exists for each module in ms
243 <- preUpsweep valid_linkables mg2unsorted_names [] mg2_with_srcimps
246 = concatMap (findInSummaries mg2unsorted) stable_mods
249 putStrLn (showSDoc (text "STABLE MODULES:"
250 <+> sep (map (text.moduleNameUserString) stable_mods)))
252 let (hst2, hit2) = retainInTopLevelEnvs stable_mods (hst1, hit1)
254 -- Now hst2 and hit2 now hold the 'reduced system', just the set of
255 -- modules which are stable.
257 -- We could at this point detect cycles which aren't broken by
258 -- a source-import, and complain immediately, but it seems better
259 -- to let upsweep_mods do this, so at least some useful work gets
260 -- done before the upsweep is abandoned.
262 = filter (\scc -> any (`notElem` stable_mods)
263 (map name_of_summary (flattenSCC scc)))
266 --hPutStrLn stderr "after tsort:\n"
267 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
269 -- Because we don't take into account source imports when doing
270 -- the topological sort, there shouldn't be any cycles in mg2.
271 -- If there is, we complain and give up -- the user needs to
272 -- break the cycle using a boot file.
274 -- Now do the upsweep, calling compile for each module in
275 -- turn. Final result is version 3 of everything.
277 let threaded2 = CmThreaded pcs1 hst2 hit2
279 (upsweep_complete_success, threaded3, modsUpswept, newLis)
280 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
281 threaded2 upsweep_these
283 let ui3 = add_to_ui valid_linkables newLis
284 let (CmThreaded pcs3 hst3 hit3) = threaded3
286 -- At this point, modsUpswept and newLis should have the same
287 -- length, so there is one new (or old) linkable for each
288 -- mod which was processed (passed to compile).
290 -- Make modsDone be the summaries for each home module now
291 -- available; this should equal the domains of hst3 and hit3.
292 -- (NOT STRICTLY TRUE if an interactive session was started
293 -- with some object on disk ???)
294 -- Get in in a roughly top .. bottom order (hence reverse).
296 let modsDone = reverse modsUpswept ++ stable_summaries
298 -- Try and do linking in some form, depending on whether the
299 -- upsweep was completely or only partially successful.
301 if upsweep_complete_success
304 -- Easy; just relink it all.
305 do when (verb >= 2) $
306 hPutStrLn stderr "Upsweep completely successful."
308 <- link ghci_mode dflags a_root_is_Main ui3 pls1
311 -> panic "cmLoadModule: link failed (1)"
313 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
317 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
318 return (cmstate3, True,
322 -- Tricky. We need to back out the effects of compiling any
323 -- half-done cycles, both so as to clean up the top level envs
324 -- and to avoid telling the interactive linker to link them.
325 do when (verb >= 2) $
326 hPutStrLn stderr "Upsweep partially successful."
329 = map name_of_summary modsDone
330 let mods_to_zap_names
331 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
332 let (hst4, hit4, ui4)
333 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
335 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
336 let mods_to_keep_names
337 = map name_of_summary mods_to_keep
338 -- we could get the relevant linkables by filtering newLis, but
339 -- it seems easier to drag them out of the updated, cleaned-up UI
340 let linkables_to_link
341 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
344 linkresult <- link ghci_mode dflags False linkables_to_link pls1
347 -> panic "cmLoadModule: link failed (2)"
349 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
350 ui=ui4, mg=mods_to_keep,
353 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
354 return (cmstate4, False,
355 map ms_mod mods_to_keep)
358 -----------------------------------------------------------------------------
362 :: [Linkable] -- old linkables
363 -> [ModSummary] -- all modules in the program
364 -> IO [Linkable] -- still-valid linkables
366 getValidLinkables old_linkables summaries
367 = do lis <- mapM (getValidLinkable old_linkables) summaries
370 getValidLinkable old_linkables summary
371 = do let mod_name = moduleName (ms_mod summary)
373 <- case ml_obj_file (ms_location summary) of
374 Nothing -> return Nothing
375 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
377 -- find an old in-core linkable if we have one. (forget about
378 -- on-disk linkables for now, we'll check again whether there's
379 -- one here below, just in case a new one has popped up recently).
380 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
383 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
386 -- The most recent of the old UI linkable or whatever we could
387 -- find on disk. Is returned as the linkable if compile
388 -- doesn't think we need to recompile.
390 = case (maybe_old_linkable, maybe_disk_linkable) of
391 (Nothing, Nothing) -> []
392 (Nothing, Just di) -> [di]
393 (Just ui, Nothing) -> [ui]
395 | linkableTime ui >= linkableTime di -> [ui]
398 -- only linkables newer than the source code are valid
399 let maybe_src_date = ms_hs_date summary
402 = case maybe_src_date of
403 Nothing -> panic "valid_linkable_list"
405 -> filter (\li -> linkableTime li > src_date) linkable_list
407 return valid_linkable_list
411 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
412 maybe_getFileLinkable mod_name obj_fn
413 = do obj_exist <- doesFileExist obj_fn
417 do let stub_fn = case splitFilename3 obj_fn of
418 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
419 stub_exist <- doesFileExist stub_fn
420 obj_time <- getModificationTime obj_fn
422 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
423 else return (Just (LM obj_time mod_name [DotO obj_fn]))
426 -----------------------------------------------------------------------------
427 -- Do a pre-upsweep without use of "compile", to establish a
428 -- (downward-closed) set of stable modules which can be retained
429 -- in the top-level environments. Also return linkables for those
430 -- modules determined to be stable, since (in Batch mode, at least)
431 -- there's no other way for them to get into UI.
433 preUpsweep :: [Linkable] -- valid linkables
434 -> [ModuleName] -- names of all mods encountered in downsweep
435 -> [ModuleName] -- accumulating stable modules
436 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
437 -> IO [ModuleName] -- stable modules
439 preUpsweep valid_lis all_home_mods stable []
441 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
442 = do let scc = flattenSCC scc0
443 scc_allhomeimps :: [ModuleName]
445 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
446 all_imports_in_scc_or_stable
447 = all in_stable_or_scc scc_allhomeimps
449 = map name_of_summary scc
451 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
452 m `elem` scc_names || m `elem` stable
455 <- if not all_imports_in_scc_or_stable
456 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
458 else do --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
459 return (all is_stable scc)
460 if not all_scc_stable
461 then preUpsweep valid_lis all_home_mods stable sccs
462 else preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
464 where is_stable new_summary
465 = isJust (findModuleLinkable_maybe valid_lis (name_of_summary new_summary))
468 -- Helper for preUpsweep. Assuming that new_summary's imports are all
469 -- stable (in the sense of preUpsweep), determine if new_summary is itself
470 -- stable, and, if so, in batch mode, return its linkable.
471 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
472 findInSummaries old_summaries mod_name
473 = [s | s <- old_summaries, name_of_summary s == mod_name]
476 -- Return (names of) all those in modsDone who are part of a cycle
477 -- as defined by theGraph.
478 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
479 findPartiallyCompletedCycles modsDone theGraph
483 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
484 chew ((CyclicSCC vs):rest)
485 = let names_in_this_cycle = nub (map name_of_summary vs)
487 = nub ([done | done <- modsDone,
488 done `elem` names_in_this_cycle])
489 chewed_rest = chew rest
491 if not (null mods_in_this_cycle)
492 && length mods_in_this_cycle < length names_in_this_cycle
493 then mods_in_this_cycle ++ chewed_rest
497 -- Does this ModDetails export Main.main?
498 --exports_main :: ModDetails -> Bool
500 -- = isJust (lookupNameEnv (md_types md) mainName)
503 -- Add the given (LM-form) Linkables to the UI, overwriting previous
504 -- versions if they exist.
505 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
509 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
511 = li : filter (\li2 -> not (for_same_module li li2)) ui
513 for_same_module :: Linkable -> Linkable -> Bool
514 for_same_module li1 li2
515 = not (is_package_linkable li1)
516 && not (is_package_linkable li2)
517 && modname_of_linkable li1 == modname_of_linkable li2
520 data CmThreaded -- stuff threaded through individual module compilations
521 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
524 -- Compile multiple modules, stopping as soon as an error appears.
525 -- There better had not be any cyclic groups here -- we check for them.
526 upsweep_mods :: GhciMode
528 -> UnlinkedImage -- valid linkables
529 -> (ModuleName -> [ModuleName]) -- to construct downward closures
530 -> CmThreaded -- PCS & HST & HIT
531 -> [SCC ModSummary] -- mods to do (the worklist)
532 -- ...... RETURNING ......
533 -> IO (Bool{-complete success?-},
535 [ModSummary], -- mods which succeeded
536 [Linkable]) -- new linkables
538 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
540 = return (True, threaded, [], [])
542 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
544 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
545 unwords (map (moduleNameUserString.name_of_summary) ms))
546 return (False, threaded, [], [])
548 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
549 ((AcyclicSCC mod):mods)
550 = do --case threaded of
551 -- CmThreaded pcsz hstz hitz
552 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
554 (threaded1, maybe_linkable)
555 <- upsweep_mod ghci_mode dflags oldUI threaded mod
556 (reachable_from (name_of_summary mod))
557 case maybe_linkable of
559 -> -- No errors; do the rest
560 do (restOK, threaded2, modOKs, linkables)
561 <- upsweep_mods ghci_mode dflags oldUI reachable_from
563 return (restOK, threaded2, mod:modOKs, linkable:linkables)
564 Nothing -- we got a compilation error; give up now
565 -> return (False, threaded1, [], [])
568 -- Compile a single module. Always produce a Linkable for it if
569 -- successful. If no compilation happened, return the old Linkable.
570 upsweep_mod :: GhciMode
576 -> IO (CmThreaded, Maybe Linkable)
578 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
580 let mod_name = name_of_summary summary1
581 let verb = verbosity dflags
584 if (ghci_mode == Batch)
585 then hPutStr stderr (progName ++ ": module "
586 ++ moduleNameUserString mod_name
588 else hPutStr stderr ("Compiling "
589 ++ moduleNameUserString mod_name
592 let (CmThreaded pcs1 hst1 hit1) = threaded1
593 let old_iface = lookupUFM hit1 mod_name
595 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
597 source_unchanged = isJust maybe_old_linkable
599 (hst1_strictDC, hit1_strictDC)
600 = retainInTopLevelEnvs
601 (filter (/= (name_of_summary summary1)) reachable_from_here)
605 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
607 compresult <- compile ghci_mode summary1 source_unchanged
608 old_iface hst1_strictDC hit1_strictDC pcs1
612 -- Compilation "succeeded", but didn't return a new
613 -- linkable, meaning that compilation wasn't needed, and the
614 -- new details were manufactured from the old iface.
615 CompOK pcs2 new_details new_iface Nothing
616 -> do let hst2 = addToUFM hst1 mod_name new_details
617 hit2 = addToUFM hit1 mod_name new_iface
618 threaded2 = CmThreaded pcs2 hst2 hit2
620 if ghci_mode == Interactive && verb >= 1 then
621 -- if we're using an object file, tell the user
622 case maybe_old_linkable of
623 Just (LM _ _ objs@(DotO _:_))
624 -> do hPutStr stderr (showSDoc (space <>
625 parens (hsep (text "using":
627 [ text o | DotO o <- objs ]))))
628 when (verb > 1) $ hPutStrLn stderr ""
633 when (verb == 1) $ hPutStrLn stderr ""
634 return (threaded2, Just old_linkable)
636 -- Compilation really did happen, and succeeded. A new
637 -- details, iface and linkable are returned.
638 CompOK pcs2 new_details new_iface (Just new_linkable)
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 when (verb == 1) $ hPutStrLn stderr ""
644 return (threaded2, Just new_linkable)
646 -- Compilation failed. compile may still have updated
649 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
650 when (verb == 1) $ hPutStrLn stderr ""
651 return (threaded2, Nothing)
653 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
654 removeFromTopLevelEnvs :: [ModuleName]
655 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
656 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
657 removeFromTopLevelEnvs zap_these (hst, hit, ui)
658 = (delListFromUFM hst zap_these,
659 delListFromUFM hit zap_these,
660 filterModuleLinkables (`notElem` zap_these) ui
663 retainInTopLevelEnvs :: [ModuleName]
664 -> (HomeSymbolTable, HomeIfaceTable)
665 -> (HomeSymbolTable, HomeIfaceTable)
666 retainInTopLevelEnvs keep_these (hst, hit)
667 = (retainInUFM hst keep_these,
668 retainInUFM hit keep_these
671 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
672 retainInUFM ufm keys_to_keep
673 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
675 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
677 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
678 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
679 downwards_closure_of_module summaries root
680 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
681 toEdge summ = (name_of_summary summ, ms_allimps summ)
682 res = simple_transitive_closure (map toEdge summaries) [root]
684 --trace (showSDoc (text "DC of mod" <+> ppr root
685 -- <+> text "=" <+> ppr res)) (
689 -- Calculate transitive closures from a set of roots given an adjacency list
690 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
691 simple_transitive_closure graph set
692 = let set2 = nub (concatMap dsts set ++ set)
693 dsts node = fromMaybe [] (lookup node graph)
695 if length set == length set2
697 else simple_transitive_closure graph set2
700 -- Calculate SCCs of the module graph, with or without taking into
701 -- account source imports.
702 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
703 topological_sort include_source_imports summaries
705 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
707 = (summ, name_of_summary summ,
708 (if include_source_imports
709 then ms_srcimps summ else []) ++ ms_imps summ)
711 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
712 mash_edge (summ, m, m_imports)
713 = case lookup m key_map of
714 Nothing -> panic "reverse_topological_sort"
715 Just mk -> (summ, mk,
716 -- ignore imports not from the home package
717 catMaybes (map (flip lookup key_map) m_imports))
719 edges = map toEdge summaries
720 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
721 scc_input = map mash_edge edges
722 sccs = stronglyConnComp scc_input
727 -- Chase downwards from the specified root set, returning summaries
728 -- for all home modules encountered. Only follow source-import
729 -- links. Also returns a Bool to indicate whether any of the roots
731 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
733 = do rootSummaries <- mapM getRootSummary rootNm
735 = any ((=="Main").moduleNameUserString.name_of_summary)
738 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
739 return (all_summaries, a_root_is_Main)
741 getRootSummary :: FilePath -> IO ModSummary
743 | haskellish_file file
744 = do exists <- doesFileExist file
745 if exists then summariseFile file else do
746 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
748 = do exists <- doesFileExist hs_file
749 if exists then summariseFile hs_file else do
750 exists <- doesFileExist lhs_file
751 if exists then summariseFile lhs_file else do
752 getSummary (mkModuleName file)
754 hs_file = file ++ ".hs"
755 lhs_file = file ++ ".lhs"
757 getSummary :: ModuleName -> IO ModSummary
759 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
760 = do found <- findModule nm
762 -- Be sure not to use the mod and location passed in to
763 -- summarise for any other purpose -- summarise may change
764 -- the module names in them if name of module /= name of file,
765 -- and put the changed versions in the returned summary.
766 -- These will then conflict with the passed-in versions.
767 Just (mod, location) -> summarise mod location
768 Nothing -> throwDyn (OtherError
769 ("can't find module `"
770 ++ showSDoc (ppr nm) ++ "'"))
772 -- loop invariant: homeSummaries doesn't contain package modules
773 loop :: [ModSummary] -> IO [ModSummary]
775 = do let allImps :: [ModuleName]
776 allImps = (nub . concatMap ms_imps) homeSummaries
777 let allHome -- all modules currently in homeSummaries
778 = map (moduleName.ms_mod) homeSummaries
780 = filter (`notElem` allHome) allImps
782 <- mapM getSummary neededImps
784 = filter (isHomeModule.ms_mod) neededSummaries
785 if null newHomeSummaries
786 then return homeSummaries
787 else loop (newHomeSummaries ++ homeSummaries)
790 -----------------------------------------------------------------------------
791 -- Summarising modules
793 -- We have two types of summarisation:
795 -- * Summarise a file. This is used for the root module passed to
796 -- cmLoadModule. The file is read, and used to determine the root
797 -- module name. The module name may differ from the filename.
799 -- * Summarise a module. We are given a module name, and must provide
800 -- a summary. The finder is used to locate the file in which the module
803 summariseFile :: FilePath -> IO ModSummary
805 = do hspp_fn <- preprocess file
806 modsrc <- readFile hspp_fn
808 let (srcimps,imps,mod_name) = getImports modsrc
809 (path, basename, ext) = splitFilename3 file
812 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
815 <- case ml_hs_file location of
816 Nothing -> return Nothing
817 Just src_fn -> maybe_getModificationTime src_fn
819 return (ModSummary mod
820 location{ml_hspp_file=Just hspp_fn}
824 -- Summarise a module, and pick up source and interface timestamps.
825 summarise :: Module -> ModuleLocation -> IO ModSummary
826 summarise mod location
828 = do let hs_fn = unJust "summarise" (ml_hs_file location)
829 hspp_fn <- preprocess hs_fn
830 modsrc <- readFile hspp_fn
831 let (srcimps,imps,mod_name) = getImports modsrc
834 <- case ml_hs_file location of
835 Nothing -> return Nothing
836 Just src_fn -> maybe_getModificationTime src_fn
838 if mod_name == moduleName mod
840 else throwDyn (OtherError
841 (showSDoc (text "file name does not match module name: "
842 <+> ppr (moduleName mod) <+> text "vs"
845 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
850 = return (ModSummary mod location [] [] Nothing)
852 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
853 maybe_getModificationTime fn
854 = (do time <- getModificationTime fn
857 (\err -> return Nothing)