[project @ 2004-07-21 10:07:29 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, ModSummary(..),
10
11     CmState,            -- abstract
12
13     cmInit,        -- :: GhciMode -> DynFlags -> IO CmState
14
15     cmDepAnal,     -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
16
17     cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18                    --    -> IO (CmState, Bool, [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 -> String -> IO (CmState, [(TyThing,Fixity)])
29     cmBrowseModule, -- :: CmState -> IO [TyThing]
30
31     CmRunResult(..),
32     cmRunStmt,     -- :: CmState -> DynFlags -> String
33                    --    -> IO (CmState, CmRunResult)
34
35     cmTypeOfExpr,  -- :: CmState -> DynFlags -> String
36                    --   -> IO (CmState, Maybe String)
37
38     cmKindOfType,  -- :: CmState -> DynFlags -> String
39                    --   -> IO (CmState, Maybe String)
40
41     cmTypeOfName,  -- :: CmState -> Name -> IO (Maybe String)
42
43     HValue,
44     cmCompileExpr, -- :: CmState -> DynFlags -> String 
45                    --   -> IO (CmState, Maybe HValue)
46
47     cmGetModInfo,               -- :: CmState -> (ModuleGraph, HomePackageTable)
48
49     cmSetDFlags,
50     cmGetBindings,      -- :: CmState -> [TyThing]
51     cmGetPrintUnqual,   -- :: CmState -> PrintUnqualified
52 #endif
53   )
54 where
55
56 #include "HsVersions.h"
57
58 import DriverPipeline   ( CompResult(..), preprocess, compile, link )
59 import HscMain          ( newHscEnv )
60 import DriverState      ( v_Output_file, v_NoHsMain, v_MainModIs )
61 import DriverPhases
62 import Finder
63 import HscTypes
64 import PrelNames        ( gHC_PRIM_Name )
65 import Module           ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
66                           ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
67                           extendModuleEnvList, extendModuleEnv,
68                           moduleNameUserString,
69                           ModLocation(..) )
70 import GetImports
71 import UniqFM
72 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
73 import ErrUtils         ( showPass )
74 import SysTools         ( cleanTempFilesExcept )
75 import BasicTypes       ( SuccessFlag(..), succeeded, failed )
76 import Util
77 import Outputable
78 import Panic
79 import CmdLineOpts      ( DynFlags(..), getDynFlags )
80 import Maybes           ( expectJust, orElse, mapCatMaybes )
81
82 import DATA_IOREF       ( readIORef )
83
84 #ifdef GHCI
85 import HscMain          ( hscThing, hscStmt, hscTcExpr, hscKcType )
86 import TcRnDriver       ( mkExportEnv, getModuleContents )
87 import IfaceSyn         ( IfaceDecl )
88 import RdrName          ( GlobalRdrEnv, plusGlobalRdrEnv )
89 import Name             ( Name )
90 import NameEnv
91 import Id               ( idType )
92 import Type             ( tidyType )
93 import VarEnv           ( emptyTidyEnv )
94 import BasicTypes       ( Fixity )
95 import Linker           ( HValue, unload, extendLinkEnv )
96 import GHC.Exts         ( unsafeCoerce# )
97 import Foreign
98 import SrcLoc           ( SrcLoc )
99 import Control.Exception as Exception ( Exception, try )
100 #endif
101
102 import EXCEPTION        ( throwDyn )
103
104 -- std
105 import Directory        ( getModificationTime, doesFileExist )
106 import IO
107 import Monad
108 import List             ( nub )
109 import Maybe
110 import Time             ( ClockTime )
111 \end{code}
112
113
114 \begin{code}
115 -- Persistent state for the entire system
116 data CmState
117    = CmState {
118         cm_hsc :: HscEnv,               -- Includes the home-package table
119         cm_mg  :: ModuleGraph,          -- The module graph
120         cm_ic  :: InteractiveContext    -- Command-line binding info
121      }
122
123 #ifdef GHCI
124 cmGetModInfo     cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
125 cmGetBindings    cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
126 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
127 cmHPT            cmstate = hsc_HPT (cm_hsc cmstate)
128 #endif
129
130 cmInit :: GhciMode -> DynFlags -> IO CmState
131 cmInit ghci_mode dflags
132    = do { hsc_env <- newHscEnv ghci_mode dflags
133         ; return (CmState { cm_hsc = hsc_env,
134                             cm_mg  = emptyMG, 
135                             cm_ic  = emptyInteractiveContext })}
136
137 discardCMInfo :: CmState -> CmState
138 -- Forget the compilation manager's state, including the home package table
139 -- but retain the persistent info in HscEnv
140 discardCMInfo cm_state
141   = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
142                cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
143
144 -------------------------------------------------------------------
145 --                      The unlinked image
146 -- 
147 -- The compilation manager keeps a list of compiled, but as-yet unlinked
148 -- binaries (byte code or object code).  Even when it links bytecode
149 -- it keeps the unlinked version so it can re-link it later without
150 -- recompiling.
151
152 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
153
154 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
155 findModuleLinkable_maybe lis mod
156    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
157         []   -> Nothing
158         [li] -> Just li
159         many -> pprPanic "findModuleLinkable" (ppr mod)
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165         GHCI stuff
166 %*                                                                      *
167 %************************************************************************
168
169 \begin{code}
170 #ifdef GHCI
171 -----------------------------------------------------------------------------
172 -- Setting the context doesn't throw away any bindings; the bindings
173 -- we've built up in the InteractiveContext simply move to the new
174 -- module.  They always shadow anything in scope in the current context.
175
176 cmSetContext
177         :: CmState
178         -> [String]             -- take the top-level scopes of these modules
179         -> [String]             -- and the just the exports from these
180         -> IO CmState
181 cmSetContext cmstate toplevs exports = do 
182   let old_ic  = cm_ic cmstate
183       hsc_env = cm_hsc cmstate
184       hpt     = hsc_HPT hsc_env
185
186   export_env  <- mkExportEnv hsc_env (map mkModuleName exports)
187   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
188
189   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
190   return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
191                                    ic_exports      = exports,
192                                    ic_rn_gbl_env   = all_env } }
193
194 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
195 mkTopLevEnv hpt mod
196  = case lookupModuleEnvByName hpt (mkModuleName mod) of
197       Nothing      -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
198       Just details -> case hm_globals details of
199                         Nothing  -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
200                         Just env -> return env
201
202 cmGetContext :: CmState -> IO ([String],[String])
203 cmGetContext CmState{cm_ic=ic} = 
204   return (ic_toplev_scope ic, ic_exports ic)
205
206 cmModuleIsInterpreted :: CmState -> String -> IO Bool
207 cmModuleIsInterpreted cmstate str 
208  = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
209       Just details       -> return (isJust (hm_globals details))
210       _not_a_home_module -> return False
211
212 -----------------------------------------------------------------------------
213 cmSetDFlags :: CmState -> DynFlags -> CmState
214 cmSetDFlags cm_state dflags 
215   = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
216
217 -----------------------------------------------------------------------------
218 -- cmInfoThing: convert a String to a TyThing
219
220 -- A string may refer to more than one TyThing (eg. a constructor,
221 -- and type constructor), so we return a list of all the possible TyThings.
222
223 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity,SrcLoc)]
224 cmInfoThing cmstate id
225    = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
226
227 -- ---------------------------------------------------------------------------
228 -- cmBrowseModule: get all the TyThings defined in a module
229
230 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
231 cmBrowseModule cmstate str exports_only
232   = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate) 
233                                        (mkModuleName str) exports_only
234        ; case mb_decls of
235            Nothing -> return []         -- An error of some kind
236            Just ds -> return ds
237    }
238
239
240 -----------------------------------------------------------------------------
241 -- cmRunStmt:  Run a statement/expr.
242
243 data CmRunResult
244   = CmRunOk [Name]              -- names bound by this evaluation
245   | CmRunFailed 
246   | CmRunException Exception    -- statement raised an exception
247
248 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)             
249 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
250    = do 
251         maybe_stuff <- hscStmt hsc_env icontext expr
252
253         case maybe_stuff of
254            Nothing -> return (cmstate, CmRunFailed)
255            Just (new_ic, names, hval) -> do
256
257                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
258                 either_hvals <- sandboxIO thing_to_run
259
260                 case either_hvals of
261                     Left e -> do
262                         -- on error, keep the *old* interactive context,
263                         -- so that 'it' is not bound to something
264                         -- that doesn't exist.
265                         return ( cmstate, CmRunException e )
266
267                     Right hvals -> do
268                         -- Get the newly bound things, and bind them.  
269                         -- Don't need to delete any shadowed bindings;
270                         -- the new ones override the old ones. 
271                         extendLinkEnv (zip names hvals)
272                         
273                         return (cmstate{ cm_ic=new_ic }, 
274                                 CmRunOk names)
275
276
277 -- We run the statement in a "sandbox" to protect the rest of the
278 -- system from anything the expression might do.  For now, this
279 -- consists of just wrapping it in an exception handler, but see below
280 -- for another version.
281
282 sandboxIO :: IO a -> IO (Either Exception a)
283 sandboxIO thing = Exception.try thing
284
285 {-
286 -- This version of sandboxIO runs the expression in a completely new
287 -- RTS main thread.  It is disabled for now because ^C exceptions
288 -- won't be delivered to the new thread, instead they'll be delivered
289 -- to the (blocked) GHCi main thread.
290
291 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
292
293 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
294 sandboxIO thing = do
295   st_thing <- newStablePtr (Exception.try thing)
296   alloca $ \ p_st_result -> do
297     stat <- rts_evalStableIO st_thing p_st_result
298     freeStablePtr st_thing
299     if stat == 1
300         then do st_result <- peek p_st_result
301                 result <- deRefStablePtr st_result
302                 freeStablePtr st_result
303                 return (Right result)
304         else do
305                 return (Left (fromIntegral stat))
306
307 foreign import "rts_evalStableIO"  {- safe -}
308   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
309   -- more informative than the C type!
310 -}
311
312 -----------------------------------------------------------------------------
313 -- cmTypeOfExpr: returns a string representing the type of an expression
314
315 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
316 cmTypeOfExpr cmstate expr
317    = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
318
319         case maybe_stuff of
320            Nothing -> return Nothing
321            Just ty -> return (Just res_str)
322              where 
323                 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
324                 unqual  = icPrintUnqual (cm_ic cmstate)
325                 tidy_ty = tidyType emptyTidyEnv ty
326
327
328 -----------------------------------------------------------------------------
329 -- cmKindOfType: returns a string representing the kind of a type
330
331 cmKindOfType :: CmState -> String -> IO (Maybe String)
332 cmKindOfType cmstate str
333    = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
334         case maybe_stuff of
335            Nothing -> return Nothing
336            Just kind -> return (Just res_str)
337              where 
338                 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
339                 unqual  = icPrintUnqual (cm_ic cmstate)
340
341 -----------------------------------------------------------------------------
342 -- cmTypeOfName: returns a string representing the type of a name.
343
344 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
345 cmTypeOfName CmState{ cm_ic=ic } name
346  = do 
347     hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
348     case lookupNameEnv (ic_type_env ic) name of
349         Nothing        -> return Nothing
350         Just (AnId id) -> return (Just str)
351            where
352              unqual = icPrintUnqual ic
353              ty = tidyType emptyTidyEnv (idType id)
354              str = showSDocForUser unqual (ppr ty)
355
356         _ -> panic "cmTypeOfName"
357
358 -----------------------------------------------------------------------------
359 -- cmCompileExpr: compile an expression and deliver an HValue
360
361 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
362 cmCompileExpr cmstate expr
363    = do 
364         maybe_stuff 
365             <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
366                        ("let __cmCompileExpr = "++expr)
367
368         case maybe_stuff of
369            Nothing -> return Nothing
370            Just (new_ic, names, hval) -> do
371
372                         -- Run it!
373                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
374
375                 case (names,hvals) of
376                   ([n],[hv]) -> return (Just hv)
377                   _          -> panic "cmCompileExpr"
378
379 #endif /* GHCI */
380 \end{code}
381
382
383 %************************************************************************
384 %*                                                                      *
385         Loading and unloading
386 %*                                                                      *
387 %************************************************************************
388
389 \begin{code}
390 -----------------------------------------------------------------------------
391 -- Unload the compilation manager's state: everything it knows about the
392 -- current collection of modules in the Home package.
393
394 cmUnload :: CmState -> IO CmState
395 cmUnload state@CmState{ cm_hsc = hsc_env }
396  = do -- Throw away the old home dir cache
397       flushFinderCache
398
399       -- Unload everything the linker knows about
400       cm_unload hsc_env []
401
402       -- Start with a fresh CmState, but keep the PersistentCompilerState
403       return (discardCMInfo state)
404
405 cm_unload hsc_env linkables
406   = case hsc_mode hsc_env of
407         Batch -> return ()
408 #ifdef GHCI
409         Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
410 #else
411         Interactive -> panic "unload: no interpreter"
412 #endif
413     
414
415 -----------------------------------------------------------------------------
416 -- Trace dependency graph
417
418 -- This is a seperate pass so that the caller can back off and keep
419 -- the current state if the downsweep fails.  Typically the caller
420 -- might go     cmDepAnal
421 --              cmUnload
422 --              cmLoadModules
423 -- He wants to do the dependency analysis before the unload, so that
424 -- if the former fails he can use the later
425
426 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
427 cmDepAnal cmstate rootnames
428   = do showPass dflags "Chasing dependencies"
429        when (verbosity dflags >= 1 && gmode == Batch) $
430            hPutStrLn stderr (showSDoc (hcat [
431              text "Chasing modules from: ",
432              hcat (punctuate comma (map text rootnames))]))
433        downsweep rootnames (cm_mg cmstate)
434   where
435     hsc_env = cm_hsc cmstate
436     dflags  = hsc_dflags hsc_env
437     gmode   = hsc_mode hsc_env
438
439 -----------------------------------------------------------------------------
440 -- The real business of the compilation manager: given a system state and
441 -- a module name, try and bring the module up to date, probably changing
442 -- the system state at the same time.
443
444 cmLoadModules :: CmState                -- The HPT may not be as up to date
445               -> ModuleGraph            -- Bang up to date
446               -> IO (CmState,           -- new state
447                      SuccessFlag,       -- was successful
448                      [String])          -- list of modules loaded
449
450 cmLoadModules cmstate1 mg2unsorted
451    = do -- version 1's are the original, before downsweep
452         let hsc_env   = cm_hsc cmstate1
453         let hpt1      = hsc_HPT hsc_env
454         let ghci_mode = hsc_mode   hsc_env -- this never changes
455         let dflags    = hsc_dflags hsc_env -- this never changes
456
457         -- Do the downsweep to reestablish the module graph
458         let verb = verbosity dflags
459
460         -- Find out if we have a Main module
461         mb_main_mod <- readIORef v_MainModIs
462         let 
463             main_mod = mb_main_mod `orElse` "Main"
464             a_root_is_Main 
465                = any ((==main_mod).moduleNameUserString.modSummaryName) 
466                      mg2unsorted
467
468         let mg2unsorted_names = map modSummaryName mg2unsorted
469
470         -- reachable_from follows source as well as normal imports
471         let reachable_from :: ModuleName -> [ModuleName]
472             reachable_from = downwards_closure_of_module mg2unsorted
473  
474         -- should be cycle free; ignores 'import source's
475         let mg2 = topological_sort False mg2unsorted
476         -- ... whereas this takes them into account.  Used for
477         -- backing out partially complete cycles following a failed
478         -- upsweep, and for removing from hpt all the modules
479         -- not in strict downwards closure, during calls to compile.
480         let mg2_with_srcimps = topological_sort True mg2unsorted
481
482         -- Sort out which linkables we wish to keep in the unlinked image.
483         -- See getValidLinkables below for details.
484         (valid_old_linkables, new_linkables)
485             <- getValidLinkables ghci_mode (hptLinkables hpt1)
486                   mg2unsorted_names mg2_with_srcimps
487
488         -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
489
490                 -- Uniq of ModuleName is the same as Module, fortunately...
491         let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
492             hsc_env2 = hsc_env { hsc_HPT = hpt2 }
493
494         -- When (verb >= 2) $
495         --    putStrLn (showSDoc (text "Valid linkables:" 
496         --                       <+> ppr valid_linkables))
497
498         -- Figure out a stable set of modules which can be retained
499         -- the top level envs, to avoid upsweeping them.  Goes to a
500         -- bit of trouble to avoid upsweeping module cycles.
501         --
502         -- Construct a set S of stable modules like this:
503         -- Travel upwards, over the sccified graph.  For each scc
504         -- of modules ms, add ms to S only if:
505         -- 1.  All home imports of ms are either in ms or S
506         -- 2.  A valid old linkable exists for each module in ms
507
508         stable_mods <- preUpsweep valid_old_linkables
509                                   mg2unsorted_names [] mg2_with_srcimps
510
511         let stable_summaries
512                = concatMap (findInSummaries mg2unsorted) stable_mods
513
514             stable_linkables
515                = filter (\m -> linkableModName m `elem` stable_mods) 
516                     valid_old_linkables
517
518         when (verb >= 2) $
519            hPutStrLn stderr (showSDoc (text "Stable modules:" 
520                                <+> sep (map (text.moduleNameUserString) stable_mods)))
521
522         -- Unload any modules which are going to be re-linked this
523         -- time around.
524         cm_unload hsc_env2 stable_linkables
525
526         -- we can now glom together our linkable sets
527         let valid_linkables = valid_old_linkables ++ new_linkables
528
529         -- We could at this point detect cycles which aren't broken by
530         -- a source-import, and complain immediately, but it seems better
531         -- to let upsweep_mods do this, so at least some useful work gets
532         -- done before the upsweep is abandoned.
533         let upsweep_these
534                = filter (\scc -> any (`notElem` stable_mods) 
535                                      (map modSummaryName (flattenSCC scc)))
536                         mg2
537
538         --hPutStrLn stderr "after tsort:\n"
539         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
540
541         -- Because we don't take into account source imports when doing
542         -- the topological sort, there shouldn't be any cycles in mg2.
543         -- If there is, we complain and give up -- the user needs to
544         -- break the cycle using a boot file.
545
546         -- Now do the upsweep, calling compile for each module in
547         -- turn.  Final result is version 3 of everything.
548
549         -- clean up between compilations
550         let cleanup = cleanTempFilesExcept verb 
551                           (ppFilesFromSummaries (flattenSCCs mg2))
552
553         (upsweep_ok, hsc_env3, modsUpswept)
554            <- upsweep_mods hsc_env2 valid_linkables reachable_from 
555                            cleanup upsweep_these
556
557         -- At this point, modsUpswept and newLis should have the same
558         -- length, so there is one new (or old) linkable for each 
559         -- mod which was processed (passed to compile).
560
561         -- Make modsDone be the summaries for each home module now
562         -- available; this should equal the domain of hpt3.
563         -- (NOT STRICTLY TRUE if an interactive session was started
564         --  with some object on disk ???)
565         -- Get in in a roughly top .. bottom order (hence reverse).
566
567         let modsDone = reverse modsUpswept ++ stable_summaries
568
569         -- Try and do linking in some form, depending on whether the
570         -- upsweep was completely or only partially successful.
571
572         if succeeded upsweep_ok
573
574          then 
575            -- Easy; just relink it all.
576            do when (verb >= 2) $ 
577                  hPutStrLn stderr "Upsweep completely successful."
578
579               -- clean up after ourselves
580               cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
581
582               ofile <- readIORef v_Output_file
583               no_hs_main <- readIORef v_NoHsMain
584
585               -- Issue a warning for the confusing case where the user
586               -- said '-o foo' but we're not going to do any linking.
587               -- We attempt linking if either (a) one of the modules is
588               -- called Main, or (b) the user said -no-hs-main, indicating
589               -- that main() is going to come from somewhere else.
590               --
591               let do_linking = a_root_is_Main || no_hs_main
592               when (ghci_mode == Batch && isJust ofile && not do_linking
593                      && verb > 0) $
594                  hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
595
596               -- link everything together
597               linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
598
599               let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
600               cmLoadFinish Succeeded linkresult cmstate3
601
602          else 
603            -- Tricky.  We need to back out the effects of compiling any
604            -- half-done cycles, both so as to clean up the top level envs
605            -- and to avoid telling the interactive linker to link them.
606            do when (verb >= 2) $
607                 hPutStrLn stderr "Upsweep partially successful."
608
609               let modsDone_names
610                      = map modSummaryName modsDone
611               let mods_to_zap_names 
612                      = findPartiallyCompletedCycles modsDone_names 
613                           mg2_with_srcimps
614               let mods_to_keep
615                      = filter ((`notElem` mods_to_zap_names).modSummaryName) 
616                           modsDone
617
618               let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) 
619                                               (hsc_HPT hsc_env3)
620
621               -- Clean up after ourselves
622               cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
623
624               -- Link everything together
625               linkresult <- link ghci_mode dflags False hpt4
626
627               let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
628                                         cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
629               cmLoadFinish Failed linkresult cmstate3
630
631
632 -- Finish up after a cmLoad.
633
634 -- If the link failed, unload everything and return.
635 cmLoadFinish ok Failed cmstate
636   = do cm_unload (cm_hsc cmstate) []
637        return (discardCMInfo cmstate, Failed, [])
638
639 -- Empty the interactive context and set the module context to the topmost
640 -- newly loaded module, or the Prelude if none were loaded.
641 cmLoadFinish ok Succeeded cmstate
642   = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
643            mods_loaded = map (moduleNameUserString.modSummaryName) 
644                              (cm_mg cmstate)
645
646        return (new_cmstate, ok, mods_loaded)
647
648 -- used to fish out the preprocess output files for the purposes of
649 -- cleaning up.  The preprocessed file *might* be the same as the
650 -- source file, but that doesn't do any harm.
651 ppFilesFromSummaries summaries
652   = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
653
654 -----------------------------------------------------------------------------
655 -- getValidLinkables
656
657 -- For each module (or SCC of modules), we take:
658 --
659 --      - an on-disk linkable, if this is the first time around and one
660 --        is available.
661 --
662 --      - the old linkable, otherwise (and if one is available).
663 --
664 -- and we throw away the linkable if it is older than the source file.
665 -- In interactive mode, we also ignore the on-disk linkables unless
666 -- all of the dependents of this SCC also have on-disk linkables (we
667 -- can't have dynamically loaded objects that depend on interpreted
668 -- modules in GHCi).
669 --
670 -- If a module has a valid linkable, then it may be STABLE (see below),
671 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
672 -- compile.
673 --
674 -- ToDo: this pass could be merged with the preUpsweep.
675
676 getValidLinkables
677         :: GhciMode
678         -> [Linkable]           -- old linkables
679         -> [ModuleName]         -- all home modules
680         -> [SCC ModSummary]     -- all modules in the program, dependency order
681         -> IO ( [Linkable],     -- still-valid linkables 
682                 [Linkable]      -- new linkables we just found
683               )
684
685 getValidLinkables mode old_linkables all_home_mods module_graph = do
686   ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
687                 [] module_graph
688   return (partition_it ls [] [])
689  where
690   partition_it []         valid new = (valid,new)
691   partition_it ((l,b):ls) valid new 
692         | b         = partition_it ls valid (l:new)
693         | otherwise = partition_it ls (l:valid) new
694
695
696 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
697    = let 
698           scc             = flattenSCC scc0
699           scc_names       = map modSummaryName scc
700           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
701           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
702                 -- NB. ms_imps, not ms_allimps above.  We don't want to
703                 -- force a module's SOURCE imports to be already compiled for
704                 -- its object linkable to be valid.
705
706           has_object m = 
707                 case findModuleLinkable_maybe (map fst new_linkables) m of
708                     Nothing -> False
709                     Just l  -> isObjectLinkable l
710
711           objects_allowed = mode == Batch || all has_object scc_allhomeimps
712      in do
713
714      new_linkables'
715         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
716
717         -- since an scc can contain only all objects or no objects at all,
718         -- we have to check whether we got all objects or not, and re-do
719         -- the linkable check if not.
720      new_linkables' <- 
721         if objects_allowed
722              && not (all isObjectLinkable (map fst new_linkables'))
723           then foldM (getValidLinkable old_linkables False) [] scc
724           else return new_linkables'
725
726      return (new_linkables ++ new_linkables')
727
728
729 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary 
730         -> IO [(Linkable,Bool)]
731         -- True <=> linkable is new; i.e. freshly discovered on the disk
732         --                                presumably generated 'on the side'
733         --                                by a separate GHC run
734 getValidLinkable old_linkables objects_allowed new_linkables summary 
735         -- 'objects_allowed' says whether we permit this module to
736         -- have a .o-file linkable.  We only permit it if all the
737         -- modules it depends on also have .o files; a .o file can't
738         -- link to a bytecode module
739    = do let mod_name = modSummaryName summary
740
741         maybe_disk_linkable
742           <- if (not objects_allowed)
743                 then return Nothing
744
745                 else findLinkable mod_name (ms_location summary)
746
747         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
748
749             new_linkables' = 
750              case (old_linkable, maybe_disk_linkable) of
751                 (Nothing, Nothing)                      -> []
752
753                 -- new object linkable just appeared
754                 (Nothing, Just l)                       -> up_to_date l True
755
756                 (Just l,  Nothing)
757                   | isObjectLinkable l                  -> []
758                     -- object linkable disappeared!  In case we need to
759                     -- relink the module, disregard the old linkable and
760                     -- just interpret the module from now on.
761                   | otherwise                           -> up_to_date l False
762                     -- old byte code linkable
763
764                 (Just l, Just l') 
765                   | not (isObjectLinkable l)            -> up_to_date l  False
766                     -- if the previous linkable was interpreted, then we
767                     -- ignore a newly compiled version, because the version
768                     -- numbers in the interface file will be out-of-sync with
769                     -- our internal ones.
770                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
771                   | linkableTime l' == linkableTime l   -> up_to_date l  False
772                   | otherwise                           -> []
773                     -- on-disk linkable has been replaced by an older one!
774                     -- again, disregard the previous one.
775
776             up_to_date l b
777                 | linkableTime l < ms_hs_date summary = []
778                 | otherwise = [(l,b)]
779                 -- why '<' rather than '<=' above?  If the filesystem stores
780                 -- times to the nearset second, we may occasionally find that
781                 -- the object & source have the same modification time, 
782                 -- especially if the source was automatically generated
783                 -- and compiled.  Using >= is slightly unsafe, but it matches
784                 -- make's behaviour.
785
786         return (new_linkables' ++ new_linkables)
787
788
789 hptLinkables :: HomePackageTable -> [Linkable]
790 -- Get all the linkables from the home package table, one for each module
791 -- Once the HPT is up to date, these are the ones we should link
792 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
793
794
795 -----------------------------------------------------------------------------
796 -- Do a pre-upsweep without use of "compile", to establish a 
797 -- (downward-closed) set of stable modules for which we won't call compile.
798
799 -- a stable module:
800 --      * has a valid linkable (see getValidLinkables above)
801 --      * depends only on stable modules
802 --      * has an interface in the HPT (interactive mode only)
803
804 preUpsweep :: [Linkable]        -- new valid linkables
805            -> [ModuleName]      -- names of all mods encountered in downsweep
806            -> [ModuleName]      -- accumulating stable modules
807            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
808            -> IO [ModuleName]   -- stable modules
809
810 preUpsweep valid_lis all_home_mods stable []  = return stable
811 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
812    = do let scc = flattenSCC scc0
813             scc_allhomeimps :: [ModuleName]
814             scc_allhomeimps 
815                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
816             all_imports_in_scc_or_stable
817                = all in_stable_or_scc scc_allhomeimps
818             scc_names
819                 = map modSummaryName scc
820             in_stable_or_scc m
821                = m `elem` scc_names || m `elem` stable
822
823             -- now we check for valid linkables: each module in the SCC must 
824             -- have a valid linkable (see getValidLinkables above).
825             has_valid_linkable new_summary
826               = isJust (findModuleLinkable_maybe valid_lis modname)
827                where modname = modSummaryName new_summary
828
829             scc_is_stable = all_imports_in_scc_or_stable
830                           && all has_valid_linkable scc
831
832         if scc_is_stable
833          then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
834          else preUpsweep valid_lis all_home_mods stable sccs
835
836
837 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
838 -- stable (in the sense of preUpsweep), determine if new_summary is itself
839 -- stable, and, if so, in batch mode, return its linkable.
840 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
841 findInSummaries old_summaries mod_name
842    = [s | s <- old_summaries, modSummaryName s == mod_name]
843
844 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
845 findModInSummaries old_summaries mod
846    = case [s | s <- old_summaries, ms_mod s == mod] of
847          [] -> Nothing
848          (s:_) -> Just s
849
850 -- Return (names of) all those in modsDone who are part of a cycle
851 -- as defined by theGraph.
852 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
853 findPartiallyCompletedCycles modsDone theGraph
854    = chew theGraph
855      where
856         chew [] = []
857         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
858         chew ((CyclicSCC vs):rest)
859            = let names_in_this_cycle = nub (map modSummaryName vs)
860                  mods_in_this_cycle  
861                     = nub ([done | done <- modsDone, 
862                                    done `elem` names_in_this_cycle])
863                  chewed_rest = chew rest
864              in 
865              if   notNull mods_in_this_cycle
866                   && length mods_in_this_cycle < length names_in_this_cycle
867              then mods_in_this_cycle ++ chewed_rest
868              else chewed_rest
869
870
871 -- Compile multiple modules, stopping as soon as an error appears.
872 -- There better had not be any cyclic groups here -- we check for them.
873 upsweep_mods :: HscEnv                  -- Includes up-to-date HPT
874              -> [Linkable]              -- Valid linkables
875              -> (ModuleName -> [ModuleName])  -- to construct downward closures
876              -> IO ()                 -- how to clean up unwanted tmp files
877              -> [SCC ModSummary]      -- mods to do (the worklist)
878                                       -- ...... RETURNING ......
879              -> IO (SuccessFlag,
880                     HscEnv,             -- With an updated HPT
881                     [ModSummary])       -- Mods which succeeded
882
883 upsweep_mods hsc_env oldUI reachable_from cleanup
884      []
885    = return (Succeeded, hsc_env, [])
886
887 upsweep_mods hsc_env oldUI reachable_from cleanup
888      ((CyclicSCC ms):_)
889    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
890                           unwords (map (moduleNameUserString.modSummaryName) ms))
891         return (Failed, hsc_env, [])
892
893 upsweep_mods hsc_env oldUI reachable_from cleanup
894      ((AcyclicSCC mod):mods)
895    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
896         --           show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
897
898         (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod 
899                                             (reachable_from (modSummaryName mod))
900
901         cleanup         -- Remove unwanted tmp files between compilations
902
903         if failed ok_flag then
904              return (Failed, hsc_env1, [])
905           else do 
906              (restOK, hsc_env2, modOKs) 
907                        <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
908              return (restOK, hsc_env2, mod:modOKs)
909
910
911 -- Compile a single module.  Always produce a Linkable for it if 
912 -- successful.  If no compilation happened, return the old Linkable.
913 upsweep_mod :: HscEnv
914             -> UnlinkedImage
915             -> ModSummary
916             -> [ModuleName]
917             -> IO (SuccessFlag, 
918                    HscEnv)              -- With updated HPT
919
920 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
921    = do 
922         let this_mod = ms_mod summary1
923             location = ms_location summary1
924             mod_name = moduleName this_mod
925             hpt1     = hsc_HPT hsc_env
926
927         let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
928                              Just mod_info -> Just (hm_iface mod_info)
929                              Nothing       -> Nothing
930
931         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
932             source_unchanged   = isJust maybe_old_linkable
933
934             reachable_only = filter (/= mod_name) reachable_inc_me
935
936            -- In interactive mode, all home modules below us *must* have an
937            -- interface in the HPT.  We never demand-load home interfaces in
938            -- interactive mode.
939             hpt1_strictDC
940                = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
941                  retainInTopLevelEnvs reachable_only hpt1
942             hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
943
944             old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
945
946             have_object 
947                | Just l <- maybe_old_linkable, isObjectLinkable l = True
948                | otherwise = False
949
950         compresult <- compile hsc_env_strictDC this_mod location 
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}