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