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 )
42 import CmdLineOpts ( DynFlags(..) )
46 import Interpreter ( HValue )
47 import HscMain ( hscExpr )
49 import PrelGHC ( unsafeCoerce# )
53 import Exception ( throwDyn )
56 import Time ( ClockTime )
57 import Directory ( getModificationTime, doesFileExist )
61 import Maybe ( catMaybes, fromMaybe, isJust, fromJust )
66 cmInit :: GhciMode -> IO CmState
73 -> Bool -- True <=> wrap in 'print' to get an IO-typed result
76 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
77 cmGetExpr cmstate dflags wrap_io mod expr
78 = do (new_pcs, maybe_stuff) <-
79 hscExpr dflags wrap_io hst hit pcs mod expr
81 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
82 Just (bcos, print_unqual, ty) -> do
83 hValue <- linkExpr pls bcos
84 return (cmstate{ pcs=new_pcs },
85 Just (hValue, print_unqual, ty))
87 -- ToDo: check that the module we passed in is sane/exists?
89 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
91 -- The HValue should represent a value of type IO () (Perhaps IO a?)
92 cmRunExpr :: HValue -> IO ()
94 = do unsafeCoerce# hval :: IO ()
98 emptyHIT :: HomeIfaceTable
100 emptyHST :: HomeSymbolTable
103 -- Persistent state for the entire system
106 hst :: HomeSymbolTable, -- home symbol table
107 hit :: HomeIfaceTable, -- home interface table
108 ui :: UnlinkedImage, -- the unlinked images
109 mg :: ModuleGraph, -- the module graph
110 gmode :: GhciMode, -- NEVER CHANGES
112 pcs :: PersistentCompilerState, -- compile's persistent state
113 pls :: PersistentLinkerState -- link's persistent state
116 emptyCmState :: GhciMode -> IO CmState
118 = do pcs <- initPersistentCompilerState
120 return (CmState { hst = emptyHST,
129 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
130 emptyUI :: UnlinkedImage
133 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
134 emptyMG :: ModuleGraph
139 Unload the compilation manager's state: everything it knows about the
140 current collection of modules in the Home package.
143 cmUnload :: CmState -> IO CmState
145 = do -- Throw away the old home dir cache
147 -- Throw away the HIT and the HST
148 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
150 CmState{ hst=hst, hit=hit } = state
151 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
154 The real business of the compilation manager: given a system state and
155 a module name, try and bring the module up to date, probably changing
156 the system state at the same time.
159 cmLoadModule :: CmState
161 -> IO (CmState, -- new state
162 Bool, -- was successful
163 [Module]) -- list of modules loaded
165 cmLoadModule cmstate1 rootname
166 = do -- version 1's are the original, before downsweep
167 let pls1 = pls cmstate1
168 let pcs1 = pcs cmstate1
169 let hst1 = hst cmstate1
170 let hit1 = hit cmstate1
171 -- similarly, ui1 is the (complete) set of linkables from
172 -- the previous pass, if any.
173 let ui1 = ui cmstate1
174 let mg1 = mg cmstate1
176 let ghci_mode = gmode cmstate1 -- this never changes
178 -- Do the downsweep to reestablish the module graph
179 -- then generate version 2's by retaining in HIT,HST,UI a
180 -- stable set S of modules, as defined below.
182 dflags <- getDynFlags
183 let verb = verbosity dflags
185 showPass dflags "Chasing dependencies"
186 when (verb >= 1 && ghci_mode == Batch) $
187 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
189 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
190 let mg2unsorted_names = map name_of_summary mg2unsorted
192 -- reachable_from follows source as well as normal imports
193 let reachable_from :: ModuleName -> [ModuleName]
194 reachable_from = downwards_closure_of_module mg2unsorted
196 -- should be cycle free; ignores 'import source's
197 let mg2 = topological_sort False mg2unsorted
198 -- ... whereas this takes them into account. Used for
199 -- backing out partially complete cycles following a failed
200 -- upsweep, and for removing from hst/hit all the modules
201 -- not in strict downwards closure, during calls to compile.
202 let mg2_with_srcimps = topological_sort True mg2unsorted
204 -- Sort out which linkables we wish to keep in the unlinked image.
205 -- See getValidLinkables below for details.
206 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
209 -- Figure out a stable set of modules which can be retained
210 -- the top level envs, to avoid upsweeping them. Goes to a
211 -- bit of trouble to avoid upsweeping module cycles.
213 -- Construct a set S of stable modules like this:
214 -- Travel upwards, over the sccified graph. For each scc
215 -- of modules ms, add ms to S only if:
216 -- 1. All home imports of ms are either in ms or S
217 -- 2. A valid linkable exists for each module in ms
220 <- preUpsweep valid_linkables ui1 mg2unsorted_names
224 = concatMap (findInSummaries mg2unsorted) stable_mods
227 = filter (\m -> linkableModName m `elem` stable_mods)
231 putStrLn (showSDoc (text "STABLE MODULES:"
232 <+> sep (map (text.moduleNameUserString) stable_mods)))
234 -- unload any modules which aren't going to be re-linked this
236 pls2 <- unload ghci_mode dflags stable_linkables pls1
238 -- We could at this point detect cycles which aren't broken by
239 -- a source-import, and complain immediately, but it seems better
240 -- to let upsweep_mods do this, so at least some useful work gets
241 -- done before the upsweep is abandoned.
243 = filter (\scc -> any (`notElem` stable_mods)
244 (map name_of_summary (flattenSCC scc)))
247 --hPutStrLn stderr "after tsort:\n"
248 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
250 -- Because we don't take into account source imports when doing
251 -- the topological sort, there shouldn't be any cycles in mg2.
252 -- If there is, we complain and give up -- the user needs to
253 -- break the cycle using a boot file.
255 -- Now do the upsweep, calling compile for each module in
256 -- turn. Final result is version 3 of everything.
258 let threaded2 = CmThreaded pcs1 hst1 hit1
260 (upsweep_complete_success, threaded3, modsUpswept, newLis)
261 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
262 threaded2 upsweep_these
264 let ui3 = add_to_ui valid_linkables newLis
265 let (CmThreaded pcs3 hst3 hit3) = threaded3
267 -- At this point, modsUpswept and newLis should have the same
268 -- length, so there is one new (or old) linkable for each
269 -- mod which was processed (passed to compile).
271 -- Make modsDone be the summaries for each home module now
272 -- available; this should equal the domains of hst3 and hit3.
273 -- (NOT STRICTLY TRUE if an interactive session was started
274 -- with some object on disk ???)
275 -- Get in in a roughly top .. bottom order (hence reverse).
277 let modsDone = reverse modsUpswept ++ stable_summaries
279 -- Try and do linking in some form, depending on whether the
280 -- upsweep was completely or only partially successful.
282 if upsweep_complete_success
285 -- Easy; just relink it all.
286 do when (verb >= 2) $
287 hPutStrLn stderr "Upsweep completely successful."
289 -- clean up after ourselves
290 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
293 <- link ghci_mode dflags a_root_is_Main ui3 pls2
296 -> panic "cmLoadModule: link failed (1)"
299 = CmState { hst=hst3, hit=hit3,
303 return (cmstate3, True,
307 -- Tricky. We need to back out the effects of compiling any
308 -- half-done cycles, both so as to clean up the top level envs
309 -- and to avoid telling the interactive linker to link them.
310 do when (verb >= 2) $
311 hPutStrLn stderr "Upsweep partially successful."
314 = map name_of_summary modsDone
315 let mods_to_zap_names
316 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
317 let (hst4, hit4, ui4)
318 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
320 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
321 let mods_to_keep_names
322 = map name_of_summary mods_to_keep
323 -- we could get the relevant linkables by filtering newLis, but
324 -- it seems easier to drag them out of the updated, cleaned-up UI
325 let linkables_to_link
326 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
329 -- clean up after ourselves
330 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
332 linkresult <- link ghci_mode dflags False linkables_to_link pls2
335 -> panic "cmLoadModule: link failed (2)"
338 = CmState { hst=hst4, hit=hit4,
339 ui=ui4, mg=mods_to_keep,
340 gmode=ghci_mode, pcs=pcs3, pls=pls3 }
341 return (cmstate4, False,
342 map ms_mod mods_to_keep)
345 ppFilesFromSummaries summaries
346 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
348 -----------------------------------------------------------------------------
351 -- For each module (or SCC of modules), we take:
353 -- - the old in-core linkable, if available
354 -- - an on-disk linkable, if available
356 -- and we take the youngest of these, provided it is younger than the
357 -- source file. We ignore the on-disk linkables unless all of the
358 -- dependents of this SCC also have on-disk linkables.
360 -- If a module has a valid linkable, then it may be STABLE (see below),
361 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
364 -- ToDo: this pass could be merged with the preUpsweep.
367 :: [Linkable] -- old linkables
368 -> [ModuleName] -- all home modules
369 -> [SCC ModSummary] -- all modules in the program, dependency order
370 -> IO [Linkable] -- still-valid linkables
372 getValidLinkables old_linkables all_home_mods module_graph
373 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
375 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
377 scc = flattenSCC scc0
378 scc_names = map name_of_summary scc
379 home_module m = m `elem` all_home_mods && m `notElem` scc_names
380 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
382 has_object m = case findModuleLinkable_maybe new_linkables m of
384 Just l -> isObjectLinkable l
386 objects_allowed = all has_object scc_allhomeimps
390 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
392 -- since an scc can contain only all objects or no objects at all,
393 -- we have to check whether we got all objects or not, and re-do
394 -- the linkable check if not.
396 <- if objects_allowed && not (all isObjectLinkable these_linkables)
397 then foldM (getValidLinkable old_linkables False) [] scc
398 else return these_linkables
400 return (adjusted_linkables ++ new_linkables)
403 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
405 getValidLinkable old_linkables objects_allowed new_linkables summary
407 let mod_name = name_of_summary summary
410 <- if (not objects_allowed)
412 else case ml_obj_file (ms_location summary) of
413 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
414 Nothing -> return Nothing
416 -- find an old in-core linkable if we have one. (forget about
417 -- on-disk linkables for now, we'll check again whether there's
418 -- one here below, just in case a new one has popped up recently).
419 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
422 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
425 -- The most recent of the old UI linkable or whatever we could
426 -- find on disk is returned as the linkable if compile
427 -- doesn't think we need to recompile.
429 = case (maybe_old_linkable, maybe_disk_linkable) of
430 (Nothing, Nothing) -> []
431 (Nothing, Just di) -> [di]
432 (Just ui, Nothing) -> [ui]
434 | linkableTime ui >= linkableTime di -> [ui]
437 -- only linkables newer than the source code are valid
438 let maybe_src_date = ms_hs_date summary
441 = case maybe_src_date of
442 Nothing -> panic "valid_linkable_list"
444 -> filter (\li -> linkableTime li > src_date) linkable_list
446 return (valid_linkable_list ++ new_linkables)
449 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
450 maybe_getFileLinkable mod_name obj_fn
451 = do obj_exist <- doesFileExist obj_fn
455 do let stub_fn = case splitFilename3 obj_fn of
456 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
457 stub_exist <- doesFileExist stub_fn
458 obj_time <- getModificationTime obj_fn
460 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
461 else return (Just (LM obj_time mod_name [DotO obj_fn]))
464 -----------------------------------------------------------------------------
465 -- Do a pre-upsweep without use of "compile", to establish a
466 -- (downward-closed) set of stable modules for which we won't call compile.
468 preUpsweep :: [Linkable] -- new valid linkables
469 -> [Linkable] -- old linkables
470 -> [ModuleName] -- names of all mods encountered in downsweep
471 -> [ModuleName] -- accumulating stable modules
472 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
473 -> IO [ModuleName] -- stable modules
475 preUpsweep valid_lis old_lis all_home_mods stable []
477 preUpsweep valid_lis old_lis all_home_mods stable (scc0:sccs)
478 = do let scc = flattenSCC scc0
479 scc_allhomeimps :: [ModuleName]
481 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
482 all_imports_in_scc_or_stable
483 = all in_stable_or_scc scc_allhomeimps
485 = map name_of_summary scc
487 = m `elem` scc_names || m `elem` stable
489 -- now we check for valid linkables: each module in the SCC must
490 -- have a valid linkable (see getValidLinkables above), and the
491 -- newest linkable must be the same as the previous linkable for
492 -- this module (if one exists).
493 has_valid_linkable new_summary
494 = case findModuleLinkable_maybe valid_lis modname of
496 Just l -> case findModuleLinkable_maybe old_lis modname of
498 Just m -> linkableTime l == linkableTime m
499 where modname = name_of_summary new_summary
501 scc_is_stable = all_imports_in_scc_or_stable
502 && all has_valid_linkable scc
505 then preUpsweep valid_lis old_lis all_home_mods
506 (scc_names++stable) sccs
507 else preUpsweep valid_lis old_lis all_home_mods
513 -- Helper for preUpsweep. Assuming that new_summary's imports are all
514 -- stable (in the sense of preUpsweep), determine if new_summary is itself
515 -- stable, and, if so, in batch mode, return its linkable.
516 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
517 findInSummaries old_summaries mod_name
518 = [s | s <- old_summaries, name_of_summary s == mod_name]
520 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
521 findModInSummaries old_summaries mod
522 = case [s | s <- old_summaries, ms_mod s == mod] of
526 -- Return (names of) all those in modsDone who are part of a cycle
527 -- as defined by theGraph.
528 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
529 findPartiallyCompletedCycles modsDone theGraph
533 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
534 chew ((CyclicSCC vs):rest)
535 = let names_in_this_cycle = nub (map name_of_summary vs)
537 = nub ([done | done <- modsDone,
538 done `elem` names_in_this_cycle])
539 chewed_rest = chew rest
541 if not (null mods_in_this_cycle)
542 && length mods_in_this_cycle < length names_in_this_cycle
543 then mods_in_this_cycle ++ chewed_rest
547 -- Add the given (LM-form) Linkables to the UI, overwriting previous
548 -- versions if they exist.
549 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
551 = filter (not_in lis) ui ++ lis
553 not_in :: [Linkable] -> Linkable -> Bool
555 = all (\l -> linkableModName l /= mod) lis
556 where mod = linkableModName li
559 data CmThreaded -- stuff threaded through individual module compilations
560 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
563 -- Compile multiple modules, stopping as soon as an error appears.
564 -- There better had not be any cyclic groups here -- we check for them.
565 upsweep_mods :: GhciMode
567 -> UnlinkedImage -- valid linkables
568 -> (ModuleName -> [ModuleName]) -- to construct downward closures
569 -> CmThreaded -- PCS & HST & HIT
570 -> [SCC ModSummary] -- mods to do (the worklist)
571 -- ...... RETURNING ......
572 -> IO (Bool{-complete success?-},
574 [ModSummary], -- mods which succeeded
575 [Linkable]) -- new linkables
577 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
579 = return (True, threaded, [], [])
581 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
583 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
584 unwords (map (moduleNameUserString.name_of_summary) ms))
585 return (False, threaded, [], [])
587 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
588 ((AcyclicSCC mod):mods)
589 = do --case threaded of
590 -- CmThreaded pcsz hstz hitz
591 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
593 (threaded1, maybe_linkable)
594 <- upsweep_mod ghci_mode dflags oldUI threaded mod
595 (reachable_from (name_of_summary mod))
596 case maybe_linkable of
598 -> -- No errors; do the rest
599 do (restOK, threaded2, modOKs, linkables)
600 <- upsweep_mods ghci_mode dflags oldUI reachable_from
602 return (restOK, threaded2, mod:modOKs, linkable:linkables)
603 Nothing -- we got a compilation error; give up now
604 -> return (False, threaded1, [], [])
607 -- Compile a single module. Always produce a Linkable for it if
608 -- successful. If no compilation happened, return the old Linkable.
609 upsweep_mod :: GhciMode
615 -> IO (CmThreaded, Maybe Linkable)
617 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
619 let mod_name = name_of_summary summary1
620 let verb = verbosity dflags
623 if (ghci_mode == Batch)
624 then hPutStr stderr (progName ++ ": module "
625 ++ moduleNameUserString mod_name
627 else hPutStr stderr ("Compiling "
628 ++ moduleNameUserString mod_name
631 let (CmThreaded pcs1 hst1 hit1) = threaded1
632 let old_iface = lookupUFM hit1 mod_name
634 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
636 source_unchanged = isJust maybe_old_linkable
638 (hst1_strictDC, hit1_strictDC)
639 = retainInTopLevelEnvs
640 (filter (/= (name_of_summary summary1)) reachable_from_here)
644 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
646 compresult <- compile ghci_mode summary1 source_unchanged
647 old_iface hst1_strictDC hit1_strictDC pcs1
651 -- Compilation "succeeded", but didn't return a new
652 -- linkable, meaning that compilation wasn't needed, and the
653 -- new details were manufactured from the old iface.
654 CompOK pcs2 new_details new_iface Nothing
655 -> do let hst2 = addToUFM hst1 mod_name new_details
656 hit2 = addToUFM hit1 mod_name new_iface
657 threaded2 = CmThreaded pcs2 hst2 hit2
659 if ghci_mode == Interactive && verb >= 1 then
660 -- if we're using an object file, tell the user
662 (LM _ _ objs@(DotO _:_))
663 -> do hPutStrLn stderr (showSDoc (space <>
664 parens (hsep (text "using":
666 [ text o | DotO o <- objs ]))))
671 return (threaded2, Just old_linkable)
673 -- Compilation really did happen, and succeeded. A new
674 -- details, iface and linkable are returned.
675 CompOK pcs2 new_details new_iface (Just new_linkable)
676 -> do let hst2 = addToUFM hst1 mod_name new_details
677 hit2 = addToUFM hit1 mod_name new_iface
678 threaded2 = CmThreaded pcs2 hst2 hit2
680 return (threaded2, Just new_linkable)
682 -- Compilation failed. compile may still have updated
685 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
686 return (threaded2, Nothing)
688 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
689 removeFromTopLevelEnvs :: [ModuleName]
690 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
691 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
692 removeFromTopLevelEnvs zap_these (hst, hit, ui)
693 = (delListFromUFM hst zap_these,
694 delListFromUFM hit zap_these,
695 filterModuleLinkables (`notElem` zap_these) ui
698 retainInTopLevelEnvs :: [ModuleName]
699 -> (HomeSymbolTable, HomeIfaceTable)
700 -> (HomeSymbolTable, HomeIfaceTable)
701 retainInTopLevelEnvs keep_these (hst, hit)
702 = (retainInUFM hst keep_these,
703 retainInUFM hit keep_these
706 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
707 retainInUFM ufm keys_to_keep
708 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
710 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
712 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
713 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
714 downwards_closure_of_module summaries root
715 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
716 toEdge summ = (name_of_summary summ, ms_allimps summ)
717 res = simple_transitive_closure (map toEdge summaries) [root]
719 --trace (showSDoc (text "DC of mod" <+> ppr root
720 -- <+> text "=" <+> ppr res)) (
724 -- Calculate transitive closures from a set of roots given an adjacency list
725 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
726 simple_transitive_closure graph set
727 = let set2 = nub (concatMap dsts set ++ set)
728 dsts node = fromMaybe [] (lookup node graph)
730 if length set == length set2
732 else simple_transitive_closure graph set2
735 -- Calculate SCCs of the module graph, with or without taking into
736 -- account source imports.
737 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
738 topological_sort include_source_imports summaries
740 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
742 = (summ, name_of_summary summ,
743 (if include_source_imports
744 then ms_srcimps summ else []) ++ ms_imps summ)
746 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
747 mash_edge (summ, m, m_imports)
748 = case lookup m key_map of
749 Nothing -> panic "reverse_topological_sort"
750 Just mk -> (summ, mk,
751 -- ignore imports not from the home package
752 catMaybes (map (flip lookup key_map) m_imports))
754 edges = map toEdge summaries
755 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
756 scc_input = map mash_edge edges
757 sccs = stronglyConnComp scc_input
762 -- Chase downwards from the specified root set, returning summaries
763 -- for all home modules encountered. Only follow source-import
764 -- links. Also returns a Bool to indicate whether any of the roots
766 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
767 downsweep rootNm old_summaries
768 = do rootSummaries <- mapM getRootSummary rootNm
770 = any ((=="Main").moduleNameUserString.name_of_summary)
773 <- loop (concat (map ms_imps rootSummaries))
774 (filter (isHomeModule.ms_mod) rootSummaries)
775 return (all_summaries, a_root_is_Main)
777 getRootSummary :: FilePath -> IO ModSummary
779 | haskellish_file file
780 = do exists <- doesFileExist file
781 if exists then summariseFile file else do
782 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
784 = do exists <- doesFileExist hs_file
785 if exists then summariseFile hs_file else do
786 exists <- doesFileExist lhs_file
787 if exists then summariseFile lhs_file else do
788 getSummary (mkModuleName file)
790 hs_file = file ++ ".hs"
791 lhs_file = file ++ ".lhs"
793 getSummary :: ModuleName -> IO ModSummary
795 = do found <- findModule nm
797 Just (mod, location) -> do
798 let old_summary = findModInSummaries old_summaries mod
799 new_summary <- summarise mod location old_summary
801 Nothing -> return (fromJust old_summary)
804 Nothing -> throwDyn (OtherError
805 ("can't find module `"
806 ++ showSDoc (ppr nm) ++ "'"))
808 -- loop invariant: home_summaries doesn't contain package modules
809 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
810 loop [] home_summaries = return home_summaries
811 loop imps home_summaries
812 = do -- all modules currently in homeSummaries
813 let all_home = map (moduleName.ms_mod) home_summaries
815 -- imports for modules we don't already have
816 let needed_imps = nub (filter (`notElem` all_home) imps)
819 needed_summaries <- mapM getSummary needed_imps
821 -- get just the "home" modules
822 let new_home_summaries
823 = filter (isHomeModule.ms_mod) needed_summaries
825 -- loop, checking the new imports
826 let new_imps = concat (map ms_imps new_home_summaries)
827 loop new_imps (new_home_summaries ++ home_summaries)
829 -----------------------------------------------------------------------------
830 -- Summarising modules
832 -- We have two types of summarisation:
834 -- * Summarise a file. This is used for the root module passed to
835 -- cmLoadModule. The file is read, and used to determine the root
836 -- module name. The module name may differ from the filename.
838 -- * Summarise a module. We are given a module name, and must provide
839 -- a summary. The finder is used to locate the file in which the module
842 summariseFile :: FilePath -> IO ModSummary
844 = do hspp_fn <- preprocess file
845 modsrc <- readFile hspp_fn
847 let (srcimps,imps,mod_name) = getImports modsrc
848 (path, basename, ext) = splitFilename3 file
851 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
854 <- case ml_hs_file location of
855 Nothing -> return Nothing
856 Just src_fn -> maybe_getModificationTime src_fn
858 return (ModSummary mod
859 location{ml_hspp_file=Just hspp_fn}
863 -- Summarise a module, and pick up source and timestamp.
864 summarise :: Module -> ModuleLocation -> Maybe ModSummary
865 -> IO (Maybe ModSummary)
866 summarise mod location old_summary
868 = do let hs_fn = unJust "summarise" (ml_hs_file location)
871 <- case ml_hs_file location of
872 Nothing -> return Nothing
873 Just src_fn -> maybe_getModificationTime src_fn
875 -- return the cached summary if the source didn't change
876 case old_summary of {
877 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
880 hspp_fn <- preprocess hs_fn
881 modsrc <- readFile hspp_fn
882 let (srcimps,imps,mod_name) = getImports modsrc
885 <- case ml_hs_file location of
886 Nothing -> return Nothing
887 Just src_fn -> maybe_getModificationTime src_fn
889 when (mod_name /= moduleName mod) $
891 (showSDoc (text "file name does not match module name: "
892 <+> ppr (moduleName mod) <+> text "vs"
895 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
897 maybe_src_timestamp))
901 = return (Just (ModSummary mod location [] [] Nothing))
903 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
904 maybe_getModificationTime fn
905 = (do time <- getModificationTime fn
908 (\err -> return Nothing)