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