[project @ 2000-11-21 14:31:58 by simonmar]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CompManager]{The Compilation Manager}
5
6 \begin{code}
7 module CompManager ( cmInit, cmLoadModule,
8 #ifdef GHCI
9                      cmGetExpr, cmRunExpr,
10 #endif
11                      CmState, emptyCmState  -- abstract
12                    )
13 where
14
15 #include "HsVersions.h"
16
17 import CmLink
18 import CmTypes
19 import HscTypes
20 import Module           ( ModuleName, moduleName,
21                           isHomeModule, moduleEnvElts,
22                           moduleNameUserString )
23 import CmStaticInfo     ( PackageConfigInfo, GhciMode(..) )
24 import DriverPipeline
25 import GetImports
26 import HscTypes         ( HomeSymbolTable, HomeIfaceTable, 
27                           PersistentCompilerState, ModDetails(..) )
28 import Name             ( lookupNameEnv )
29 import Module
30 import PrelNames        ( mainName )
31 import HscMain          ( initPersistentCompilerState )
32 import Finder
33 import UniqFM           ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
34                           UniqFM, listToUFM )
35 import Unique           ( Uniquable )
36 import Digraph          ( SCC(..), stronglyConnComp )
37 import DriverFlags      ( getDynFlags )
38 import DriverPhases
39 import DriverUtil       ( BarfKind(..), splitFilename3 )
40 import ErrUtils         ( showPass )
41 import Util
42 import Outputable
43 import Panic            ( panic )
44
45 #ifdef GHCI
46 import CmdLineOpts      ( DynFlags(..) )
47 import Interpreter      ( HValue )
48 import HscMain          ( hscExpr )
49 import RdrName
50 import PrelGHC          ( unsafeCoerce# )
51 #endif
52
53 -- lang
54 import Exception        ( throwDyn )
55
56 -- std
57 import Time             ( ClockTime )
58 import Directory        ( getModificationTime, doesFileExist )
59 import IO
60 import Monad
61 import List             ( nub )
62 import Maybe            ( catMaybes, fromMaybe, isJust )
63 \end{code}
64
65
66 \begin{code}
67 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
68 cmInit raw_package_info gmode
69    = emptyCmState raw_package_info gmode
70
71 #ifdef GHCI
72 cmGetExpr :: CmState
73           -> DynFlags
74           -> ModuleName
75           -> String
76           -> IO (CmState, Maybe HValue)
77 cmGetExpr cmstate dflags modname expr
78    = do (new_pcs, maybe_unlinked_iexpr) <- 
79            hscExpr dflags hst hit pcs (mkHomeModule modname) expr
80         case maybe_unlinked_iexpr of
81            Nothing     -> return (cmstate{ pcs=new_pcs }, Nothing)
82            Just uiexpr -> do
83                 hValue <- linkExpr pls uiexpr
84                 return (cmstate{ pcs=new_pcs }, Just hValue)
85
86    -- ToDo: check that the module we passed in is sane/exists?
87    where
88        CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
89        PersistentCMState{ hst=hst, hit=hit } = pcms
90
91 -- The HValue should represent a value of type IO () (Perhaps IO a?)
92 cmRunExpr :: HValue -> IO ()
93 cmRunExpr hval
94    = do unsafeCoerce# hval :: IO ()
95         -- putStrLn "done."
96 #endif
97
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         pci   :: PackageConfigInfo,  -- NEVER CHANGES
106         gmode :: GhciMode            -- NEVER CHANGES
107      }
108
109 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
110 emptyPCMS pci gmode
111   = PersistentCMState { hst = emptyHST, hit = emptyHIT,
112                         ui  = emptyUI,  mg  = emptyMG, 
113                         pci = pci, gmode = gmode }
114
115 emptyHIT :: HomeIfaceTable
116 emptyHIT = emptyUFM
117 emptyHST :: HomeSymbolTable
118 emptyHST = emptyUFM
119
120
121
122 -- Persistent state for the entire system
123 data CmState
124    = CmState {
125         pcms   :: PersistentCMState,       -- CM's persistent state
126         pcs    :: PersistentCompilerState, -- compile's persistent state
127         pls    :: PersistentLinkerState    -- link's persistent state
128      }
129
130 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
131 emptyCmState pci gmode
132     = do let pcms = emptyPCMS pci gmode
133          pcs     <- initPersistentCompilerState
134          pls     <- emptyPLS
135          return (CmState { pcms   = pcms,
136                            pcs    = pcs,
137                            pls    = pls })
138
139 -- CM internal types
140 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
141 emptyUI :: UnlinkedImage
142 emptyUI = []
143
144 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
145 emptyMG :: ModuleGraph
146 emptyMG = []
147
148 \end{code}
149
150 The real business of the compilation manager: given a system state and
151 a module name, try and bring the module up to date, probably changing
152 the system state at the same time.
153
154 \begin{code}
155 cmLoadModule :: CmState 
156              -> FilePath
157              -> IO (CmState,            -- new state
158                     Bool,               -- was successful
159                     [ModuleName])       -- list of modules loaded
160
161 cmLoadModule cmstate1 rootname
162    = do -- version 1's are the original, before downsweep
163         let pcms1     = pcms   cmstate1
164         let pls1      = pls    cmstate1
165         let pcs1      = pcs    cmstate1
166         let mg1       = mg     pcms1
167         let hst1      = hst    pcms1
168         let hit1      = hit    pcms1
169         let ui1       = ui     pcms1
170    
171         let pcii      = pci   pcms1 -- this never changes
172         let ghci_mode = gmode pcms1 -- ToDo: fix!
173
174         -- Do the downsweep to reestablish the module graph
175         -- then generate version 2's by removing from HIT,HST,UI any
176         -- modules in the old MG which are not in the new one.
177
178         -- Throw away the old home dir cache
179         emptyHomeDirCache
180
181         dflags <- getDynFlags
182         let verb = verbosity dflags
183
184         showPass dflags "Chasing dependencies"
185
186         mg2unsorted <- downsweep [rootname]
187
188         let modnames1   = map name_of_summary mg1
189         let modnames2   = map name_of_summary mg2unsorted
190         let mods_to_zap = filter (`notElem` modnames2) modnames1
191
192         let (hst2, hit2, ui2)
193                = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
194         -- should be cycle free; ignores 'import source's
195         let mg2 = topological_sort False mg2unsorted
196         -- ... whereas this takes them into account.  Used for
197         -- backing out partially complete cycles following a failed
198         -- upsweep, and for removing from hst/hit all the modules
199         -- not in strict downwards closure, during calls to compile.
200         let mg2_with_srcimps = topological_sort True mg2unsorted
201       
202         let reachable_from :: ModuleName -> [ModuleName]
203             reachable_from = downwards_closure_of_module mg2unsorted
204
205         --hPutStrLn stderr "after tsort:\n"
206         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
207
208         -- Because we don't take into account source imports when doing
209         -- the topological sort, there shouldn't be any cycles in mg2.
210         -- If there is, we complain and give up -- the user needs to
211         -- break the cycle using a boot file.
212
213         -- Now do the upsweep, calling compile for each module in
214         -- turn.  Final result is version 3 of everything.
215
216         let threaded2 = CmThreaded pcs1 hst2 hit2
217
218         (upsweep_complete_success, threaded3, modsDone, newLis)
219            <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
220
221         let ui3 = add_to_ui ui2 newLis
222         let (CmThreaded pcs3 hst3 hit3) = threaded3
223
224         -- At this point, modsDone and newLis should have the same
225         -- length, so there is one new (or old) linkable for each 
226         -- mod which was processed (passed to compile).
227
228         -- Try and do linking in some form, depending on whether the
229         -- upsweep was completely or only partially successful.
230
231         if upsweep_complete_success
232
233          then 
234            -- Easy; just relink it all.
235            do when (verb >= 2) $ 
236                 hPutStrLn stderr "Upsweep completely successful."
237               linkresult 
238                  <- link ghci_mode dflags 
239                         (any exports_main (moduleEnvElts hst3)) 
240                         newLis pls1
241               case linkresult of
242                  LinkErrs _ _
243                     -> panic "cmLoadModule: link failed (1)"
244                  LinkOK pls3 
245                     -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3, 
246                                                           ui=ui3, mg=modsDone, 
247                                                           pci=pcii, gmode=ghci_mode }
248                           let cmstate3 
249                                  = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
250                           return (cmstate3, True, map name_of_summary modsDone)
251
252          else 
253            -- Tricky.  We need to back out the effects of compiling any
254            -- half-done cycles, both so as to clean up the top level envs
255            -- and to avoid telling the interactive linker to link them.
256            do when (verb >= 2) $
257                 hPutStrLn stderr "Upsweep partially successful."
258
259               let modsDone_names
260                      = map name_of_summary modsDone
261               let mods_to_zap_names 
262                      = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
263               let (hst4, hit4, ui4) 
264                      = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
265               let mods_to_keep
266                      = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
267               let mods_to_keep_names 
268                      = map name_of_summary mods_to_keep
269               -- we could get the relevant linkables by filtering newLis, but
270               -- it seems easier to drag them out of the updated, cleaned-up UI
271               let linkables_to_link 
272                      = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
273                            mods_to_keep_names
274
275               linkresult <- link ghci_mode dflags False linkables_to_link pls1
276               case linkresult of
277                  LinkErrs _ _
278                     -> panic "cmLoadModule: link failed (2)"
279                  LinkOK pls4
280                     -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4, 
281                                                           ui=ui4, mg=mods_to_keep,
282                                                           pci=pcii, gmode=ghci_mode }
283                           let cmstate4 
284                                  = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
285                           return (cmstate4, False, mods_to_keep_names)
286
287
288 -- Return (names of) all those in modsDone who are part of a cycle
289 -- as defined by theGraph.
290 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
291 findPartiallyCompletedCycles modsDone theGraph
292    = chew theGraph
293      where
294         chew [] = []
295         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
296         chew ((CyclicSCC vs):rest)
297            = let names_in_this_cycle = nub (map name_of_summary vs)
298                  mods_in_this_cycle  
299                     = nub ([done | done <- modsDone, 
300                                    done `elem` names_in_this_cycle])
301                  chewed_rest = chew rest
302              in 
303              if   not (null mods_in_this_cycle) 
304                   && length mods_in_this_cycle < length names_in_this_cycle
305              then mods_in_this_cycle ++ chewed_rest
306              else chewed_rest
307
308
309 -- Does this ModDetails export Main.main?
310 exports_main :: ModDetails -> Bool
311 exports_main md
312    = isJust (lookupNameEnv (md_types md) mainName)
313
314
315 -- Add the given (LM-form) Linkables to the UI, overwriting previous
316 -- versions if they exist.
317 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
318 add_to_ui ui lis
319    = foldr add1 ui lis
320      where
321         add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
322         add1 li ui
323            = li : filter (\li2 -> not (for_same_module li li2)) ui
324
325         for_same_module :: Linkable -> Linkable -> Bool
326         for_same_module li1 li2 
327            = not (is_package_linkable li1)
328              && not (is_package_linkable li2)
329              && modname_of_linkable li1 == modname_of_linkable li2
330                                   
331
332 data CmThreaded  -- stuff threaded through individual module compilations
333    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
334
335
336 -- Compile multiple modules, stopping as soon as an error appears.
337 -- There better had not be any cyclic groups here -- we check for them.
338 upsweep_mods :: GhciMode
339              -> UnlinkedImage         -- old linkables
340              -> (ModuleName -> [ModuleName])  -- to construct downward closures
341              -> CmThreaded            -- PCS & HST & HIT
342              -> [SCC ModSummary]      -- mods to do (the worklist)
343                                       -- ...... RETURNING ......
344              -> IO (Bool{-complete success?-},
345                     CmThreaded,
346                     [ModSummary],     -- mods which succeeded
347                     [Linkable])       -- new linkables
348
349 upsweep_mods ghci_mode oldUI reachable_from threaded 
350      []
351    = return (True, threaded, [], [])
352
353 upsweep_mods ghci_mode oldUI reachable_from threaded 
354      ((CyclicSCC ms):_)
355    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
356                           unwords (map (moduleNameUserString.name_of_summary) ms))
357         return (False, threaded, [], [])
358
359 upsweep_mods ghci_mode oldUI reachable_from threaded 
360      ((AcyclicSCC mod):mods)
361    = do (threaded1, maybe_linkable) 
362            <- upsweep_mod ghci_mode oldUI threaded mod 
363                           (reachable_from (name_of_summary mod)) 
364         case maybe_linkable of
365            Just linkable 
366               -> -- No errors; do the rest
367                  do (restOK, threaded2, modOKs, linkables) 
368                        <- upsweep_mods ghci_mode oldUI reachable_from 
369                                        threaded1 mods
370                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
371            Nothing -- we got a compilation error; give up now
372               -> return (False, threaded1, [], [])
373
374
375 -- Compile a single module.  Always produce a Linkable for it if 
376 -- successful.  If no compilation happened, return the old Linkable.
377 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
378 maybe_getFileLinkable mod_name obj_fn
379    = do obj_exist <- doesFileExist obj_fn
380         if not obj_exist 
381          then return Nothing 
382          else 
383          do let stub_fn = case splitFilename3 obj_fn of
384                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
385             stub_exist <- doesFileExist stub_fn
386             obj_time <- getModificationTime obj_fn
387             if stub_exist
388              then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
389              else return (Just (LM obj_time mod_name [DotO obj_fn]))
390
391
392 upsweep_mod :: GhciMode 
393             -> UnlinkedImage
394             -> CmThreaded
395             -> ModSummary
396             -> [ModuleName]
397             -> IO (CmThreaded, Maybe Linkable)
398
399 upsweep_mod ghci_mode oldUI threaded1 summary1 reachable_from_here
400    = do hPutStr stderr ("ghc: module " 
401                         ++ moduleNameUserString (name_of_summary summary1) ++ ": ")
402         let mod_name = name_of_summary summary1
403         let (CmThreaded pcs1 hst1 hit1) = threaded1
404         let old_iface = lookupUFM hit1 (name_of_summary summary1)
405
406         -- We *have* to compile it if we're in batch mode and we can't see
407         -- a previous linkable for it on disk.
408         compilation_mandatory 
409            <- if ghci_mode /= Batch then return False 
410               else case ml_obj_file (ms_location summary1) of
411                       Nothing     -> do --putStrLn "cmcm: object?!"
412                                         return True
413                       Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
414                                         b <- doesFileExist obj_fn
415                                         return (not b)
416
417         let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
418         maybe_oldDisk_linkable
419            <- case ml_obj_file (ms_location summary1) of
420                  Nothing -> return Nothing
421                  Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
422
423         -- The most recent of the old UI linkable or whatever we could
424         -- find on disk.  Is returned as the linkable if compile
425         -- doesn't think we need to recompile.        
426         let maybe_old_linkable
427                = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
428                     (Nothing, Nothing) -> Nothing
429                     (Nothing, Just di) -> Just di
430                     (Just ui, Nothing) -> Just ui
431                     (Just ui, Just di)
432                        | linkableTime ui >= linkableTime di -> Just ui
433                        | otherwise                          -> Just di
434
435         let compilation_mandatory
436                = case maybe_old_linkable of
437                     Nothing -> True
438                     Just li -> case ms_hs_date summary1 of
439                                   Nothing -> panic "compilation_mandatory:no src date"
440                                   Just src_date -> src_date >= linkableTime li
441             source_unchanged
442                = not compilation_mandatory
443
444             (hst1_strictDC, hit1_strictDC)
445                = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
446
447             old_linkable 
448                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
449
450         compresult <- compile ghci_mode summary1 source_unchanged
451                          old_iface hst1_strictDC hit1_strictDC pcs1
452
453         case compresult of
454
455            -- Compilation "succeeded", but didn't return a new
456            -- linkable, meaning that compilation wasn't needed, and the
457            -- new details were manufactured from the old iface.
458            CompOK pcs2 new_details new_iface Nothing
459               -> let hst2         = addToUFM hst1 mod_name new_details
460                      hit2         = addToUFM hit1 mod_name new_iface
461                      threaded2    = CmThreaded pcs2 hst2 hit2
462                  in  return (threaded2, Just old_linkable)
463
464            -- Compilation really did happen, and succeeded.  A new
465            -- details, iface and linkable are returned.
466            CompOK pcs2 new_details new_iface (Just new_linkable)
467               -> let hst2      = addToUFM hst1 mod_name new_details
468                      hit2      = addToUFM hit1 mod_name new_iface
469                      threaded2 = CmThreaded pcs2 hst2 hit2
470                  in  return (threaded2, Just new_linkable)
471
472            -- Compilation failed.  compile may still have updated
473            -- the PCS, tho.
474            CompErrs pcs2
475               -> let threaded2 = CmThreaded pcs2 hst1 hit1
476                  in  return (threaded2, Nothing)
477
478
479 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
480 removeFromTopLevelEnvs :: [ModuleName]
481                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
482                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
483 removeFromTopLevelEnvs zap_these (hst, hit, ui)
484    = (delListFromUFM hst zap_these,
485       delListFromUFM hit zap_these,
486       filterModuleLinkables (`notElem` zap_these) ui
487      )
488
489 retainInTopLevelEnvs :: [ModuleName]
490                         -> (HomeSymbolTable, HomeIfaceTable)
491                         -> (HomeSymbolTable, HomeIfaceTable)
492 retainInTopLevelEnvs keep_these (hst, hit)
493    = (retainInUFM hst keep_these,
494       retainInUFM hit keep_these
495      )
496      where
497         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
498         retainInUFM ufm keys_to_keep
499            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
500         maybeLookupUFM ufm u 
501            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
502
503 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
504 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
505 downwards_closure_of_module summaries root
506    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
507          toEdge summ
508              = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
509          res = simple_transitive_closure (map toEdge summaries) [root]             
510      in
511          --trace (showSDoc (text "DC of mod" <+> ppr root
512          --                 <+> text "=" <+> ppr res)) (
513          res
514          --)
515
516 -- Calculate transitive closures from a set of roots given an adjacency list
517 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
518 simple_transitive_closure graph set 
519    = let set2      = nub (concatMap dsts set ++ set)
520          dsts node = fromMaybe [] (lookup node graph)
521      in
522          if   length set == length set2
523          then set
524          else simple_transitive_closure graph set2
525
526
527 -- Calculate SCCs of the module graph, with or without taking into
528 -- account source imports.
529 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
530 topological_sort include_source_imports summaries
531    = let 
532          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
533          toEdge summ
534              = (summ, name_of_summary summ, 
535                       (if include_source_imports 
536                        then ms_srcimps summ else []) ++ ms_imps summ)
537         
538          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
539          mash_edge (summ, m, m_imports)
540             = case lookup m key_map of
541                  Nothing -> panic "reverse_topological_sort"
542                  Just mk -> (summ, mk, 
543                                 -- ignore imports not from the home package
544                                 catMaybes (map (flip lookup key_map) m_imports))
545
546          edges     = map toEdge summaries
547          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
548          scc_input = map mash_edge edges
549          sccs      = stronglyConnComp scc_input
550      in
551          sccs
552
553
554 -- Chase downwards from the specified root set, returning summaries
555 -- for all home modules encountered.  Only follow source-import
556 -- links.
557 downsweep :: [FilePath] -> IO [ModSummary]
558 downsweep rootNm
559    = do rootSummaries <- mapM getRootSummary rootNm
560         loop (filter (isHomeModule.ms_mod) rootSummaries)
561      where
562         getRootSummary :: FilePath -> IO ModSummary
563         getRootSummary file
564            | haskellish_file file
565            = do exists <- doesFileExist file
566                 if exists then summariseFile file else do
567                 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))      
568            | otherwise
569            = do exists <- doesFileExist hs_file
570                 if exists then summariseFile hs_file else do
571                 exists <- doesFileExist lhs_file
572                 if exists then summariseFile lhs_file else do
573                 getSummary (mkModuleName file)
574            where 
575                  hs_file = file ++ ".hs"
576                  lhs_file = file ++ ".lhs"
577
578         getSummary :: ModuleName -> IO ModSummary
579         getSummary nm
580            -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
581            = do found <- findModule nm
582                 case found of
583                    -- Be sure not to use the mod and location passed in to 
584                    -- summarise for any other purpose -- summarise may change
585                    -- the module names in them if name of module /= name of file,
586                    -- and put the changed versions in the returned summary.
587                    -- These will then conflict with the passed-in versions.
588                    Just (mod, location) -> summarise mod location
589                    Nothing -> throwDyn (OtherError 
590                                    ("can't find module `" 
591                                      ++ showSDoc (ppr nm) ++ "'"))
592                                  
593         -- loop invariant: homeSummaries doesn't contain package modules
594         loop :: [ModSummary] -> IO [ModSummary]
595         loop homeSummaries
596            = do let allImps :: [ModuleName]
597                     allImps = (nub . concatMap ms_imps) homeSummaries
598                 let allHome   -- all modules currently in homeSummaries
599                        = map (moduleName.ms_mod) homeSummaries
600                 let neededImps
601                        = filter (`notElem` allHome) allImps
602                 neededSummaries
603                        <- mapM getSummary neededImps
604                 let newHomeSummaries
605                        = filter (isHomeModule.ms_mod) neededSummaries
606                 if null newHomeSummaries
607                  then return homeSummaries
608                  else loop (newHomeSummaries ++ homeSummaries)
609
610
611 -----------------------------------------------------------------------------
612 -- Summarising modules
613
614 -- We have two types of summarisation:
615 --
616 --    * Summarise a file.  This is used for the root module passed to
617 --      cmLoadModule.  The file is read, and used to determine the root
618 --      module name.  The module name may differ from the filename.
619 --
620 --    * Summarise a module.  We are given a module name, and must provide
621 --      a summary.  The finder is used to locate the file in which the module
622 --      resides.
623
624 summariseFile :: FilePath -> IO ModSummary
625 summariseFile file
626    = do hspp_fn <- preprocess file
627         modsrc <- readFile hspp_fn
628
629         let (srcimps,imps,mod_name) = getImports modsrc
630             (path, basename, ext) = splitFilename3 file
631
632         Just (mod, location)
633            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
634            
635         maybe_src_timestamp
636            <- case ml_hs_file location of 
637                  Nothing     -> return Nothing
638                  Just src_fn -> maybe_getModificationTime src_fn
639
640         return (ModSummary mod
641                            location{ml_hspp_file=Just hspp_fn}
642                            srcimps imps
643                            maybe_src_timestamp)
644
645 -- Summarise a module, and pick up source and interface timestamps.
646 summarise :: Module -> ModuleLocation -> IO ModSummary
647 summarise mod location
648    | isHomeModule mod
649    = do let hs_fn = unJust "summarise" (ml_hs_file location)
650         hspp_fn <- preprocess hs_fn
651         modsrc <- readFile hspp_fn
652         let (srcimps,imps,mod_name) = getImports modsrc
653
654         maybe_src_timestamp
655            <- case ml_hs_file location of 
656                  Nothing     -> return Nothing
657                  Just src_fn -> maybe_getModificationTime src_fn
658
659         if mod_name == moduleName mod
660                 then return ()
661                 else throwDyn (OtherError 
662                         (showSDoc (text "file name does not match module name: "
663                            <+> ppr (moduleName mod) <+> text "vs" 
664                            <+> ppr mod_name)))
665
666         return (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
667                                srcimps imps
668                                maybe_src_timestamp)
669
670    | otherwise
671    = return (ModSummary mod location [] [] Nothing)
672
673 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
674 maybe_getModificationTime fn
675    = (do time <- getModificationTime fn
676          return (Just time)) 
677      `catch`
678      (\err -> return Nothing)
679 \end{code}