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