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