[project @ 2000-11-20 14:48:52 by simonpj]
[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           ( findModule, emptyHomeDirCache )
33 import UniqFM           ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
34                           UniqFM, listToUFM )
35 import Unique           ( Uniquable )
36 import Digraph          ( SCC(..), stronglyConnComp )
37 import DriverUtil       ( BarfKind(..), splitFilename3 )
38 import Util
39 import Outputable
40 import Panic            ( panic )
41
42 #ifdef GHCI
43 import CmdLineOpts      ( DynFlags )
44 import Interpreter      ( HValue )
45 import HscMain          ( hscExpr )
46 import RdrName
47 import PrelGHC          ( unsafeCoerce# )
48 #endif
49
50 -- lang
51 import Exception        ( throwDyn )
52
53 -- std
54 import Time             ( ClockTime )
55 import Directory        ( getModificationTime, doesFileExist )
56 import IO
57 import List             ( nub )
58 import Maybe            ( catMaybes, fromMaybe, isJust )
59 \end{code}
60
61
62 \begin{code}
63 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
64 cmInit raw_package_info gmode
65    = emptyCmState raw_package_info gmode
66
67 #ifdef GHCI
68 cmGetExpr :: CmState
69           -> DynFlags
70           -> ModuleName
71           -> String
72           -> IO (CmState, Maybe HValue)
73 cmGetExpr cmstate dflags modname expr
74    = do (new_pcs, maybe_unlinked_iexpr) <- 
75            hscExpr dflags hst hit pcs (mkModuleInThisPackage modname) expr
76         case maybe_unlinked_iexpr of
77            Nothing     -> return (cmstate{ pcs=new_pcs }, Nothing)
78            Just uiexpr -> do
79                 hValue <- linkExpr pls uiexpr
80                 return (cmstate{ pcs=new_pcs }, Just hValue)
81
82    -- ToDo: check that the module we passed in is sane/exists?
83    where
84        CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
85        PersistentCMState{ hst=hst, hit=hit } = pcms
86
87 -- The HValue should represent a value of type IO () (Perhaps IO a?)
88 cmRunExpr :: HValue -> IO ()
89 cmRunExpr hval
90    = do unsafeCoerce# hval :: IO ()
91         -- putStrLn "done."
92 #endif
93
94 -- Persistent state just for CM, excluding link & compile subsystems
95 data PersistentCMState
96    = PersistentCMState {
97         hst   :: HomeSymbolTable,    -- home symbol table
98         hit   :: HomeIfaceTable,     -- home interface table
99         ui    :: UnlinkedImage,      -- the unlinked images
100         mg    :: ModuleGraph,        -- the module graph
101         pci   :: PackageConfigInfo,  -- NEVER CHANGES
102         gmode :: GhciMode            -- NEVER CHANGES
103      }
104
105 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
106 emptyPCMS pci gmode
107   = PersistentCMState { hst = emptyHST, hit = emptyHIT,
108                         ui  = emptyUI,  mg  = emptyMG, 
109                         pci = pci, gmode = gmode }
110
111 emptyHIT :: HomeIfaceTable
112 emptyHIT = emptyUFM
113 emptyHST :: HomeSymbolTable
114 emptyHST = emptyUFM
115
116
117
118 -- Persistent state for the entire system
119 data CmState
120    = CmState {
121         pcms   :: PersistentCMState,       -- CM's persistent state
122         pcs    :: PersistentCompilerState, -- compile's persistent state
123         pls    :: PersistentLinkerState    -- link's persistent state
124      }
125
126 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
127 emptyCmState pci gmode
128     = do let pcms = emptyPCMS pci gmode
129          pcs     <- initPersistentCompilerState
130          pls     <- emptyPLS
131          return (CmState { pcms   = pcms,
132                            pcs    = pcs,
133                            pls    = pls })
134
135 -- CM internal types
136 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
137 emptyUI :: UnlinkedImage
138 emptyUI = []
139
140 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
141 emptyMG :: ModuleGraph
142 emptyMG = []
143
144 \end{code}
145
146 The real business of the compilation manager: given a system state and
147 a module name, try and bring the module up to date, probably changing
148 the system state at the same time.
149
150 \begin{code}
151 cmLoadModule :: CmState 
152              -> ModuleName
153              -> IO (CmState, Maybe ModuleName)
154
155 cmLoadModule cmstate1 rootname
156    = do -- version 1's are the original, before downsweep
157         let pcms1     = pcms   cmstate1
158         let pls1      = pls    cmstate1
159         let pcs1      = pcs    cmstate1
160         let mg1       = mg     pcms1
161         let hst1      = hst    pcms1
162         let hit1      = hit    pcms1
163         let ui1       = ui     pcms1
164    
165         let pcii      = pci   pcms1 -- this never changes
166         let ghci_mode = gmode pcms1 -- ToDo: fix!
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 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 (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
260                            mods_to_keep_names
261
262               linkresult <- link ghci_mode False linkables_to_link pls1
263               case linkresult of
264                  LinkErrs _ _
265                     -> panic "cmLoadModule: link failed (2)"
266                  LinkOK pls4
267                     -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4, 
268                                                           ui=ui4, mg=mods_to_keep,
269                                                           pci=pcii, gmode=ghci_mode }
270                           let cmstate4 
271                                  = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
272                           return (cmstate4, 
273                                   -- choose rather arbitrarily who to return
274                                   if null mods_to_keep then Nothing 
275                                      else Just (last 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         let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
395         maybe_oldDisk_linkable
396            <- case ml_obj_file (ms_location summary1) of
397                  Nothing -> return Nothing
398                  Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
399
400         -- The most recent of the old UI linkable or whatever we could
401         -- find on disk.  Is returned as the linkable if compile
402         -- doesn't think we need to recompile.        
403         let maybe_old_linkable
404                = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
405                     (Nothing, Nothing) -> Nothing
406                     (Nothing, Just di) -> Just di
407                     (Just ui, Nothing) -> Just ui
408                     (Just ui, Just di)
409                        | linkableTime ui >= linkableTime di -> Just ui
410                        | otherwise                          -> Just di
411
412         let compilation_mandatory
413                = case maybe_old_linkable of
414                     Nothing -> True
415                     Just li -> case ms_hs_date summary1 of
416                                   Nothing -> panic "compilation_mandatory:no src date"
417                                   Just src_date -> src_date >= linkableTime li
418             source_unchanged
419                = not compilation_mandatory
420
421             (hst1_strictDC, hit1_strictDC)
422                = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
423
424             old_linkable 
425                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
426
427         compresult <- compile ghci_mode summary1 source_unchanged
428                          old_iface hst1_strictDC hit1_strictDC pcs1
429
430         case compresult of
431
432            -- Compilation "succeeded", but didn't return a new iface or
433            -- linkable, meaning that compilation wasn't needed, and the
434            -- new details were manufactured from the old iface.
435            CompOK details Nothing pcs2
436               -> let hst2         = addToUFM hst1 mod_name details
437                      hit2         = hit1
438                      threaded2    = CmThreaded pcs2 hst2 hit2
439                  in  return (threaded2, Just old_linkable)
440
441            -- Compilation really did happen, and succeeded.  A new
442            -- details, iface and linkable are returned.
443            CompOK details (Just (new_iface, new_linkable)) pcs2
444               -> let hst2      = addToUFM hst1 mod_name details
445                      hit2      = addToUFM hit1 mod_name new_iface
446                      threaded2 = CmThreaded pcs2 hst2 hit2
447                  in  return (threaded2, Just new_linkable)
448
449            -- Compilation failed.  compile may still have updated
450            -- the PCS, tho.
451            CompErrs pcs2
452               -> let threaded2 = CmThreaded pcs2 hst1 hit1
453                  in  return (threaded2, Nothing)
454
455
456 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
457 removeFromTopLevelEnvs :: [ModuleName]
458                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
459                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
460 removeFromTopLevelEnvs zap_these (hst, hit, ui)
461    = (delListFromUFM hst zap_these,
462       delListFromUFM hit zap_these,
463       filterModuleLinkables (`notElem` zap_these) ui
464      )
465
466 retainInTopLevelEnvs :: [ModuleName]
467                         -> (HomeSymbolTable, HomeIfaceTable)
468                         -> (HomeSymbolTable, HomeIfaceTable)
469 retainInTopLevelEnvs keep_these (hst, hit)
470    = (retainInUFM hst keep_these,
471       retainInUFM hit keep_these
472      )
473      where
474         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
475         retainInUFM ufm keys_to_keep
476            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
477         maybeLookupUFM ufm u 
478            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
479
480 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
481 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
482 downwards_closure_of_module summaries root
483    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
484          toEdge summ
485              = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
486          res = simple_transitive_closure (map toEdge summaries) [root]             
487      in
488          trace (showSDoc (text "DC of mod" <+> ppr root
489                           <+> text "=" <+> ppr res)) (
490          res
491          )
492
493 -- Calculate transitive closures from a set of roots given an adjacency list
494 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
495 simple_transitive_closure graph set 
496    = let set2      = nub (concatMap dsts set ++ set)
497          dsts node = fromMaybe [] (lookup node graph)
498      in
499          if   length set == length set2
500          then set
501          else simple_transitive_closure graph set2
502
503
504 -- Calculate SCCs of the module graph, with or without taking into
505 -- account source imports.
506 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
507 topological_sort include_source_imports summaries
508    = let 
509          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
510          toEdge summ
511              = (summ, name_of_summary summ, 
512                       (if include_source_imports 
513                        then ms_srcimps summ else []) ++ ms_imps summ)
514         
515          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
516          mash_edge (summ, m, m_imports)
517             = case lookup m key_map of
518                  Nothing -> panic "reverse_topological_sort"
519                  Just mk -> (summ, mk, 
520                                 -- ignore imports not from the home package
521                                 catMaybes (map (flip lookup key_map) m_imports))
522
523          edges     = map toEdge summaries
524          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
525          scc_input = map mash_edge edges
526          sccs      = stronglyConnComp scc_input
527      in
528          sccs
529
530
531 -- Chase downwards from the specified root set, returning summaries
532 -- for all home modules encountered.  Only follow source-import
533 -- links.
534 downsweep :: [ModuleName] -> IO [ModSummary]
535 downsweep rootNm
536    = do rootSummaries <- mapM getSummary rootNm
537         loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
538      where
539         getSummary :: ModuleName -> IO ModSummary
540         getSummary nm
541            | trace ("getSummary: "++ showSDoc (ppr nm)) True
542            = do found <- findModule nm
543                 case found of
544                    -- Be sure not to use the mod and location passed in to 
545                    -- summarise for any other purpose -- summarise may change
546                    -- the module names in them if name of module /= name of file,
547                    -- and put the changed versions in the returned summary.
548                    -- These will then conflict with the passed-in versions.
549                    Just (mod, location) -> summarise mod location
550                    Nothing -> throwDyn (OtherError 
551                                    ("no signs of life for module `" 
552                                      ++ showSDoc (ppr nm) ++ "'"))
553                                  
554         -- loop invariant: homeSummaries doesn't contain package modules
555         loop :: [ModSummary] -> IO [ModSummary]
556         loop homeSummaries
557            = do let allImps :: [ModuleName]
558                     allImps = (nub . concatMap ms_imps) homeSummaries
559                 let allHome   -- all modules currently in homeSummaries
560                        = map (moduleName.ms_mod) homeSummaries
561                 let neededImps
562                        = filter (`notElem` allHome) allImps
563                 neededSummaries
564                        <- mapM getSummary neededImps
565                 let newHomeSummaries
566                        = filter (isModuleInThisPackage.ms_mod) neededSummaries
567                 if null newHomeSummaries
568                  then return homeSummaries
569                  else loop (newHomeSummaries ++ homeSummaries)
570
571
572 -- Summarise a module, and pick up source and interface timestamps.
573 summarise :: Module -> ModuleLocation -> IO ModSummary
574 summarise mod location
575    | isModuleInThisPackage mod
576    = do let hs_fn = unJust "summarise" (ml_hs_file location)
577         hspp_fn <- preprocess hs_fn
578         modsrc <- readFile hspp_fn
579         let (srcimps,imps,mod_name) = getImports modsrc
580
581         maybe_src_timestamp
582            <- case ml_hs_file location of 
583                  Nothing     -> return Nothing
584                  Just src_fn -> maybe_getModificationTime src_fn
585
586         -- If the module name is Main, allow it to be in a file
587         -- different from Main.hs, and mash the mod and loc 
588         -- to match.  Otherwise just moan.
589         (mashed_mod, mashed_loc)
590            <- case () of
591               () |  mod_name == moduleName mod
592                  -> return (mod, location)
593                  |  mod_name /= moduleName mod && mod_name == mkModuleName "Main"
594                  -> return (mash mod location "Main")
595                  |  otherwise
596                  -> do hPutStrLn stderr (showSDoc (
597                           text "ghc: warning: file name - module name mismatch:" <+> 
598                           ppr (moduleName mod) <+> text "vs" <+> ppr mod_name))
599                        return (mash mod location (moduleNameUserString (moduleName mod)))
600                where
601                  mash old_mod old_loc new_nm
602                     = (mkHomeModule (mkModuleName new_nm), 
603                        old_loc{ml_hi_file = maybe_swizzle_basename new_nm 
604                                                 (ml_hi_file old_loc)})
605
606                  maybe_swizzle_basename new Nothing = Nothing
607                  maybe_swizzle_basename new (Just old) 
608                     = case splitFilename3 old of 
609                          (dir, name, ext) -> Just (dir ++ new ++ ext)
610
611         return (ModSummary mashed_mod 
612                            mashed_loc{ml_hspp_file=Just hspp_fn} 
613                            srcimps imps
614                            maybe_src_timestamp)
615
616    | otherwise
617    = return (ModSummary mod location [] [] Nothing)
618
619    where
620       maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
621       maybe_getModificationTime fn
622          = (do time <- getModificationTime fn
623                return (Just time)) 
624            `catch`
625            (\err -> return Nothing)
626 \end{code}