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