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 -- We could at this point detect cycles which aren't broken by
253 -- a source-import, and complain immediately, but it seems better
254 -- to let upsweep_mods do this, so at least some useful work gets
255 -- done before the upsweep is abandoned.
257 = filter (\scc -> any (`notElem` stable_mods)
258 (map name_of_summary (flattenSCC scc)))
261 --hPutStrLn stderr "after tsort:\n"
262 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
264 -- Because we don't take into account source imports when doing
265 -- the topological sort, there shouldn't be any cycles in mg2.
266 -- If there is, we complain and give up -- the user needs to
267 -- break the cycle using a boot file.
269 -- Now do the upsweep, calling compile for each module in
270 -- turn. Final result is version 3 of everything.
272 let threaded2 = CmThreaded pcs1 hst1 hit1
274 (upsweep_complete_success, threaded3, modsUpswept, newLis)
275 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
276 threaded2 upsweep_these
278 let ui3 = add_to_ui valid_linkables newLis
279 let (CmThreaded pcs3 hst3 hit3) = threaded3
281 -- At this point, modsUpswept and newLis should have the same
282 -- length, so there is one new (or old) linkable for each
283 -- mod which was processed (passed to compile).
285 -- Make modsDone be the summaries for each home module now
286 -- available; this should equal the domains of hst3 and hit3.
287 -- (NOT STRICTLY TRUE if an interactive session was started
288 -- with some object on disk ???)
289 -- Get in in a roughly top .. bottom order (hence reverse).
291 let modsDone = reverse modsUpswept ++ stable_summaries
293 -- Try and do linking in some form, depending on whether the
294 -- upsweep was completely or only partially successful.
296 if upsweep_complete_success
299 -- Easy; just relink it all.
300 do when (verb >= 2) $
301 hPutStrLn stderr "Upsweep completely successful."
303 <- link ghci_mode dflags a_root_is_Main ui3 pls1
306 -> panic "cmLoadModule: link failed (1)"
308 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
312 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
313 return (cmstate3, True,
317 -- Tricky. We need to back out the effects of compiling any
318 -- half-done cycles, both so as to clean up the top level envs
319 -- and to avoid telling the interactive linker to link them.
320 do when (verb >= 2) $
321 hPutStrLn stderr "Upsweep partially successful."
324 = map name_of_summary modsDone
325 let mods_to_zap_names
326 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
327 let (hst4, hit4, ui4)
328 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
330 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
331 let mods_to_keep_names
332 = map name_of_summary mods_to_keep
333 -- we could get the relevant linkables by filtering newLis, but
334 -- it seems easier to drag them out of the updated, cleaned-up UI
335 let linkables_to_link
336 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
339 linkresult <- link ghci_mode dflags False linkables_to_link pls1
342 -> panic "cmLoadModule: link failed (2)"
344 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
345 ui=ui4, mg=mods_to_keep,
348 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
349 return (cmstate4, False,
350 map ms_mod mods_to_keep)
353 -----------------------------------------------------------------------------
357 :: [Linkable] -- old linkables
358 -> [ModSummary] -- all modules in the program
359 -> IO [Linkable] -- still-valid linkables
361 getValidLinkables old_linkables summaries
362 = do lis <- mapM (getValidLinkable old_linkables) summaries
365 getValidLinkable old_linkables summary
366 = do let mod_name = moduleName (ms_mod summary)
368 <- case ml_obj_file (ms_location summary) of
369 Nothing -> return Nothing
370 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
372 -- find an old in-core linkable if we have one. (forget about
373 -- on-disk linkables for now, we'll check again whether there's
374 -- one here below, just in case a new one has popped up recently).
375 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
378 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
381 -- The most recent of the old UI linkable or whatever we could
382 -- find on disk. Is returned as the linkable if compile
383 -- doesn't think we need to recompile.
385 = case (maybe_old_linkable, maybe_disk_linkable) of
386 (Nothing, Nothing) -> []
387 (Nothing, Just di) -> [di]
388 (Just ui, Nothing) -> [ui]
390 | linkableTime ui >= linkableTime di -> [ui]
393 -- only linkables newer than the source code are valid
394 let maybe_src_date = ms_hs_date summary
397 = case maybe_src_date of
398 Nothing -> panic "valid_linkable_list"
400 -> filter (\li -> linkableTime li > src_date) linkable_list
402 return valid_linkable_list
406 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
407 maybe_getFileLinkable mod_name obj_fn
408 = do obj_exist <- doesFileExist obj_fn
412 do let stub_fn = case splitFilename3 obj_fn of
413 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
414 stub_exist <- doesFileExist stub_fn
415 obj_time <- getModificationTime obj_fn
417 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
418 else return (Just (LM obj_time mod_name [DotO obj_fn]))
421 -----------------------------------------------------------------------------
422 -- Do a pre-upsweep without use of "compile", to establish a
423 -- (downward-closed) set of stable modules which can be retained
424 -- in the top-level environments. Also return linkables for those
425 -- modules determined to be stable, since (in Batch mode, at least)
426 -- there's no other way for them to get into UI.
428 preUpsweep :: [Linkable] -- valid linkables
429 -> [ModuleName] -- names of all mods encountered in downsweep
430 -> [ModuleName] -- accumulating stable modules
431 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
432 -> IO [ModuleName] -- stable modules
434 preUpsweep valid_lis all_home_mods stable []
436 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
437 = do let scc = flattenSCC scc0
438 scc_allhomeimps :: [ModuleName]
440 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
441 all_imports_in_scc_or_stable
442 = all in_stable_or_scc scc_allhomeimps
444 = map name_of_summary scc
446 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
447 m `elem` scc_names || m `elem` stable
450 <- if not all_imports_in_scc_or_stable
451 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
453 else do --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
454 return (all is_stable scc)
455 if not all_scc_stable
456 then preUpsweep valid_lis all_home_mods stable sccs
457 else preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
459 where is_stable new_summary
460 = isJust (findModuleLinkable_maybe valid_lis (name_of_summary new_summary))
463 -- Helper for preUpsweep. Assuming that new_summary's imports are all
464 -- stable (in the sense of preUpsweep), determine if new_summary is itself
465 -- stable, and, if so, in batch mode, return its linkable.
466 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
467 findInSummaries old_summaries mod_name
468 = [s | s <- old_summaries, name_of_summary s == mod_name]
471 -- Return (names of) all those in modsDone who are part of a cycle
472 -- as defined by theGraph.
473 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
474 findPartiallyCompletedCycles modsDone theGraph
478 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
479 chew ((CyclicSCC vs):rest)
480 = let names_in_this_cycle = nub (map name_of_summary vs)
482 = nub ([done | done <- modsDone,
483 done `elem` names_in_this_cycle])
484 chewed_rest = chew rest
486 if not (null mods_in_this_cycle)
487 && length mods_in_this_cycle < length names_in_this_cycle
488 then mods_in_this_cycle ++ chewed_rest
492 -- Does this ModDetails export Main.main?
493 --exports_main :: ModDetails -> Bool
495 -- = isJust (lookupNameEnv (md_types md) mainName)
498 -- Add the given (LM-form) Linkables to the UI, overwriting previous
499 -- versions if they exist.
500 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
504 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
506 = li : filter (\li2 -> not (for_same_module li li2)) ui
508 for_same_module :: Linkable -> Linkable -> Bool
509 for_same_module li1 li2
510 = not (is_package_linkable li1)
511 && not (is_package_linkable li2)
512 && modname_of_linkable li1 == modname_of_linkable li2
515 data CmThreaded -- stuff threaded through individual module compilations
516 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
519 -- Compile multiple modules, stopping as soon as an error appears.
520 -- There better had not be any cyclic groups here -- we check for them.
521 upsweep_mods :: GhciMode
523 -> UnlinkedImage -- valid linkables
524 -> (ModuleName -> [ModuleName]) -- to construct downward closures
525 -> CmThreaded -- PCS & HST & HIT
526 -> [SCC ModSummary] -- mods to do (the worklist)
527 -- ...... RETURNING ......
528 -> IO (Bool{-complete success?-},
530 [ModSummary], -- mods which succeeded
531 [Linkable]) -- new linkables
533 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
535 = return (True, threaded, [], [])
537 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
539 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
540 unwords (map (moduleNameUserString.name_of_summary) ms))
541 return (False, threaded, [], [])
543 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
544 ((AcyclicSCC mod):mods)
545 = do --case threaded of
546 -- CmThreaded pcsz hstz hitz
547 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
549 (threaded1, maybe_linkable)
550 <- upsweep_mod ghci_mode dflags oldUI threaded mod
551 (reachable_from (name_of_summary mod))
552 case maybe_linkable of
554 -> -- No errors; do the rest
555 do (restOK, threaded2, modOKs, linkables)
556 <- upsweep_mods ghci_mode dflags oldUI reachable_from
558 return (restOK, threaded2, mod:modOKs, linkable:linkables)
559 Nothing -- we got a compilation error; give up now
560 -> return (False, threaded1, [], [])
563 -- Compile a single module. Always produce a Linkable for it if
564 -- successful. If no compilation happened, return the old Linkable.
565 upsweep_mod :: GhciMode
571 -> IO (CmThreaded, Maybe Linkable)
573 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
575 let mod_name = name_of_summary summary1
576 let verb = verbosity dflags
579 if (ghci_mode == Batch)
580 then hPutStr stderr (progName ++ ": module "
581 ++ moduleNameUserString mod_name
583 else hPutStr stderr ("Compiling "
584 ++ moduleNameUserString mod_name
587 let (CmThreaded pcs1 hst1 hit1) = threaded1
588 let old_iface = lookupUFM hit1 mod_name
590 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
592 source_unchanged = isJust maybe_old_linkable
594 (hst1_strictDC, hit1_strictDC)
595 = retainInTopLevelEnvs
596 (filter (/= (name_of_summary summary1)) reachable_from_here)
600 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
602 compresult <- compile ghci_mode summary1 source_unchanged
603 old_iface hst1_strictDC hit1_strictDC pcs1
607 -- Compilation "succeeded", but didn't return a new
608 -- linkable, meaning that compilation wasn't needed, and the
609 -- new details were manufactured from the old iface.
610 CompOK pcs2 new_details new_iface Nothing
611 -> do let hst2 = addToUFM hst1 mod_name new_details
612 hit2 = addToUFM hit1 mod_name new_iface
613 threaded2 = CmThreaded pcs2 hst2 hit2
615 if ghci_mode == Interactive && verb >= 1 then
616 -- if we're using an object file, tell the user
617 case maybe_old_linkable of
618 Just (LM _ _ objs@(DotO _:_))
619 -> do hPutStr stderr (showSDoc (space <>
620 parens (hsep (text "using":
622 [ text o | DotO o <- objs ]))))
623 when (verb > 1) $ hPutStrLn stderr ""
628 when (verb == 1) $ hPutStrLn stderr ""
629 return (threaded2, Just old_linkable)
631 -- Compilation really did happen, and succeeded. A new
632 -- details, iface and linkable are returned.
633 CompOK pcs2 new_details new_iface (Just new_linkable)
634 -> do let hst2 = addToUFM hst1 mod_name new_details
635 hit2 = addToUFM hit1 mod_name new_iface
636 threaded2 = CmThreaded pcs2 hst2 hit2
638 when (verb == 1) $ hPutStrLn stderr ""
639 return (threaded2, Just new_linkable)
641 -- Compilation failed. compile may still have updated
644 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
645 when (verb == 1) $ hPutStrLn stderr ""
646 return (threaded2, Nothing)
648 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
649 removeFromTopLevelEnvs :: [ModuleName]
650 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
651 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
652 removeFromTopLevelEnvs zap_these (hst, hit, ui)
653 = (delListFromUFM hst zap_these,
654 delListFromUFM hit zap_these,
655 filterModuleLinkables (`notElem` zap_these) ui
658 retainInTopLevelEnvs :: [ModuleName]
659 -> (HomeSymbolTable, HomeIfaceTable)
660 -> (HomeSymbolTable, HomeIfaceTable)
661 retainInTopLevelEnvs keep_these (hst, hit)
662 = (retainInUFM hst keep_these,
663 retainInUFM hit keep_these
666 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
667 retainInUFM ufm keys_to_keep
668 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
670 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
672 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
673 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
674 downwards_closure_of_module summaries root
675 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
676 toEdge summ = (name_of_summary summ, ms_allimps summ)
677 res = simple_transitive_closure (map toEdge summaries) [root]
679 --trace (showSDoc (text "DC of mod" <+> ppr root
680 -- <+> text "=" <+> ppr res)) (
684 -- Calculate transitive closures from a set of roots given an adjacency list
685 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
686 simple_transitive_closure graph set
687 = let set2 = nub (concatMap dsts set ++ set)
688 dsts node = fromMaybe [] (lookup node graph)
690 if length set == length set2
692 else simple_transitive_closure graph set2
695 -- Calculate SCCs of the module graph, with or without taking into
696 -- account source imports.
697 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
698 topological_sort include_source_imports summaries
700 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
702 = (summ, name_of_summary summ,
703 (if include_source_imports
704 then ms_srcimps summ else []) ++ ms_imps summ)
706 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
707 mash_edge (summ, m, m_imports)
708 = case lookup m key_map of
709 Nothing -> panic "reverse_topological_sort"
710 Just mk -> (summ, mk,
711 -- ignore imports not from the home package
712 catMaybes (map (flip lookup key_map) m_imports))
714 edges = map toEdge summaries
715 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
716 scc_input = map mash_edge edges
717 sccs = stronglyConnComp scc_input
722 -- Chase downwards from the specified root set, returning summaries
723 -- for all home modules encountered. Only follow source-import
724 -- links. Also returns a Bool to indicate whether any of the roots
726 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
728 = do rootSummaries <- mapM getRootSummary rootNm
730 = any ((=="Main").moduleNameUserString.name_of_summary)
733 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
734 return (all_summaries, a_root_is_Main)
736 getRootSummary :: FilePath -> IO ModSummary
738 | haskellish_file file
739 = do exists <- doesFileExist file
740 if exists then summariseFile file else do
741 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
743 = do exists <- doesFileExist hs_file
744 if exists then summariseFile hs_file else do
745 exists <- doesFileExist lhs_file
746 if exists then summariseFile lhs_file else do
747 getSummary (mkModuleName file)
749 hs_file = file ++ ".hs"
750 lhs_file = file ++ ".lhs"
752 getSummary :: ModuleName -> IO ModSummary
754 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
755 = do found <- findModule nm
757 -- Be sure not to use the mod and location passed in to
758 -- summarise for any other purpose -- summarise may change
759 -- the module names in them if name of module /= name of file,
760 -- and put the changed versions in the returned summary.
761 -- These will then conflict with the passed-in versions.
762 Just (mod, location) -> summarise mod location
763 Nothing -> throwDyn (OtherError
764 ("can't find module `"
765 ++ showSDoc (ppr nm) ++ "'"))
767 -- loop invariant: homeSummaries doesn't contain package modules
768 loop :: [ModSummary] -> IO [ModSummary]
770 = do let allImps :: [ModuleName]
771 allImps = (nub . concatMap ms_imps) homeSummaries
772 let allHome -- all modules currently in homeSummaries
773 = map (moduleName.ms_mod) homeSummaries
775 = filter (`notElem` allHome) allImps
777 <- mapM getSummary neededImps
779 = filter (isHomeModule.ms_mod) neededSummaries
780 if null newHomeSummaries
781 then return homeSummaries
782 else loop (newHomeSummaries ++ homeSummaries)
785 -----------------------------------------------------------------------------
786 -- Summarising modules
788 -- We have two types of summarisation:
790 -- * Summarise a file. This is used for the root module passed to
791 -- cmLoadModule. The file is read, and used to determine the root
792 -- module name. The module name may differ from the filename.
794 -- * Summarise a module. We are given a module name, and must provide
795 -- a summary. The finder is used to locate the file in which the module
798 summariseFile :: FilePath -> IO ModSummary
800 = do hspp_fn <- preprocess file
801 modsrc <- readFile hspp_fn
803 let (srcimps,imps,mod_name) = getImports modsrc
804 (path, basename, ext) = splitFilename3 file
807 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
810 <- case ml_hs_file location of
811 Nothing -> return Nothing
812 Just src_fn -> maybe_getModificationTime src_fn
814 return (ModSummary mod
815 location{ml_hspp_file=Just hspp_fn}
819 -- Summarise a module, and pick up source and interface timestamps.
820 summarise :: Module -> ModuleLocation -> IO ModSummary
821 summarise mod location
823 = do let hs_fn = unJust "summarise" (ml_hs_file location)
824 hspp_fn <- preprocess hs_fn
825 modsrc <- readFile hspp_fn
826 let (srcimps,imps,mod_name) = getImports modsrc
829 <- case ml_hs_file location of
830 Nothing -> return Nothing
831 Just src_fn -> maybe_getModificationTime src_fn
833 if mod_name == moduleName mod
835 else throwDyn (OtherError
836 (showSDoc (text "file name does not match module name: "
837 <+> ppr (moduleName mod) <+> text "vs"
840 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
845 = return (ModSummary mod location [] [] Nothing)
847 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
848 maybe_getModificationTime fn
849 = (do time <- getModificationTime fn
852 (\err -> return Nothing)