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