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