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