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