[project @ 2000-11-20 16:28:29 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                           isModuleInThisPackage, 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 (mkModuleInThisPackage 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         hPutStr stderr "cmLoadModule: downsweep begins\n"
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 let mod_name = name_of_summary summary1
391         let (CmThreaded pcs1 hst1 hit1) = threaded1
392         let old_iface = lookupUFM hit1 (name_of_summary summary1)
393
394         -- We *have* to compile it if we're in batch mode and we can't see
395         -- a previous linkable for it on disk.
396         compilation_mandatory 
397            <- if ghci_mode /= Batch then return False 
398               else case ml_obj_file (ms_location summary1) of
399                       Nothing     -> do --putStrLn "cmcm: object?!"
400                                         return True
401                       Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
402                                         b <- doesFileExist obj_fn
403                                         return (not b)
404
405         let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
406         maybe_oldDisk_linkable
407            <- case ml_obj_file (ms_location summary1) of
408                  Nothing -> return Nothing
409                  Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
410
411         -- The most recent of the old UI linkable or whatever we could
412         -- find on disk.  Is returned as the linkable if compile
413         -- doesn't think we need to recompile.        
414         let maybe_old_linkable
415                = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
416                     (Nothing, Nothing) -> Nothing
417                     (Nothing, Just di) -> Just di
418                     (Just ui, Nothing) -> Just ui
419                     (Just ui, Just di)
420                        | linkableTime ui >= linkableTime di -> Just ui
421                        | otherwise                          -> Just di
422
423         let compilation_mandatory
424                = case maybe_old_linkable of
425                     Nothing -> True
426                     Just li -> case ms_hs_date summary1 of
427                                   Nothing -> panic "compilation_mandatory:no src date"
428                                   Just src_date -> src_date >= linkableTime li
429             source_unchanged
430                = not compilation_mandatory
431
432             (hst1_strictDC, hit1_strictDC)
433                = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
434
435             old_linkable 
436                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
437
438         compresult <- compile ghci_mode summary1 source_unchanged
439                          old_iface hst1_strictDC hit1_strictDC pcs1
440
441         case compresult of
442
443            -- Compilation "succeeded", but didn't return a new iface or
444            -- linkable, meaning that compilation wasn't needed, and the
445            -- new details were manufactured from the old iface.
446            CompOK details Nothing pcs2
447               -> let hst2         = addToUFM hst1 mod_name details
448                      hit2         = hit1
449                      threaded2    = CmThreaded pcs2 hst2 hit2
450                  in  return (threaded2, Just old_linkable)
451
452            -- Compilation really did happen, and succeeded.  A new
453            -- details, iface and linkable are returned.
454            CompOK details (Just (new_iface, new_linkable)) pcs2
455               -> let hst2      = addToUFM hst1 mod_name details
456                      hit2      = addToUFM hit1 mod_name new_iface
457                      threaded2 = CmThreaded pcs2 hst2 hit2
458                  in  return (threaded2, Just new_linkable)
459
460            -- Compilation failed.  compile may still have updated
461            -- the PCS, tho.
462            CompErrs pcs2
463               -> let threaded2 = CmThreaded pcs2 hst1 hit1
464                  in  return (threaded2, Nothing)
465
466
467 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
468 removeFromTopLevelEnvs :: [ModuleName]
469                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
470                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
471 removeFromTopLevelEnvs zap_these (hst, hit, ui)
472    = (delListFromUFM hst zap_these,
473       delListFromUFM hit zap_these,
474       filterModuleLinkables (`notElem` zap_these) ui
475      )
476
477 retainInTopLevelEnvs :: [ModuleName]
478                         -> (HomeSymbolTable, HomeIfaceTable)
479                         -> (HomeSymbolTable, HomeIfaceTable)
480 retainInTopLevelEnvs keep_these (hst, hit)
481    = (retainInUFM hst keep_these,
482       retainInUFM hit keep_these
483      )
484      where
485         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
486         retainInUFM ufm keys_to_keep
487            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
488         maybeLookupUFM ufm u 
489            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
490
491 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
492 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
493 downwards_closure_of_module summaries root
494    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
495          toEdge summ
496              = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
497          res = simple_transitive_closure (map toEdge summaries) [root]             
498      in
499          trace (showSDoc (text "DC of mod" <+> ppr root
500                           <+> text "=" <+> ppr res)) (
501          res
502          )
503
504 -- Calculate transitive closures from a set of roots given an adjacency list
505 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
506 simple_transitive_closure graph set 
507    = let set2      = nub (concatMap dsts set ++ set)
508          dsts node = fromMaybe [] (lookup node graph)
509      in
510          if   length set == length set2
511          then set
512          else simple_transitive_closure graph set2
513
514
515 -- Calculate SCCs of the module graph, with or without taking into
516 -- account source imports.
517 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
518 topological_sort include_source_imports summaries
519    = let 
520          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
521          toEdge summ
522              = (summ, name_of_summary summ, 
523                       (if include_source_imports 
524                        then ms_srcimps summ else []) ++ ms_imps summ)
525         
526          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
527          mash_edge (summ, m, m_imports)
528             = case lookup m key_map of
529                  Nothing -> panic "reverse_topological_sort"
530                  Just mk -> (summ, mk, 
531                                 -- ignore imports not from the home package
532                                 catMaybes (map (flip lookup key_map) m_imports))
533
534          edges     = map toEdge summaries
535          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
536          scc_input = map mash_edge edges
537          sccs      = stronglyConnComp scc_input
538      in
539          sccs
540
541
542 -- Chase downwards from the specified root set, returning summaries
543 -- for all home modules encountered.  Only follow source-import
544 -- links.
545 downsweep :: [FilePath] -> IO [ModSummary]
546 downsweep rootNm
547    = do rootSummaries <- mapM getRootSummary rootNm
548         loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
549      where
550         getRootSummary :: FilePath -> IO ModSummary
551         getRootSummary file
552            | haskellish_file file
553            = do exists <- doesFileExist file
554                 if exists then summariseFile file
555                           else getSummary (mkModuleName file)
556                 -- ToDo: should check import paths
557            | otherwise
558            = getSummary (mkModuleName file)
559
560         getSummary :: ModuleName -> IO ModSummary
561         getSummary nm
562            | trace ("getSummary: "++ showSDoc (ppr nm)) True
563            = do found <- findModule nm
564                 case found of
565                    -- Be sure not to use the mod and location passed in to 
566                    -- summarise for any other purpose -- summarise may change
567                    -- the module names in them if name of module /= name of file,
568                    -- and put the changed versions in the returned summary.
569                    -- These will then conflict with the passed-in versions.
570                    Just (mod, location) -> summarise mod location
571                    Nothing -> throwDyn (OtherError 
572                                    ("no signs of life for module `" 
573                                      ++ showSDoc (ppr nm) ++ "'"))
574                                  
575         -- loop invariant: homeSummaries doesn't contain package modules
576         loop :: [ModSummary] -> IO [ModSummary]
577         loop homeSummaries
578            = do let allImps :: [ModuleName]
579                     allImps = (nub . concatMap ms_imps) homeSummaries
580                 let allHome   -- all modules currently in homeSummaries
581                        = map (moduleName.ms_mod) homeSummaries
582                 let neededImps
583                        = filter (`notElem` allHome) allImps
584                 neededSummaries
585                        <- mapM getSummary neededImps
586                 let newHomeSummaries
587                        = filter (isModuleInThisPackage.ms_mod) neededSummaries
588                 if null newHomeSummaries
589                  then return homeSummaries
590                  else loop (newHomeSummaries ++ homeSummaries)
591
592
593 -----------------------------------------------------------------------------
594 -- Summarising modules
595
596 -- We have two types of summarisation:
597 --
598 --    * Summarise a file.  This is used for the root module passed to
599 --      cmLoadModule.  The file is read, and used to determine the root
600 --      module name.  The module name may differ from the filename.
601 --
602 --    * Summarise a module.  We are given a module name, and must provide
603 --      a summary.  The finder is used to locate the file in which the module
604 --      resides.
605
606 summariseFile :: FilePath -> IO ModSummary
607 summariseFile file
608    = do hspp_fn <- preprocess file
609         modsrc <- readFile hspp_fn
610
611         let (srcimps,imps,mod_name) = getImports modsrc
612             (path, basename, ext) = splitFilename3 file
613
614         Just (mod, location)
615            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
616            
617         maybe_src_timestamp
618            <- case ml_hs_file location of 
619                  Nothing     -> return Nothing
620                  Just src_fn -> maybe_getModificationTime src_fn
621
622         return (ModSummary mod
623                            location{ml_hspp_file=Just hspp_fn}
624                            srcimps imps
625                            maybe_src_timestamp)
626
627 -- Summarise a module, and pick up source and interface timestamps.
628 summarise :: Module -> ModuleLocation -> IO ModSummary
629 summarise mod location
630    | isModuleInThisPackage mod
631    = do let hs_fn = unJust "summarise" (ml_hs_file location)
632         hspp_fn <- preprocess hs_fn
633         modsrc <- readFile hspp_fn
634         let (srcimps,imps,mod_name) = getImports modsrc
635
636         maybe_src_timestamp
637            <- case ml_hs_file location of 
638                  Nothing     -> return Nothing
639                  Just src_fn -> maybe_getModificationTime src_fn
640
641         if mod_name == moduleName mod
642                 then return ()
643                 else throwDyn (OtherError 
644                         (showSDoc (text "file name does not match module name: "
645                            <+> ppr (moduleName mod) <+> text "vs" 
646                            <+> ppr mod_name)))
647
648         return (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
649                                srcimps imps
650                                maybe_src_timestamp)
651
652    | otherwise
653    = return (ModSummary mod location [] [] Nothing)
654
655 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
656 maybe_getModificationTime fn
657    = (do time <- getModificationTime fn
658          return (Just time)) 
659      `catch`
660      (\err -> return Nothing)
661 \end{code}