eb19468ffea2dc9bf3a40a9c0ec0035b5f71c973
[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         -- During upsweep, look at new summaries to see if source has
162         -- changed.  Here's a function to pass down; it takes a new
163         -- summary.
164         let source_changed :: ModSummary -> Bool
165             source_changed = summary_indicates_source_changed mg1
166
167         -- Do the downsweep to reestablish the module graph
168         -- then generate version 2's by removing from HIT,HST,UI any
169         -- modules in the old MG which are not in the new one.
170
171         -- Throw away the old home dir cache
172         emptyHomeDirCache
173
174         hPutStr stderr "cmLoadModule: downsweep begins\n"
175         mg2unsorted <- downsweep [rootname]
176
177         let modnames1   = map name_of_summary mg1
178         let modnames2   = map name_of_summary mg2unsorted
179         let mods_to_zap = filter (`notElem` modnames2) modnames1
180
181         let (hst2, hit2, ui2)
182                = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
183         -- should be cycle free; ignores 'import source's
184         let mg2 = topological_sort False mg2unsorted
185         -- ... whereas this takes them into account.  Used for
186         -- backing out partially complete cycles following a failed
187         -- upsweep, and for removing from hst/hit all the modules
188         -- not in strict downwards closure, during calls to compile.
189         let mg2_with_srcimps = topological_sort True mg2unsorted
190       
191         let reachable_from :: ModuleName -> [ModuleName]
192             reachable_from = downwards_closure_of_module mg2unsorted
193
194         hPutStrLn stderr "after tsort:\n"
195         hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
196
197         -- Because we don't take into account source imports when doing
198         -- the topological sort, there shouldn't be any cycles in mg2.
199         -- If there is, we complain and give up -- the user needs to
200         -- break the cycle using a boot file.
201
202         -- Now do the upsweep, calling compile for each module in
203         -- turn.  Final result is version 3 of everything.
204
205         let threaded2 = CmThreaded pcs1 hst2 hit2
206
207         (upsweep_complete_success, threaded3, modsDone, newLis)
208            <- upsweep_mods ghci_mode ui2 reachable_from source_changed threaded2 mg2
209
210         let ui3 = add_to_ui ui2 newLis
211         let (CmThreaded pcs3 hst3 hit3) = threaded3
212
213         -- At this point, modsDone and newLis should have the same
214         -- length, so there is one new (or old) linkable for each 
215         -- mod which was processed (passed to compile).
216
217         -- Try and do linking in some form, depending on whether the
218         -- upsweep was completely or only partially successful.
219
220         if upsweep_complete_success
221
222          then 
223            -- Easy; just relink it all.
224            do hPutStrLn stderr "UPSWEEP COMPLETELY SUCCESSFUL"
225               linkresult 
226                  <- link ghci_mode (any exports_main (moduleEnvElts hst3)) 
227                          newLis pls1
228               case linkresult of
229                  LinkErrs _ _
230                     -> panic "cmLoadModule: link failed (1)"
231                  LinkOK pls3 
232                     -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3, 
233                                                           ui=ui3, mg=modsDone, 
234                                                           pci=pcii, gmode=ghci_mode }
235                           let cmstate3 
236                                  = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
237                           return (cmstate3, Just rootname)
238
239          else 
240            -- Tricky.  We need to back out the effects of compiling any
241            -- half-done cycles, both so as to clean up the top level envs
242            -- and to avoid telling the interactive linker to link them.
243            do hPutStrLn stderr "UPSWEEP PARTIALLY SUCCESSFUL"
244
245               let modsDone_names
246                      = map name_of_summary modsDone
247               let mods_to_zap_names 
248                      = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
249               let (hst4, hit4, ui4) 
250                      = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
251               let mods_to_keep
252                      = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
253               let mods_to_keep_names 
254                      = map name_of_summary mods_to_keep
255               -- we could get the relevant linkables by filtering newLis, but
256               -- it seems easier to drag them out of the updated, cleaned-up UI
257               let linkables_to_link 
258                      = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
259                            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    = panic "SISC"
284 #if 0
285    = case [old | old <- old_summaries, 
286                  name_of_summary old == name_of_summary new_summary] of
287
288         (_:_:_) -> panic "summary_indicates_newer_source"
289                    
290         []      -> -- can't find a corresponding old summary, so
291                    -- compare source and iface dates in the new summary.
292                    trace (showSDoc (text "SISC: no old summary, new =" 
293                                     <+> pprSummaryTimes new_summary)) (
294                    case (ms_hs_date new_summary, ms_hi_date new_summary) of
295                       (Just hs_t, Just hi_t) -> hs_t > hi_t
296                       other                  -> True
297                    )
298
299         [old]   -> -- found old summary; compare source timestamps
300                    trace (showSDoc (text "SISC: old =" 
301                                     <+> pprSummaryTimes old
302                                     <+> pprSummaryTimes new_summary)) (
303                    case (ms_hs_date old, ms_hs_date new_summary) of
304                       (Just old_t, Just new_t) -> new_t > old_t
305                       other                    -> True
306                    )
307 #endif
308
309
310 -- Return (names of) all those in modsDone who are part of a cycle
311 -- as defined by theGraph.
312 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
313 findPartiallyCompletedCycles modsDone theGraph
314    = chew theGraph
315      where
316         chew [] = []
317         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
318         chew ((CyclicSCC vs):rest)
319            = let names_in_this_cycle = nub (map name_of_summary vs)
320                  mods_in_this_cycle  
321                     = nub ([done | done <- modsDone, 
322                                    done `elem` names_in_this_cycle])
323                  chewed_rest = chew rest
324              in 
325              if   not (null mods_in_this_cycle) 
326                   && length mods_in_this_cycle < length names_in_this_cycle
327              then mods_in_this_cycle ++ chewed_rest
328              else chewed_rest
329
330
331 -- Does this ModDetails export Main.main?
332 exports_main :: ModDetails -> Bool
333 exports_main md
334    = isJust (lookupNameEnv (md_types md) mainName)
335
336
337 -- Add the given (LM-form) Linkables to the UI, overwriting previous
338 -- versions if they exist.
339 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
340 add_to_ui ui lis
341    = foldr add1 ui lis
342      where
343         add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
344         add1 li ui
345            = li : filter (\li2 -> not (for_same_module li li2)) ui
346
347         for_same_module :: Linkable -> Linkable -> Bool
348         for_same_module li1 li2 
349            = not (is_package_linkable li1)
350              && not (is_package_linkable li2)
351              && modname_of_linkable li1 == modname_of_linkable li2
352                                   
353
354 data CmThreaded  -- stuff threaded through individual module compilations
355    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
356
357
358 -- Compile multiple modules, stopping as soon as an error appears.
359 -- There better had not be any cyclic groups here -- we check for them.
360 upsweep_mods :: GhciMode
361              -> UnlinkedImage         -- old linkables
362              -> (ModuleName -> [ModuleName])  -- to construct downward closures
363              -> (ModSummary -> Bool)  -- has source changed?
364              -> CmThreaded            -- PCS & HST & HIT
365              -> [SCC ModSummary]      -- mods to do (the worklist)
366                                       -- ...... RETURNING ......
367              -> IO (Bool{-complete success?-},
368                     CmThreaded,
369                     [ModSummary],     -- mods which succeeded
370                     [Linkable])       -- new linkables
371
372 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded 
373      []
374    = return (True, threaded, [], [])
375
376 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded 
377      ((CyclicSCC ms):_)
378    = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
379                           unwords (map (moduleNameUserString.name_of_summary) ms))
380         return (False, threaded, [], [])
381
382 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded 
383      ((AcyclicSCC mod):mods)
384    = do (threaded1, maybe_linkable) 
385            <- upsweep_mod ghci_mode oldUI threaded mod 
386                           (reachable_from (name_of_summary mod)) 
387                           (source_changed mod)
388         case maybe_linkable of
389            Just linkable 
390               -> -- No errors; do the rest
391                  do (restOK, threaded2, modOKs, linkables) 
392                        <- upsweep_mods ghci_mode oldUI reachable_from 
393                                        source_changed threaded1 mods
394                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
395            Nothing -- we got a compilation error; give up now
396               -> return (False, threaded1, [], [])
397
398
399 -- Compile a single module.  Always produce a Linkable for it if 
400 -- successful.  If no compilation happened, return the old Linkable.
401 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
402 maybe_getFileLinkable mod_name obj_fn
403    = do obj_exist <- doesFileExist obj_fn
404         if not obj_exist 
405          then return Nothing 
406          else 
407          do let stub_fn = case splitFilename3 obj_fn of
408                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
409             stub_exist <- doesFileExist stub_fn
410             obj_time <- getModificationTime obj_fn
411             if stub_exist
412              then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
413              else return (Just (LM obj_time mod_name [DotO obj_fn]))
414
415
416 upsweep_mod :: GhciMode 
417             -> UnlinkedImage
418             -> CmThreaded
419             -> ModSummary
420             -> [ModuleName]
421             -> Bool
422             -> IO (CmThreaded, Maybe Linkable)
423
424 upsweep_mod ghci_mode oldUI threaded1 summary1 
425             reachable_from_here source_might_have_changed
426    = do let mod_name = name_of_summary summary1
427         let (CmThreaded pcs1 hst1 hit1) = threaded1
428         let old_iface = lookupUFM hit1 (name_of_summary summary1)
429
430         let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
431         maybe_oldDisk_linkable
432            <- case ml_obj_file (ms_location summary1) of
433                  Nothing -> return Nothing
434                  Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
435
436         -- The most recent of the old UI linkable or whatever we could
437         -- find on disk.  Is returned as the linkable if compile
438         -- doesn't think we need to recompile.        
439         let maybe_old_linkable
440                = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
441                     (Nothing, Nothing) -> Nothing
442                     (Nothing, Just di) -> Just di
443                     (Just ui, Nothing) -> Just ui
444                     (Just ui, Just di)
445                        | linkableTime ui >= linkableTime di -> Just ui
446                        | otherwise                          -> Just di
447
448         let compilation_mandatory
449                = case maybe_old_linkable of
450                     Nothing -> True
451                     Just li -> case ms_hs_date summary1 of
452                                   Nothing -> panic "compilation_mandatory:no src date"
453                                   Just src_date -> src_date >= linkableTime li
454             source_unchanged
455                = not compilation_mandatory
456
457             (hst1_strictDC, hit1_strictDC)
458                = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
459
460             old_linkable 
461                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
462
463         compresult <- compile ghci_mode summary1 source_unchanged
464                          old_iface hst1_strictDC hit1_strictDC pcs1
465
466         case compresult of
467
468            -- Compilation "succeeded", but didn't return a new iface or
469            -- linkable, meaning that compilation wasn't needed, and the
470            -- new details were manufactured from the old iface.
471            CompOK details Nothing pcs2
472               -> let hst2         = addToUFM hst1 mod_name details
473                      hit2         = hit1
474                      threaded2    = CmThreaded pcs2 hst2 hit2
475                  in  return (threaded2, Just old_linkable)
476
477            -- Compilation really did happen, and succeeded.  A new
478            -- details, iface and linkable are returned.
479            CompOK details (Just (new_iface, new_linkable)) pcs2
480               -> let hst2      = addToUFM hst1 mod_name details
481                      hit2      = addToUFM hit1 mod_name new_iface
482                      threaded2 = CmThreaded pcs2 hst2 hit2
483                  in  return (threaded2, Just new_linkable)
484
485            -- Compilation failed.  compile may still have updated
486            -- the PCS, tho.
487            CompErrs pcs2
488               -> let threaded2 = CmThreaded pcs2 hst1 hit1
489                  in  return (threaded2, Nothing)
490
491
492 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
493 removeFromTopLevelEnvs :: [ModuleName]
494                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
495                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
496 removeFromTopLevelEnvs zap_these (hst, hit, ui)
497    = (delListFromUFM hst zap_these,
498       delListFromUFM hit zap_these,
499       filterModuleLinkables (`notElem` zap_these) ui
500      )
501
502 retainInTopLevelEnvs :: [ModuleName]
503                         -> (HomeSymbolTable, HomeIfaceTable)
504                         -> (HomeSymbolTable, HomeIfaceTable)
505 retainInTopLevelEnvs keep_these (hst, hit)
506    = (retainInUFM hst keep_these,
507       retainInUFM hit keep_these
508      )
509      where
510         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
511         retainInUFM ufm keys_to_keep
512            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
513         maybeLookupUFM ufm u 
514            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
515
516 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
517 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
518 downwards_closure_of_module summaries root
519    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
520          toEdge summ
521              = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
522          res = simple_transitive_closure (map toEdge summaries) [root]             
523      in
524          trace (showSDoc (text "DC of mod" <+> ppr root
525                           <+> text "=" <+> ppr res)) (
526          res
527          )
528
529 -- Calculate transitive closures from a set of roots given an adjacency list
530 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
531 simple_transitive_closure graph set 
532    = let set2      = nub (concatMap dsts set ++ set)
533          dsts node = fromMaybe [] (lookup node graph)
534      in
535          if   length set == length set2
536          then set
537          else simple_transitive_closure graph set2
538
539
540 -- Calculate SCCs of the module graph, with or without taking into
541 -- account source imports.
542 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
543 topological_sort include_source_imports summaries
544    = let 
545          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
546          toEdge summ
547              = (summ, name_of_summary summ, 
548                       (if include_source_imports 
549                        then ms_srcimps summ else []) ++ ms_imps summ)
550         
551          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
552          mash_edge (summ, m, m_imports)
553             = case lookup m key_map of
554                  Nothing -> panic "reverse_topological_sort"
555                  Just mk -> (summ, mk, 
556                                 -- ignore imports not from the home package
557                                 catMaybes (map (flip lookup key_map) m_imports))
558
559          edges     = map toEdge summaries
560          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
561          scc_input = map mash_edge edges
562          sccs      = stronglyConnComp scc_input
563      in
564          sccs
565
566
567 -- Chase downwards from the specified root set, returning summaries
568 -- for all home modules encountered.  Only follow source-import
569 -- links.
570 downsweep :: [ModuleName] -> IO [ModSummary]
571 downsweep rootNm
572    = do rootSummaries <- mapM getSummary rootNm
573         loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
574      where
575         getSummary :: ModuleName -> IO ModSummary
576         getSummary nm
577            | trace ("getSummary: "++ showSDoc (ppr nm)) True
578            = do found <- findModule nm
579                 case found of
580                    -- Be sure not to use the mod and location passed in to 
581                    -- summarise for any other purpose -- summarise may change
582                    -- the module names in them if name of module /= name of file,
583                    -- and put the changed versions in the returned summary.
584                    -- These will then conflict with the passed-in versions.
585                    Just (mod, location) -> summarise mod location
586                    Nothing -> throwDyn (OtherError 
587                                    ("no signs of life for module `" 
588                                      ++ showSDoc (ppr nm) ++ "'"))
589                                  
590         -- loop invariant: homeSummaries doesn't contain package modules
591         loop :: [ModSummary] -> IO [ModSummary]
592         loop homeSummaries
593            = do let allImps :: [ModuleName]
594                     allImps = (nub . concatMap ms_imps) homeSummaries
595                 let allHome   -- all modules currently in homeSummaries
596                        = map (moduleName.ms_mod) homeSummaries
597                 let neededImps
598                        = filter (`notElem` allHome) allImps
599                 neededSummaries
600                        <- mapM getSummary neededImps
601                 let newHomeSummaries
602                        = filter (isModuleInThisPackage.ms_mod) neededSummaries
603                 if null newHomeSummaries
604                  then return homeSummaries
605                  else loop (newHomeSummaries ++ homeSummaries)
606
607
608 -- Summarise a module, and pick up source and interface timestamps.
609 summarise :: Module -> ModuleLocation -> IO ModSummary
610 summarise mod location
611    | isModuleInThisPackage mod
612    = do let hs_fn = unJust "summarise" (ml_hs_file location)
613         hspp_fn <- preprocess hs_fn
614         modsrc <- readFile hspp_fn
615         let (srcimps,imps,mod_name) = getImports modsrc
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         -- If the module name is Main, allow it to be in a file
623         -- different from Main.hs, and mash the mod and loc 
624         -- to match.  Otherwise just moan.
625         (mashed_mod, mashed_loc)
626            <- case () of
627               () |  mod_name == moduleName mod
628                  -> return (mod, location)
629                  |  mod_name /= moduleName mod && mod_name == mkModuleName "Main"
630                  -> return (mash mod location "Main")
631                  |  otherwise
632                  -> do hPutStrLn stderr (showSDoc (
633                           text "ghc: warning: file name - module name mismatch:" <+> 
634                           ppr (moduleName mod) <+> text "vs" <+> ppr mod_name))
635                        return (mash mod location (moduleNameUserString (moduleName mod)))
636                where
637                  mash old_mod old_loc new_nm
638                     = (mkHomeModule (mkModuleName new_nm), 
639                        old_loc{ml_hi_file = maybe_swizzle_basename new_nm 
640                                                 (ml_hi_file old_loc)})
641
642                  maybe_swizzle_basename new Nothing = Nothing
643                  maybe_swizzle_basename new (Just old) 
644                     = case splitFilename3 old of 
645                          (dir, name, ext) -> Just (dir ++ new ++ ext)
646
647         return (ModSummary mashed_mod 
648                            mashed_loc{ml_hspp_file=Just hspp_fn} 
649                            srcimps imps
650                            maybe_src_timestamp)
651
652    | otherwise
653    = return (ModSummary mod location [] [] Nothing)
654
655    where
656       maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
657       maybe_getModificationTime fn
658          = (do time <- getModificationTime fn
659                return (Just time)) 
660            `catch`
661            (\err -> return Nothing)
662 \end{code}