[project @ 2002-03-14 15:27:15 by simonpj]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2002
3 %
4 % The Compilation Manager
5 %
6 \begin{code}
7 {-# OPTIONS -fvia-C #-}
8 module CompManager ( 
9     ModuleGraph, 
10
11     CmState, emptyCmState,  -- abstract
12
13     cmInit,        -- :: GhciMode -> IO CmState
14
15     cmDepAnal,     -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
16
17     cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18                    --    -> IO (CmState, [String])
19
20     cmUnload,      -- :: CmState -> DynFlags -> IO CmState
21
22 #ifdef GHCI
23     cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24
25     cmSetContext,  -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26     cmGetContext,  -- :: CmState -> IO ([String],[String])
27
28     cmInfoThing,   -- :: CmState -> DynFlags -> String
29                    --   -> IO (CmState, [(TyThing,Fixity)])
30
31     cmBrowseModule, -- :: CmState -> IO [TyThing]
32
33     CmRunResult(..),
34     cmRunStmt,     -- :: CmState -> DynFlags -> String
35                    --    -> IO (CmState, CmRunResult)
36
37     cmTypeOfExpr,  -- :: CmState -> DynFlags -> String
38                    --   -> IO (CmState, Maybe String)
39
40     cmTypeOfName,  -- :: CmState -> Name -> IO (Maybe String)
41
42     HValue,
43     cmCompileExpr, -- :: CmState -> DynFlags -> String 
44                    --   -> IO (CmState, Maybe HValue)
45
46     cmGetModuleGraph,           -- :: CmState -> ModuleGraph
47     cmGetLinkables,             -- :: CmState -> [Linkable]
48
49     cmGetBindings,      -- :: CmState -> [TyThing]
50     cmGetPrintUnqual,   -- :: CmState -> PrintUnqualified
51 #endif
52
53     -- utils
54     showModMsg,         -- 
55   )
56 where
57
58 #include "HsVersions.h"
59
60 import MkIface --tmp
61 import HsSyn    -- tmp
62
63 import CmLink
64 import CmTypes
65 import DriverPipeline
66 import DriverState      ( v_Output_file )
67 import DriverPhases
68 import DriverUtil
69 import Finder
70 #ifdef GHCI
71 import HscMain          ( initPersistentCompilerState, hscThing, 
72                           hscModuleContents )
73 #else
74 import HscMain          ( initPersistentCompilerState )
75 #endif
76 import HscTypes
77 import Name             ( Name, NamedThing(..), nameRdrName, nameModule,
78                           isHomePackageName, isExternalName )
79 import NameEnv
80 import Rename           ( mkGlobalContext )
81 import RdrName          ( emptyRdrEnv )
82 import Module
83 import GetImports
84 import UniqFM
85 import Unique           ( Uniquable )
86 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
87 import ErrUtils         ( showPass )
88 import SysTools         ( cleanTempFilesExcept )
89 import Util
90 import Outputable
91 import Panic
92 import CmdLineOpts      ( DynFlags(..), getDynFlags )
93
94 import IOExts
95
96 #ifdef GHCI
97 import RdrName          ( lookupRdrEnv )
98 import Id               ( idType, idName )
99 import Type             ( tidyType )
100 import VarEnv           ( emptyTidyEnv )
101 import BasicTypes       ( Fixity, defaultFixity )
102 import Interpreter      ( HValue )
103 import HscMain          ( hscStmt )
104 import GlaExts          ( unsafeCoerce# )
105 import Foreign
106 import CForeign
107 import Exception        ( Exception, try )
108 #endif
109
110 -- lang
111 import Exception        ( throwDyn )
112
113 -- std
114 import Directory        ( getModificationTime, doesFileExist )
115 import IO
116 import Monad
117 import List             ( nub )
118 import Maybe
119 \end{code}
120
121
122 \begin{code}
123 -- Persistent state for the entire system
124 data CmState
125    = CmState {
126         hst   :: HomeSymbolTable,    -- home symbol table
127         hit   :: HomeIfaceTable,     -- home interface table
128         ui    :: UnlinkedImage,      -- the unlinked images
129         mg    :: ModuleGraph,        -- the module graph
130         gmode :: GhciMode,           -- NEVER CHANGES
131         ic    :: InteractiveContext, -- command-line binding info
132
133         pcs    :: PersistentCompilerState, -- compile's persistent state
134         pls    :: PersistentLinkerState    -- link's persistent state
135      }
136
137 emptyCmState :: GhciMode -> IO CmState
138 emptyCmState gmode
139     = do pcs     <- initPersistentCompilerState
140          pls     <- emptyPLS
141          return (CmState { hst    = emptySymbolTable,
142                            hit    = emptyIfaceTable,
143                            ui     = emptyUI,
144                            mg     = emptyMG, 
145                            gmode  = gmode,
146                            ic     = emptyInteractiveContext,
147                            pcs    = pcs,
148                            pls    = pls })
149
150 emptyInteractiveContext
151   = InteractiveContext { ic_toplev_scope = [],
152                          ic_exports = [],
153                          ic_rn_gbl_env = emptyRdrEnv,
154                          ic_print_unqual = alwaysQualify,
155                          ic_rn_local_env = emptyRdrEnv,
156                          ic_type_env = emptyTypeEnv }
157
158 -- CM internal types
159 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
160 emptyUI :: UnlinkedImage
161 emptyUI = []
162
163 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
164 emptyMG :: ModuleGraph
165 emptyMG = []
166
167 -----------------------------------------------------------------------------
168 -- Produce an initial CmState.
169
170 cmInit :: GhciMode -> IO CmState
171 cmInit mode = emptyCmState mode
172
173 -----------------------------------------------------------------------------
174 -- Grab information from the CmState
175
176 cmGetModuleGraph        = mg
177 cmGetLinkables          = ui
178
179 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
180 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
181
182 -----------------------------------------------------------------------------
183 -- Setting the context doesn't throw away any bindings; the bindings
184 -- we've built up in the InteractiveContext simply move to the new
185 -- module.  They always shadow anything in scope in the current context.
186
187 cmSetContext
188         :: CmState -> DynFlags
189         -> [String]             -- take the top-level scopes of these modules
190         -> [String]             -- and the just the exports from these
191         -> IO CmState
192 cmSetContext cmstate dflags toplevs exports = do 
193   let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
194
195   toplev_mods <- mapM (getTopLevModule hit)    (map mkModuleName toplevs)
196   export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
197
198   (new_pcs, print_unqual, maybe_env)
199       <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
200
201   case maybe_env of 
202     Nothing -> return cmstate
203     Just env -> return cmstate{ pcs = new_pcs,
204                                 ic = old_ic{ ic_toplev_scope = toplev_mods,
205                                              ic_exports = export_mods,
206                                              ic_rn_gbl_env = env,
207                                              ic_print_unqual = print_unqual } }
208
209 getTopLevModule hit mn =
210   case lookupModuleEnvByName hit mn of
211     Just iface
212       | Just _ <- mi_globals iface -> return (mi_module iface)
213     _other -> throwDyn (CmdLineError (
214           "cannot enter the top-level scope of a compiled module (module `" ++
215            moduleNameUserString mn ++ "')"))
216
217 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
218 moduleNameToModule hit mn = do
219   case lookupModuleEnvByName hit mn of
220     Just iface -> return (mi_module iface)
221     _not_a_home_module -> do
222           maybe_stuff <- findModule mn
223           case maybe_stuff of
224             Nothing -> throwDyn (CmdLineError ("can't find module `"
225                                     ++ moduleNameUserString mn ++ "'"))
226             Just (m,_) -> return m
227
228 cmGetContext :: CmState -> IO ([String],[String])
229 cmGetContext CmState{ic=ic} = 
230   return (map moduleUserString (ic_toplev_scope ic), 
231           map moduleUserString (ic_exports ic))
232
233 cmModuleIsInterpreted :: CmState -> String -> IO Bool
234 cmModuleIsInterpreted cmstate str 
235  = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
236       Just iface         -> return (not (isNothing (mi_globals iface)))
237       _not_a_home_module -> return False
238
239 -----------------------------------------------------------------------------
240 -- cmInfoThing: convert a String to a TyThing
241
242 -- A string may refer to more than one TyThing (eg. a constructor,
243 -- and type constructor), so we return a list of all the possible TyThings.
244
245 #ifdef GHCI
246 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
247 cmInfoThing cmstate dflags id
248    = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
249         let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
250         return (cmstate{ pcs=new_pcs }, pairs)
251    where
252      CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
253
254      getFixity :: PersistentCompilerState -> Name -> Fixity
255      getFixity pcs name
256         | isExternalName name,
257           Just iface  <- lookupModuleEnv iface_table (nameModule name),
258           Just fixity <- lookupNameEnv (mi_fixities iface) name
259           = fixity
260         | otherwise
261           = defaultFixity
262         where iface_table | isHomePackageName name = hit
263                           | otherwise              = pcs_PIT pcs
264 #endif
265
266 -- ---------------------------------------------------------------------------
267 -- cmBrowseModule: get all the TyThings defined in a module
268
269 #ifdef GHCI
270 cmBrowseModule :: CmState -> DynFlags -> String -> Bool 
271         -> IO (CmState, [TyThing])
272 cmBrowseModule cmstate dflags str exports_only = do
273   let mn = mkModuleName str
274   mod <- moduleNameToModule hit mn
275   (pcs1, maybe_ty_things) 
276         <- hscModuleContents dflags hst hit pcs mod exports_only
277   case maybe_ty_things of
278         Nothing -> return (cmstate{pcs=pcs1}, [])
279         Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
280   where
281      CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
282 #endif
283
284 -----------------------------------------------------------------------------
285 -- cmRunStmt:  Run a statement/expr.
286
287 #ifdef GHCI
288 data CmRunResult
289   = CmRunOk [Name]              -- names bound by this evaluation
290   | CmRunFailed 
291   | CmRunException Exception    -- statement raised an exception
292
293 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)         
294 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
295           dflags expr
296    = do 
297         let InteractiveContext { 
298                 ic_rn_local_env = rn_env, 
299                 ic_type_env     = type_env } = icontext
300
301         (new_pcs, maybe_stuff) 
302             <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
303
304         case maybe_stuff of
305            Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
306            Just (ids, _, bcos) -> do
307
308                 -- update the interactive context
309                 let 
310                     names = map idName ids
311
312                     -- these names have just been shadowed
313                     shadowed = [ n | r <- map nameRdrName names,
314                                      Just n <- [lookupRdrEnv rn_env r] ]
315                     
316                     new_rn_env   = extendLocalRdrEnv rn_env names
317
318                     -- remove any shadowed bindings from the type_env
319                     filtered_type_env = delListFromNameEnv type_env shadowed
320
321                     new_type_env = extendNameEnvList filtered_type_env  
322                                         [ (getName id, AnId id) | id <- ids]
323
324                     new_ic = icontext { ic_rn_local_env = new_rn_env, 
325                                         ic_type_env     = new_type_env }
326
327                 -- link it
328                 hval <- linkExpr pls bcos
329
330                 -- run it!
331                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
332                 either_hvals <- sandboxIO thing_to_run
333                 case either_hvals of
334                    Left err
335                         -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
336                               return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
337
338                    Right maybe_hvals ->
339                      case maybe_hvals of
340                         Left e -> 
341                             return ( cmstate{ pcs=new_pcs, ic=new_ic }, 
342                                      CmRunException e )
343                         Right hvals -> do
344                              -- Get the newly bound things, and bind them.  
345                              -- Don't forget to delete any shadowed bindings from the
346                              -- closure_env, lest we end up with a space leak.
347                              pls <- delListFromClosureEnv pls shadowed
348                              new_pls <- addListToClosureEnv pls (zip names hvals)
349              
350                              return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, 
351                                      CmRunOk names)
352
353
354 -- We run the statement in a "sandbox" to protect the rest of the
355 -- system from anything the expression might do.  For now, this
356 -- consists of just wrapping it in an exception handler, but see below
357 -- for another version.
358
359 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
360 sandboxIO thing = do
361   r <- Exception.try thing
362   return (Right r)
363
364 {-
365 -- This version of sandboxIO runs the expression in a completely new
366 -- RTS main thread.  It is disabled for now because ^C exceptions
367 -- won't be delivered to the new thread, instead they'll be delivered
368 -- to the (blocked) GHCi main thread.
369
370 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
371 sandboxIO thing = do
372   st_thing <- newStablePtr (Exception.try thing)
373   alloca $ \ p_st_result -> do
374     stat <- rts_evalStableIO st_thing p_st_result
375     freeStablePtr st_thing
376     if stat == 1
377         then do st_result <- peek p_st_result
378                 result <- deRefStablePtr st_result
379                 freeStablePtr st_result
380                 return (Right result)
381         else do
382                 return (Left (fromIntegral stat))
383
384 foreign import "rts_evalStableIO"  {- safe -}
385   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
386   -- more informative than the C type!
387 -}
388 #endif
389
390 -----------------------------------------------------------------------------
391 -- cmTypeOfExpr: returns a string representing the type of an expression
392
393 #ifdef GHCI
394 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
395 cmTypeOfExpr cmstate dflags expr
396    = do (new_pcs, maybe_stuff) 
397           <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
398
399         let new_cmstate = cmstate{pcs = new_pcs}
400
401         case maybe_stuff of
402            Nothing -> return (new_cmstate, Nothing)
403            Just (_, ty, _) -> return (new_cmstate, Just str)
404              where 
405                 str = showSDocForUser unqual (ppr tidy_ty)
406                 unqual  = ic_print_unqual ic
407                 tidy_ty = tidyType emptyTidyEnv ty
408    where
409        CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
410 #endif
411
412 -----------------------------------------------------------------------------
413 -- cmTypeOfName: returns a string representing the type of a name.
414
415 #ifdef GHCI
416 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
417 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
418  = case lookupNameEnv (ic_type_env ic) name of
419         Nothing -> return Nothing
420         Just (AnId id) -> return (Just str)
421            where
422              unqual = ic_print_unqual ic
423              ty = tidyType emptyTidyEnv (idType id)
424              str = showSDocForUser unqual (ppr ty)
425
426         _ -> panic "cmTypeOfName"
427 #endif
428
429 -----------------------------------------------------------------------------
430 -- cmCompileExpr: compile an expression and deliver an HValue
431
432 #ifdef GHCI
433 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
434 cmCompileExpr cmstate dflags expr
435    = do 
436         let InteractiveContext { 
437                 ic_rn_local_env = rn_env, 
438                 ic_type_env     = type_env } = icontext
439
440         (new_pcs, maybe_stuff) 
441             <- hscStmt dflags hst hit pcs icontext 
442                   ("let __cmCompileExpr = "++expr) False{-stmt-}
443
444         case maybe_stuff of
445            Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
446            Just (ids, _, bcos) -> do
447
448                 -- link it
449                 hval <- linkExpr pls bcos
450
451                 -- run it!
452                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
453                 hvals <- thing_to_run
454
455                 case (ids,hvals) of
456                   ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
457                   _ -> panic "cmCompileExpr"
458
459    where
460        CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
461 #endif
462
463 -----------------------------------------------------------------------------
464 -- Unload the compilation manager's state: everything it knows about the
465 -- current collection of modules in the Home package.
466
467 cmUnload :: CmState -> DynFlags -> IO CmState
468 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
469  = do -- Throw away the old home dir cache
470       emptyHomeDirCache
471
472       -- Unload everything the linker knows about
473       new_pls <- CmLink.unload mode dflags [] pls 
474
475       -- Start with a fresh CmState, but keep the PersistentCompilerState
476       new_state <- cmInit mode
477       return new_state{ pcs=pcs, pls=new_pls }
478
479
480 -----------------------------------------------------------------------------
481 -- Trace dependency graph
482
483 -- This is a seperate pass so that the caller can back off and keep
484 -- the current state if the downsweep fails.
485
486 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
487 cmDepAnal cmstate dflags rootnames
488   = do showPass dflags "Chasing dependencies"
489        when (verbosity dflags >= 1 && gmode cmstate == Batch) $
490            hPutStrLn stderr (showSDoc (hcat [
491              text progName, text ": chasing modules from: ",
492              hcat (punctuate comma (map text rootnames))]))
493        downsweep rootnames (mg cmstate)
494
495 -----------------------------------------------------------------------------
496 -- The real business of the compilation manager: given a system state and
497 -- a module name, try and bring the module up to date, probably changing
498 -- the system state at the same time.
499
500 cmLoadModules :: CmState 
501              -> DynFlags
502              -> ModuleGraph
503              -> IO (CmState,            -- new state
504                     Bool,               -- was successful
505                     [String])           -- list of modules loaded
506
507 cmLoadModules cmstate1 dflags mg2unsorted
508    = do -- version 1's are the original, before downsweep
509         let pls1      = pls    cmstate1
510         let pcs1      = pcs    cmstate1
511         let hst1      = hst    cmstate1
512         let hit1      = hit    cmstate1
513         -- similarly, ui1 is the (complete) set of linkables from
514         -- the previous pass, if any.
515         let ui1       = ui     cmstate1
516
517         let ghci_mode = gmode cmstate1 -- this never changes
518
519         -- Do the downsweep to reestablish the module graph
520         let verb = verbosity dflags
521
522         -- Find out if we have a Main module
523         let a_root_is_Main 
524                = any ((=="Main").moduleNameUserString.modSummaryName) 
525                      mg2unsorted
526
527         let mg2unsorted_names = map modSummaryName mg2unsorted
528
529         -- reachable_from follows source as well as normal imports
530         let reachable_from :: ModuleName -> [ModuleName]
531             reachable_from = downwards_closure_of_module mg2unsorted
532  
533         -- should be cycle free; ignores 'import source's
534         let mg2 = topological_sort False mg2unsorted
535         -- ... whereas this takes them into account.  Used for
536         -- backing out partially complete cycles following a failed
537         -- upsweep, and for removing from hst/hit all the modules
538         -- not in strict downwards closure, during calls to compile.
539         let mg2_with_srcimps = topological_sort True mg2unsorted
540
541         -- Sort out which linkables we wish to keep in the unlinked image.
542         -- See getValidLinkables below for details.
543         (valid_old_linkables, new_linkables)
544             <- getValidLinkables ui1 mg2unsorted_names mg2_with_srcimps
545
546         -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
547
548                 -- uniq of ModuleName is the same as Module, fortunately...
549         let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
550
551         -- When (verb >= 2) $
552         --    putStrLn (showSDoc (text "Valid linkables:" 
553         --                       <+> ppr valid_linkables))
554
555         -- Figure out a stable set of modules which can be retained
556         -- the top level envs, to avoid upsweeping them.  Goes to a
557         -- bit of trouble to avoid upsweeping module cycles.
558         --
559         -- Construct a set S of stable modules like this:
560         -- Travel upwards, over the sccified graph.  For each scc
561         -- of modules ms, add ms to S only if:
562         -- 1.  All home imports of ms are either in ms or S
563         -- 2.  A valid old linkable exists for each module in ms
564
565         stable_mods <- preUpsweep valid_old_linkables
566                                   mg2unsorted_names [] mg2_with_srcimps
567
568         let stable_summaries
569                = concatMap (findInSummaries mg2unsorted) stable_mods
570
571             stable_linkables
572                = filter (\m -> linkableModName m `elem` stable_mods) 
573                     valid_old_linkables
574
575         when (verb >= 2) $
576            putStrLn (showSDoc (text "Stable modules:" 
577                                <+> sep (map (text.moduleNameUserString) stable_mods)))
578
579         -- unload any modules which are going to be re-linked this
580         -- time around.
581         pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
582
583         -- we can now glom together our linkable sets
584         let valid_linkables = valid_old_linkables ++ new_linkables
585
586         -- We could at this point detect cycles which aren't broken by
587         -- a source-import, and complain immediately, but it seems better
588         -- to let upsweep_mods do this, so at least some useful work gets
589         -- done before the upsweep is abandoned.
590         let upsweep_these
591                = filter (\scc -> any (`notElem` stable_mods) 
592                                      (map modSummaryName (flattenSCC scc)))
593                         mg2
594
595         --hPutStrLn stderr "after tsort:\n"
596         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
597
598         -- Because we don't take into account source imports when doing
599         -- the topological sort, there shouldn't be any cycles in mg2.
600         -- If there is, we complain and give up -- the user needs to
601         -- break the cycle using a boot file.
602
603         -- Now do the upsweep, calling compile for each module in
604         -- turn.  Final result is version 3 of everything.
605
606         let threaded2 = CmThreaded pcs1 hst1 hit2
607
608         -- clean up between compilations
609         let cleanup = cleanTempFilesExcept verb 
610                           (ppFilesFromSummaries (flattenSCCs upsweep_these))
611
612         (upsweep_complete_success, threaded3, modsUpswept, newLis)
613            <- upsweep_mods ghci_mode dflags valid_linkables reachable_from 
614                            threaded2 cleanup upsweep_these
615
616         let ui3 = add_to_ui valid_linkables newLis
617         let (CmThreaded pcs3 hst3 hit3) = threaded3
618
619         -- At this point, modsUpswept and newLis should have the same
620         -- length, so there is one new (or old) linkable for each 
621         -- mod which was processed (passed to compile).
622
623         -- Make modsDone be the summaries for each home module now
624         -- available; this should equal the domains of hst3 and hit3.
625         -- (NOT STRICTLY TRUE if an interactive session was started
626         --  with some object on disk ???)
627         -- Get in in a roughly top .. bottom order (hence reverse).
628
629         let modsDone = reverse modsUpswept ++ stable_summaries
630
631         -- Try and do linking in some form, depending on whether the
632         -- upsweep was completely or only partially successful.
633
634         if upsweep_complete_success
635
636          then 
637            -- Easy; just relink it all.
638            do when (verb >= 2) $ 
639                  hPutStrLn stderr "Upsweep completely successful."
640
641               -- clean up after ourselves
642               cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
643
644               -- issue a warning for the confusing case where the user said '-o foo'
645               -- but we're not going to do any linking.
646               ofile <- readIORef v_Output_file
647               when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
648                      && verb > 0) $
649                  hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
650
651               -- link everything together
652               linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
653
654               cmLoadFinish True linkresult 
655                         hst3 hit3 ui3 modsDone ghci_mode pcs3
656
657          else 
658            -- Tricky.  We need to back out the effects of compiling any
659            -- half-done cycles, both so as to clean up the top level envs
660            -- and to avoid telling the interactive linker to link them.
661            do when (verb >= 2) $
662                 hPutStrLn stderr "Upsweep partially successful."
663
664               let modsDone_names
665                      = map modSummaryName modsDone
666               let mods_to_zap_names 
667                      = findPartiallyCompletedCycles modsDone_names 
668                           mg2_with_srcimps
669               let mods_to_keep
670                      = filter ((`notElem` mods_to_zap_names).modSummaryName) 
671                           modsDone
672
673               let (hst4, hit4, ui4)
674                      = retainInTopLevelEnvs (map modSummaryName mods_to_keep) 
675                                             (hst3,hit3,ui3)
676
677               -- clean up after ourselves
678               cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
679
680               -- link everything together
681               linkresult <- link ghci_mode dflags False ui4 pls2
682
683               cmLoadFinish False linkresult 
684                     hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
685
686
687 -- Finish up after a cmLoad.
688
689 -- If the link failed, unload everything and return.
690 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
691   dflags <- getDynFlags
692   new_pls <- CmLink.unload ghci_mode dflags [] pls 
693   new_state <- cmInit ghci_mode
694   return (new_state{ pcs=pcs, pls=new_pls }, False, [])
695
696 -- Empty the interactive context and set the module context to the topmost
697 -- newly loaded module, or the Prelude if none were loaded.
698 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
699   = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
700                                   gmode=ghci_mode, pcs=pcs, pls=pls,
701                                   ic = emptyInteractiveContext }
702            mods_loaded = map (moduleNameUserString.modSummaryName) mods
703
704        return (new_cmstate, ok, mods_loaded)
705
706 -- used to fish out the preprocess output files for the purposes
707 -- of cleaning up.
708 ppFilesFromSummaries summaries
709   = [ fn | Just fn <- map toPpFile summaries ]
710   where
711    toPpFile sum
712      | hspp /= ml_hs_file loc = hspp
713      | otherwise              = Nothing
714     where
715       loc  = ms_location sum
716       hspp = ml_hspp_file loc
717
718
719 -----------------------------------------------------------------------------
720 -- getValidLin
721
722 -- For each module (or SCC of modules), we take:
723 --
724 --      - an on-disk linkable, if this is the first time around and one
725 --        is available.
726 --
727 --      - the old linkable, otherwise (and if one is available).
728 --
729 -- and we throw away the linkable if it is older than the source
730 -- file.  We ignore the on-disk linkables unless all of the dependents
731 -- of this SCC also have on-disk linkables.
732 --
733 -- If a module has a valid linkable, then it may be STABLE (see below),
734 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
735 -- compile.
736 --
737 -- ToDo: this pass could be merged with the preUpsweep.
738
739 getValidLinkables
740         :: [Linkable]           -- old linkables
741         -> [ModuleName]         -- all home modules
742         -> [SCC ModSummary]     -- all modules in the program, dependency order
743         -> IO ( [Linkable],     -- still-valid linkables 
744                 [Linkable]      -- new linkables we just found
745               )
746
747 getValidLinkables old_linkables all_home_mods module_graph = do
748   ls <- foldM (getValidLinkablesSCC old_linkables all_home_mods) 
749                 [] module_graph
750   return (partition_it ls [] [])
751  where
752   partition_it []         valid new = (valid,new)
753   partition_it ((l,b):ls) valid new 
754         | b         = partition_it ls valid (l:new)
755         | otherwise = partition_it ls (l:valid) new
756
757
758 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
759    = let 
760           scc             = flattenSCC scc0
761           scc_names       = map modSummaryName scc
762           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
763           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
764                 -- NB. ms_imps, not ms_allimps above.  We don't want to
765                 -- force a module's SOURCE imports to be already compiled for
766                 -- its object linkable to be valid.
767
768           has_object m = 
769                 case findModuleLinkable_maybe (map fst new_linkables) m of
770                     Nothing -> False
771                     Just l  -> isObjectLinkable l
772
773           objects_allowed = all has_object scc_allhomeimps
774      in do
775
776      new_linkables'
777         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
778
779         -- since an scc can contain only all objects or no objects at all,
780         -- we have to check whether we got all objects or not, and re-do
781         -- the linkable check if not.
782      new_linkables' <- 
783         if objects_allowed
784              && not (all isObjectLinkable (map fst new_linkables'))
785           then foldM (getValidLinkable old_linkables False) [] scc
786           else return new_linkables'
787
788      return (new_linkables ++ new_linkables')
789
790
791 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary 
792         -> IO [(Linkable,Bool)]
793         -- True <=> linkable is new
794 getValidLinkable old_linkables objects_allowed new_linkables summary 
795    = do let mod_name = modSummaryName summary
796
797         maybe_disk_linkable
798           <- if (not objects_allowed)
799                 then return Nothing
800
801                 else case ml_obj_file (ms_location summary) of
802                         Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
803                         Nothing     -> return Nothing
804
805         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
806
807             new_linkables' = 
808              case (old_linkable, maybe_disk_linkable) of
809                 (Nothing, Nothing)                      -> []
810
811                 -- new object linkable just appeared
812                 (Nothing, Just l)                       -> up_to_date l True
813
814                 (Just l,  Nothing)
815                   | isObjectLinkable l                  -> []
816                     -- object linkable disappeared!  In case we need to
817                     -- relink the module, disregard the old linkable and
818                     -- just interpret the module from now on.
819                   | otherwise                           -> up_to_date l False
820                     -- old byte code linkable
821
822                 (Just l, Just l') 
823                   | not (isObjectLinkable l)            -> up_to_date l  False
824                     -- if the previous linkable was interpreted, then we
825                     -- ignore a newly compiled version, because the version
826                     -- numbers in the interface file will be out-of-sync with
827                     -- our internal ones.
828                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
829                   | linkableTime l' == linkableTime l   -> up_to_date l  False
830                   | otherwise                           -> []
831                     -- on-disk linkable has been replaced by an older one!
832                     -- again, disregard the previous one.
833
834             up_to_date l b
835                 | linkableTime l < ms_hs_date summary = []
836                 | otherwise = [(l,b)]
837                 -- why '<' rather than '<=' above?  If the filesystem stores
838                 -- times to the nearset second, we may occasionally find that
839                 -- the object & source have the same modification time, 
840                 -- especially if the source was automatically generated
841                 -- and compiled.  Using >= is slightly unsafe, but it matches
842                 -- make's behaviour.
843
844         return (new_linkables' ++ new_linkables)
845
846
847 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
848 maybe_getFileLinkable mod obj_fn
849    = do obj_exist <- doesFileExist obj_fn
850         if not obj_exist 
851          then return Nothing 
852          else 
853          do let stub_fn = case splitFilename3 obj_fn of
854                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
855             stub_exist <- doesFileExist stub_fn
856             obj_time <- getModificationTime obj_fn
857             if stub_exist
858              then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
859              else return (Just (LM obj_time mod [DotO obj_fn]))
860
861
862 -----------------------------------------------------------------------------
863 -- Do a pre-upsweep without use of "compile", to establish a 
864 -- (downward-closed) set of stable modules for which we won't call compile.
865
866 -- a stable module:
867 --      * has a valid linkable (see getValidLinkables above)
868 --      * depends only on stable modules
869 --      * has an interface in the HIT (interactive mode only)
870
871 preUpsweep :: [Linkable]        -- new valid linkables
872            -> [ModuleName]      -- names of all mods encountered in downsweep
873            -> [ModuleName]      -- accumulating stable modules
874            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
875            -> IO [ModuleName]   -- stable modules
876
877 preUpsweep valid_lis all_home_mods stable []  = return stable
878 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
879    = do let scc = flattenSCC scc0
880             scc_allhomeimps :: [ModuleName]
881             scc_allhomeimps 
882                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
883             all_imports_in_scc_or_stable
884                = all in_stable_or_scc scc_allhomeimps
885             scc_names
886                 = map modSummaryName scc
887             in_stable_or_scc m
888                = m `elem` scc_names || m `elem` stable
889
890             -- now we check for valid linkables: each module in the SCC must 
891             -- have a valid linkable (see getValidLinkables above).
892             has_valid_linkable new_summary
893               = isJust (findModuleLinkable_maybe valid_lis modname)
894                where modname = modSummaryName new_summary
895
896             scc_is_stable = all_imports_in_scc_or_stable
897                           && all has_valid_linkable scc
898
899         if scc_is_stable
900          then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
901          else preUpsweep valid_lis all_home_mods stable sccs
902
903
904 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
905 -- stable (in the sense of preUpsweep), determine if new_summary is itself
906 -- stable, and, if so, in batch mode, return its linkable.
907 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
908 findInSummaries old_summaries mod_name
909    = [s | s <- old_summaries, modSummaryName s == mod_name]
910
911 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
912 findModInSummaries old_summaries mod
913    = case [s | s <- old_summaries, ms_mod s == mod] of
914          [] -> Nothing
915          (s:_) -> Just s
916
917 -- Return (names of) all those in modsDone who are part of a cycle
918 -- as defined by theGraph.
919 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
920 findPartiallyCompletedCycles modsDone theGraph
921    = chew theGraph
922      where
923         chew [] = []
924         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
925         chew ((CyclicSCC vs):rest)
926            = let names_in_this_cycle = nub (map modSummaryName vs)
927                  mods_in_this_cycle  
928                     = nub ([done | done <- modsDone, 
929                                    done `elem` names_in_this_cycle])
930                  chewed_rest = chew rest
931              in 
932              if   not (null mods_in_this_cycle) 
933                   && length mods_in_this_cycle < length names_in_this_cycle
934              then mods_in_this_cycle ++ chewed_rest
935              else chewed_rest
936
937
938 -- Add the given (LM-form) Linkables to the UI, overwriting previous
939 -- versions if they exist.
940 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
941 add_to_ui ui lis
942    = filter (not_in lis) ui ++ lis
943      where
944         not_in :: [Linkable] -> Linkable -> Bool
945         not_in lis li
946            = all (\l -> linkableModName l /= mod) lis
947            where mod = linkableModName li
948                                   
949
950 data CmThreaded  -- stuff threaded through individual module compilations
951    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
952
953
954 -- Compile multiple modules, stopping as soon as an error appears.
955 -- There better had not be any cyclic groups here -- we check for them.
956 upsweep_mods :: GhciMode
957              -> DynFlags
958              -> UnlinkedImage         -- valid linkables
959              -> (ModuleName -> [ModuleName])  -- to construct downward closures
960              -> CmThreaded            -- PCS & HST & HIT
961              -> IO ()                 -- how to clean up unwanted tmp files
962              -> [SCC ModSummary]      -- mods to do (the worklist)
963                                       -- ...... RETURNING ......
964              -> IO (Bool{-complete success?-},
965                     CmThreaded,
966                     [ModSummary],     -- mods which succeeded
967                     [Linkable])       -- new linkables
968
969 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
970      []
971    = return (True, threaded, [], [])
972
973 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
974      ((CyclicSCC ms):_)
975    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
976                           unwords (map (moduleNameUserString.modSummaryName) ms))
977         return (False, threaded, [], [])
978
979 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
980      ((AcyclicSCC mod):mods)
981    = do --case threaded of
982         --   CmThreaded pcsz hstz hitz
983         --      -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
984
985         (threaded1, maybe_linkable) 
986            <- upsweep_mod ghci_mode dflags oldUI threaded mod 
987                           (reachable_from (modSummaryName mod))
988
989         -- remove unwanted tmp files between compilations
990         cleanup
991
992         case maybe_linkable of
993            Just linkable 
994               -> -- No errors; do the rest
995                  do (restOK, threaded2, modOKs, linkables) 
996                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
997                                        threaded1 cleanup mods
998                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
999            Nothing -- we got a compilation error; give up now
1000               -> return (False, threaded1, [], [])
1001
1002
1003 -- Compile a single module.  Always produce a Linkable for it if 
1004 -- successful.  If no compilation happened, return the old Linkable.
1005 upsweep_mod :: GhciMode 
1006             -> DynFlags
1007             -> UnlinkedImage
1008             -> CmThreaded
1009             -> ModSummary
1010             -> [ModuleName]
1011             -> IO (CmThreaded, Maybe Linkable)
1012
1013 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1014    = do 
1015         let mod_name = modSummaryName summary1
1016
1017         let (CmThreaded pcs1 hst1 hit1) = threaded1
1018         let old_iface = lookupUFM hit1 mod_name
1019
1020         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1021
1022             source_unchanged = isJust maybe_old_linkable
1023
1024             reachable_only = filter (/= (modSummaryName summary1)) 
1025                                 reachable_inc_me
1026
1027            -- in interactive mode, all home modules below us *must* have an
1028            -- interface in the HIT.  We never demand-load home interfaces in
1029            -- interactive mode.
1030             (hst1_strictDC, hit1_strictDC, [])
1031                = ASSERT(ghci_mode == Batch || 
1032                         all (`elemUFM` hit1) reachable_only)
1033                  retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1034
1035             old_linkable 
1036                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
1037
1038             have_object 
1039                | Just l <- maybe_old_linkable, isObjectLinkable l = True
1040                | otherwise = False
1041
1042         compresult <- compile ghci_mode summary1 source_unchanged
1043                          have_object old_iface hst1_strictDC hit1_strictDC pcs1
1044
1045         case compresult of
1046
1047            -- Compilation "succeeded", and may or may not have returned a new
1048            -- linkable (depending on whether compilation was actually performed
1049            -- or not).
1050            CompOK pcs2 new_details new_iface maybe_new_linkable
1051               -> do let hst2      = addToUFM hst1 mod_name new_details
1052                         hit2      = addToUFM hit1 mod_name new_iface
1053                         threaded2 = CmThreaded pcs2 hst2 hit2
1054
1055                     return (threaded2, if isJust maybe_new_linkable
1056                                           then maybe_new_linkable
1057                                           else Just old_linkable)
1058
1059            -- Compilation failed.  compile may still have updated
1060            -- the PCS, tho.
1061            CompErrs pcs2
1062               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1063                     return (threaded2, Nothing)
1064
1065 -- Filter modules in the top level envs (HST, HIT, UI).
1066 retainInTopLevelEnvs :: [ModuleName]
1067                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1068                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1069 retainInTopLevelEnvs keep_these (hst, hit, ui)
1070    = (retainInUFM hst keep_these,
1071       retainInUFM hit keep_these,
1072       filterModuleLinkables (`elem` keep_these) ui
1073      )
1074      where
1075         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1076         retainInUFM ufm keys_to_keep
1077            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1078         maybeLookupUFM ufm u 
1079            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
1080
1081 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1082 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1083 downwards_closure_of_module summaries root
1084    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1085          toEdge summ = (modSummaryName summ, 
1086                         filter (`elem` all_mods) (ms_allimps summ))
1087
1088          all_mods = map modSummaryName summaries
1089
1090          res = simple_transitive_closure (map toEdge summaries) [root]
1091      in
1092 --         trace (showSDoc (text "DC of mod" <+> ppr root
1093 --                          <+> text "=" <+> ppr res)) $
1094          res
1095
1096 -- Calculate transitive closures from a set of roots given an adjacency list
1097 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1098 simple_transitive_closure graph set 
1099    = let set2      = nub (concatMap dsts set ++ set)
1100          dsts node = fromMaybe [] (lookup node graph)
1101      in
1102          if   length set == length set2
1103          then set
1104          else simple_transitive_closure graph set2
1105
1106
1107 -- Calculate SCCs of the module graph, with or without taking into
1108 -- account source imports.
1109 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1110 topological_sort include_source_imports summaries
1111    = let 
1112          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1113          toEdge summ
1114              = (summ, modSummaryName summ, 
1115                       (if include_source_imports 
1116                        then ms_srcimps summ else []) ++ ms_imps summ)
1117         
1118          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1119          mash_edge (summ, m, m_imports)
1120             = case lookup m key_map of
1121                  Nothing -> panic "reverse_topological_sort"
1122                  Just mk -> (summ, mk, 
1123                                 -- ignore imports not from the home package
1124                                 catMaybes (map (flip lookup key_map) m_imports))
1125
1126          edges     = map toEdge summaries
1127          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1128          scc_input = map mash_edge edges
1129          sccs      = stronglyConnComp scc_input
1130      in
1131          sccs
1132
1133
1134 -----------------------------------------------------------------------------
1135 -- Downsweep (dependency analysis)
1136
1137 -- Chase downwards from the specified root set, returning summaries
1138 -- for all home modules encountered.  Only follow source-import
1139 -- links.
1140
1141 -- We pass in the previous collection of summaries, which is used as a
1142 -- cache to avoid recalculating a module summary if the source is
1143 -- unchanged.
1144
1145 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1146 downsweep roots old_summaries
1147    = do rootSummaries <- mapM getRootSummary roots
1148         all_summaries
1149            <- loop (concat (map ms_imps rootSummaries))
1150                 (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
1151                                           let mod = ms_mod s, isHomeModule mod 
1152                              ])
1153         return all_summaries
1154      where
1155         getRootSummary :: FilePath -> IO ModSummary
1156         getRootSummary file
1157            | haskellish_src_file file
1158            = do exists <- doesFileExist file
1159                 if exists then summariseFile file else do
1160                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
1161            | otherwise
1162            = do exists <- doesFileExist hs_file
1163                 if exists then summariseFile hs_file else do
1164                 exists <- doesFileExist lhs_file
1165                 if exists then summariseFile lhs_file else do
1166                 let mod_name = mkModuleName file
1167                 maybe_summary <- getSummary mod_name
1168                 case maybe_summary of
1169                    Nothing -> packageModErr mod_name
1170                    Just s  -> return s
1171            where 
1172                  hs_file = file ++ ".hs"
1173                  lhs_file = file ++ ".lhs"
1174
1175         getSummary :: ModuleName -> IO (Maybe ModSummary)
1176         getSummary nm
1177            = do found <- findModule nm
1178                 case found of
1179                    Just (mod, location) -> do
1180                         let old_summary = findModInSummaries old_summaries mod
1181                         summarise mod location old_summary
1182
1183                    Nothing -> throwDyn (CmdLineError 
1184                                    ("can't find module `" 
1185                                      ++ showSDoc (ppr nm) ++ "'"))
1186
1187         -- loop invariant: env doesn't contain package modules
1188         loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1189         loop [] env = return (moduleEnvElts env)
1190         loop imps env
1191            = do -- imports for modules we don't already have
1192                 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1193
1194                 -- summarise them
1195                 needed_summaries <- mapM getSummary needed_imps
1196
1197                 -- get just the "home" modules
1198                 let new_home_summaries = [ s | Just s <- needed_summaries ]
1199
1200                 -- loop, checking the new imports
1201                 let new_imps = concat (map ms_imps new_home_summaries)
1202                 loop new_imps (extendModuleEnvList env 
1203                                 [ (ms_mod s, s) | s <- new_home_summaries ])
1204
1205 -----------------------------------------------------------------------------
1206 -- Summarising modules
1207
1208 -- We have two types of summarisation:
1209 --
1210 --    * Summarise a file.  This is used for the root module(s) passed to
1211 --      cmLoadModules.  The file is read, and used to determine the root
1212 --      module name.  The module name may differ from the filename.
1213 --
1214 --    * Summarise a module.  We are given a module name, and must provide
1215 --      a summary.  The finder is used to locate the file in which the module
1216 --      resides.
1217
1218 summariseFile :: FilePath -> IO ModSummary
1219 summariseFile file
1220    = do hspp_fn <- preprocess file
1221         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1222
1223         let (path, basename, _ext) = splitFilename3 file
1224
1225         (mod, location)
1226            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1227
1228         src_timestamp
1229            <- case ml_hs_file location of 
1230                  Nothing     -> noHsFileErr mod_name
1231                  Just src_fn -> getModificationTime src_fn
1232
1233         return (ModSummary mod
1234                            location{ml_hspp_file=Just hspp_fn}
1235                            srcimps imps src_timestamp)
1236
1237 -- Summarise a module, and pick up source and timestamp.
1238 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1239          -> IO (Maybe ModSummary)
1240 summarise mod location old_summary
1241    | not (isHomeModule mod) = return Nothing
1242    | otherwise
1243    = do let hs_fn = unJust "summarise" (ml_hs_file location)
1244
1245         case ml_hs_file location of {
1246            Nothing -> noHsFileErr mod;
1247            Just src_fn -> do
1248
1249         src_timestamp <- getModificationTime src_fn
1250
1251         -- return the cached summary if the source didn't change
1252         case old_summary of {
1253            Just s | ms_hs_date s == src_timestamp -> return (Just s);
1254            _ -> do
1255
1256         hspp_fn <- preprocess hs_fn
1257         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1258
1259         when (mod_name /= moduleName mod) $
1260                 throwDyn (ProgramError 
1261                    (showSDoc (text hs_fn
1262                               <>  text ": file name does not match module name"
1263                               <+> quotes (ppr (moduleName mod)))))
1264
1265         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1266                                  srcimps imps src_timestamp))
1267         }
1268       }
1269
1270
1271 noHsFileErr mod
1272   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1273
1274 packageModErr mod
1275   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1276                                    quotes (ppr mod) <+>
1277                                    text "is a package module")))
1278 \end{code}