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