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