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