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