cfea2b88a02a061bc2809b5dde70a708bb2d1566
[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, v_MainModIs )
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         mb_main_mod <- readIORef v_MainModIs
447         let 
448             main_mod = mb_main_mod `orElse` "Main"
449             a_root_is_Main 
450                = any ((==main_mod).moduleNameUserString.modSummaryName) 
451                      mg2unsorted
452
453         let mg2unsorted_names = map modSummaryName mg2unsorted
454
455         -- reachable_from follows source as well as normal imports
456         let reachable_from :: ModuleName -> [ModuleName]
457             reachable_from = downwards_closure_of_module mg2unsorted
458  
459         -- should be cycle free; ignores 'import source's
460         let mg2 = topological_sort False mg2unsorted
461         -- ... whereas this takes them into account.  Used for
462         -- backing out partially complete cycles following a failed
463         -- upsweep, and for removing from hpt all the modules
464         -- not in strict downwards closure, during calls to compile.
465         let mg2_with_srcimps = topological_sort True mg2unsorted
466
467         -- Sort out which linkables we wish to keep in the unlinked image.
468         -- See getValidLinkables below for details.
469         (valid_old_linkables, new_linkables)
470             <- getValidLinkables ghci_mode (hptLinkables hpt1)
471                   mg2unsorted_names mg2_with_srcimps
472
473         -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
474
475                 -- Uniq of ModuleName is the same as Module, fortunately...
476         let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
477             hsc_env2 = hsc_env { hsc_HPT = hpt2 }
478
479         -- When (verb >= 2) $
480         --    putStrLn (showSDoc (text "Valid linkables:" 
481         --                       <+> ppr valid_linkables))
482
483         -- Figure out a stable set of modules which can be retained
484         -- the top level envs, to avoid upsweeping them.  Goes to a
485         -- bit of trouble to avoid upsweeping module cycles.
486         --
487         -- Construct a set S of stable modules like this:
488         -- Travel upwards, over the sccified graph.  For each scc
489         -- of modules ms, add ms to S only if:
490         -- 1.  All home imports of ms are either in ms or S
491         -- 2.  A valid old linkable exists for each module in ms
492
493         stable_mods <- preUpsweep valid_old_linkables
494                                   mg2unsorted_names [] mg2_with_srcimps
495
496         let stable_summaries
497                = concatMap (findInSummaries mg2unsorted) stable_mods
498
499             stable_linkables
500                = filter (\m -> linkableModName m `elem` stable_mods) 
501                     valid_old_linkables
502
503         when (verb >= 2) $
504            hPutStrLn stderr (showSDoc (text "Stable modules:" 
505                                <+> sep (map (text.moduleNameUserString) stable_mods)))
506
507         -- Unload any modules which are going to be re-linked this
508         -- time around.
509         cm_unload hsc_env2 stable_linkables
510
511         -- we can now glom together our linkable sets
512         let valid_linkables = valid_old_linkables ++ new_linkables
513
514         -- We could at this point detect cycles which aren't broken by
515         -- a source-import, and complain immediately, but it seems better
516         -- to let upsweep_mods do this, so at least some useful work gets
517         -- done before the upsweep is abandoned.
518         let upsweep_these
519                = filter (\scc -> any (`notElem` stable_mods) 
520                                      (map modSummaryName (flattenSCC scc)))
521                         mg2
522
523         --hPutStrLn stderr "after tsort:\n"
524         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
525
526         -- Because we don't take into account source imports when doing
527         -- the topological sort, there shouldn't be any cycles in mg2.
528         -- If there is, we complain and give up -- the user needs to
529         -- break the cycle using a boot file.
530
531         -- Now do the upsweep, calling compile for each module in
532         -- turn.  Final result is version 3 of everything.
533
534         -- clean up between compilations
535         let cleanup = cleanTempFilesExcept verb 
536                           (ppFilesFromSummaries (flattenSCCs mg2))
537
538         (upsweep_ok, hsc_env3, modsUpswept)
539            <- upsweep_mods hsc_env2 valid_linkables reachable_from 
540                            cleanup upsweep_these
541
542         -- At this point, modsUpswept and newLis should have the same
543         -- length, so there is one new (or old) linkable for each 
544         -- mod which was processed (passed to compile).
545
546         -- Make modsDone be the summaries for each home module now
547         -- available; this should equal the domain of hpt3.
548         -- (NOT STRICTLY TRUE if an interactive session was started
549         --  with some object on disk ???)
550         -- Get in in a roughly top .. bottom order (hence reverse).
551
552         let modsDone = reverse modsUpswept ++ stable_summaries
553
554         -- Try and do linking in some form, depending on whether the
555         -- upsweep was completely or only partially successful.
556
557         if succeeded upsweep_ok
558
559          then 
560            -- Easy; just relink it all.
561            do when (verb >= 2) $ 
562                  hPutStrLn stderr "Upsweep completely successful."
563
564               -- clean up after ourselves
565               cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
566
567               ofile <- readIORef v_Output_file
568               no_hs_main <- readIORef v_NoHsMain
569
570               -- Issue a warning for the confusing case where the user
571               -- said '-o foo' but we're not going to do any linking.
572               -- We attempt linking if either (a) one of the modules is
573               -- called Main, or (b) the user said -no-hs-main, indicating
574               -- that main() is going to come from somewhere else.
575               --
576               let do_linking = a_root_is_Main || no_hs_main
577               when (ghci_mode == Batch && isJust ofile && not do_linking
578                      && verb > 0) $
579                  hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
580
581               -- link everything together
582               linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
583
584               let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
585               cmLoadFinish Succeeded linkresult cmstate3
586
587          else 
588            -- Tricky.  We need to back out the effects of compiling any
589            -- half-done cycles, both so as to clean up the top level envs
590            -- and to avoid telling the interactive linker to link them.
591            do when (verb >= 2) $
592                 hPutStrLn stderr "Upsweep partially successful."
593
594               let modsDone_names
595                      = map modSummaryName modsDone
596               let mods_to_zap_names 
597                      = findPartiallyCompletedCycles modsDone_names 
598                           mg2_with_srcimps
599               let mods_to_keep
600                      = filter ((`notElem` mods_to_zap_names).modSummaryName) 
601                           modsDone
602
603               let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) 
604                                               (hsc_HPT hsc_env3)
605
606               -- Clean up after ourselves
607               cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
608
609               -- Link everything together
610               linkresult <- link ghci_mode dflags False hpt4
611
612               let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
613                                         cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
614               cmLoadFinish Failed linkresult cmstate3
615
616
617 -- Finish up after a cmLoad.
618
619 -- If the link failed, unload everything and return.
620 cmLoadFinish ok Failed cmstate
621   = do cm_unload (cm_hsc cmstate) []
622        return (discardCMInfo cmstate, Failed, [])
623
624 -- Empty the interactive context and set the module context to the topmost
625 -- newly loaded module, or the Prelude if none were loaded.
626 cmLoadFinish ok Succeeded cmstate
627   = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
628            mods_loaded = map (moduleNameUserString.modSummaryName) 
629                              (cm_mg cmstate)
630
631        return (new_cmstate, ok, mods_loaded)
632
633 -- used to fish out the preprocess output files for the purposes of
634 -- cleaning up.  The preprocessed file *might* be the same as the
635 -- source file, but that doesn't do any harm.
636 ppFilesFromSummaries summaries
637   = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
638
639 -----------------------------------------------------------------------------
640 -- getValidLinkables
641
642 -- For each module (or SCC of modules), we take:
643 --
644 --      - an on-disk linkable, if this is the first time around and one
645 --        is available.
646 --
647 --      - the old linkable, otherwise (and if one is available).
648 --
649 -- and we throw away the linkable if it is older than the source file.
650 -- In interactive mode, we also ignore the on-disk linkables unless
651 -- all of the dependents of this SCC also have on-disk linkables (we
652 -- can't have dynamically loaded objects that depend on interpreted
653 -- modules in GHCi).
654 --
655 -- If a module has a valid linkable, then it may be STABLE (see below),
656 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
657 -- compile.
658 --
659 -- ToDo: this pass could be merged with the preUpsweep.
660
661 getValidLinkables
662         :: GhciMode
663         -> [Linkable]           -- old linkables
664         -> [ModuleName]         -- all home modules
665         -> [SCC ModSummary]     -- all modules in the program, dependency order
666         -> IO ( [Linkable],     -- still-valid linkables 
667                 [Linkable]      -- new linkables we just found
668               )
669
670 getValidLinkables mode old_linkables all_home_mods module_graph = do
671   ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods) 
672                 [] module_graph
673   return (partition_it ls [] [])
674  where
675   partition_it []         valid new = (valid,new)
676   partition_it ((l,b):ls) valid new 
677         | b         = partition_it ls valid (l:new)
678         | otherwise = partition_it ls (l:valid) new
679
680
681 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
682    = let 
683           scc             = flattenSCC scc0
684           scc_names       = map modSummaryName scc
685           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
686           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
687                 -- NB. ms_imps, not ms_allimps above.  We don't want to
688                 -- force a module's SOURCE imports to be already compiled for
689                 -- its object linkable to be valid.
690
691           has_object m = 
692                 case findModuleLinkable_maybe (map fst new_linkables) m of
693                     Nothing -> False
694                     Just l  -> isObjectLinkable l
695
696           objects_allowed = mode == Batch || all has_object scc_allhomeimps
697      in do
698
699      new_linkables'
700         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
701
702         -- since an scc can contain only all objects or no objects at all,
703         -- we have to check whether we got all objects or not, and re-do
704         -- the linkable check if not.
705      new_linkables' <- 
706         if objects_allowed
707              && not (all isObjectLinkable (map fst new_linkables'))
708           then foldM (getValidLinkable old_linkables False) [] scc
709           else return new_linkables'
710
711      return (new_linkables ++ new_linkables')
712
713
714 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary 
715         -> IO [(Linkable,Bool)]
716         -- True <=> linkable is new; i.e. freshly discovered on the disk
717         --                                presumably generated 'on the side'
718         --                                by a separate GHC run
719 getValidLinkable old_linkables objects_allowed new_linkables summary 
720         -- 'objects_allowed' says whether we permit this module to
721         -- have a .o-file linkable.  We only permit it if all the
722         -- modules it depends on also have .o files; a .o file can't
723         -- link to a bytecode module
724    = do let mod_name = modSummaryName summary
725
726         maybe_disk_linkable
727           <- if (not objects_allowed)
728                 then return Nothing
729
730                 else findLinkable mod_name (ms_location summary)
731
732         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
733
734             new_linkables' = 
735              case (old_linkable, maybe_disk_linkable) of
736                 (Nothing, Nothing)                      -> []
737
738                 -- new object linkable just appeared
739                 (Nothing, Just l)                       -> up_to_date l True
740
741                 (Just l,  Nothing)
742                   | isObjectLinkable l                  -> []
743                     -- object linkable disappeared!  In case we need to
744                     -- relink the module, disregard the old linkable and
745                     -- just interpret the module from now on.
746                   | otherwise                           -> up_to_date l False
747                     -- old byte code linkable
748
749                 (Just l, Just l') 
750                   | not (isObjectLinkable l)            -> up_to_date l  False
751                     -- if the previous linkable was interpreted, then we
752                     -- ignore a newly compiled version, because the version
753                     -- numbers in the interface file will be out-of-sync with
754                     -- our internal ones.
755                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
756                   | linkableTime l' == linkableTime l   -> up_to_date l  False
757                   | otherwise                           -> []
758                     -- on-disk linkable has been replaced by an older one!
759                     -- again, disregard the previous one.
760
761             up_to_date l b
762                 | linkableTime l < ms_hs_date summary = []
763                 | otherwise = [(l,b)]
764                 -- why '<' rather than '<=' above?  If the filesystem stores
765                 -- times to the nearset second, we may occasionally find that
766                 -- the object & source have the same modification time, 
767                 -- especially if the source was automatically generated
768                 -- and compiled.  Using >= is slightly unsafe, but it matches
769                 -- make's behaviour.
770
771         return (new_linkables' ++ new_linkables)
772
773
774 hptLinkables :: HomePackageTable -> [Linkable]
775 -- Get all the linkables from the home package table, one for each module
776 -- Once the HPT is up to date, these are the ones we should link
777 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
778
779
780 -----------------------------------------------------------------------------
781 -- Do a pre-upsweep without use of "compile", to establish a 
782 -- (downward-closed) set of stable modules for which we won't call compile.
783
784 -- a stable module:
785 --      * has a valid linkable (see getValidLinkables above)
786 --      * depends only on stable modules
787 --      * has an interface in the HPT (interactive mode only)
788
789 preUpsweep :: [Linkable]        -- new valid linkables
790            -> [ModuleName]      -- names of all mods encountered in downsweep
791            -> [ModuleName]      -- accumulating stable modules
792            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
793            -> IO [ModuleName]   -- stable modules
794
795 preUpsweep valid_lis all_home_mods stable []  = return stable
796 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
797    = do let scc = flattenSCC scc0
798             scc_allhomeimps :: [ModuleName]
799             scc_allhomeimps 
800                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
801             all_imports_in_scc_or_stable
802                = all in_stable_or_scc scc_allhomeimps
803             scc_names
804                 = map modSummaryName scc
805             in_stable_or_scc m
806                = m `elem` scc_names || m `elem` stable
807
808             -- now we check for valid linkables: each module in the SCC must 
809             -- have a valid linkable (see getValidLinkables above).
810             has_valid_linkable new_summary
811               = isJust (findModuleLinkable_maybe valid_lis modname)
812                where modname = modSummaryName new_summary
813
814             scc_is_stable = all_imports_in_scc_or_stable
815                           && all has_valid_linkable scc
816
817         if scc_is_stable
818          then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
819          else preUpsweep valid_lis all_home_mods stable sccs
820
821
822 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
823 -- stable (in the sense of preUpsweep), determine if new_summary is itself
824 -- stable, and, if so, in batch mode, return its linkable.
825 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
826 findInSummaries old_summaries mod_name
827    = [s | s <- old_summaries, modSummaryName s == mod_name]
828
829 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
830 findModInSummaries old_summaries mod
831    = case [s | s <- old_summaries, ms_mod s == mod] of
832          [] -> Nothing
833          (s:_) -> Just s
834
835 -- Return (names of) all those in modsDone who are part of a cycle
836 -- as defined by theGraph.
837 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
838 findPartiallyCompletedCycles modsDone theGraph
839    = chew theGraph
840      where
841         chew [] = []
842         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
843         chew ((CyclicSCC vs):rest)
844            = let names_in_this_cycle = nub (map modSummaryName vs)
845                  mods_in_this_cycle  
846                     = nub ([done | done <- modsDone, 
847                                    done `elem` names_in_this_cycle])
848                  chewed_rest = chew rest
849              in 
850              if   notNull mods_in_this_cycle
851                   && length mods_in_this_cycle < length names_in_this_cycle
852              then mods_in_this_cycle ++ chewed_rest
853              else chewed_rest
854
855
856 -- Compile multiple modules, stopping as soon as an error appears.
857 -- There better had not be any cyclic groups here -- we check for them.
858 upsweep_mods :: HscEnv                  -- Includes up-to-date HPT
859              -> [Linkable]              -- Valid linkables
860              -> (ModuleName -> [ModuleName])  -- to construct downward closures
861              -> IO ()                 -- how to clean up unwanted tmp files
862              -> [SCC ModSummary]      -- mods to do (the worklist)
863                                       -- ...... RETURNING ......
864              -> IO (SuccessFlag,
865                     HscEnv,             -- With an updated HPT
866                     [ModSummary])       -- Mods which succeeded
867
868 upsweep_mods hsc_env oldUI reachable_from cleanup
869      []
870    = return (Succeeded, hsc_env, [])
871
872 upsweep_mods hsc_env oldUI reachable_from cleanup
873      ((CyclicSCC ms):_)
874    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
875                           unwords (map (moduleNameUserString.modSummaryName) ms))
876         return (Failed, hsc_env, [])
877
878 upsweep_mods hsc_env oldUI reachable_from cleanup
879      ((AcyclicSCC mod):mods)
880    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
881         --           show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
882
883         (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod 
884                                             (reachable_from (modSummaryName mod))
885
886         cleanup         -- Remove unwanted tmp files between compilations
887
888         if failed ok_flag then
889              return (Failed, hsc_env1, [])
890           else do 
891              (restOK, hsc_env2, modOKs) 
892                        <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
893              return (restOK, hsc_env2, mod:modOKs)
894
895
896 -- Compile a single module.  Always produce a Linkable for it if 
897 -- successful.  If no compilation happened, return the old Linkable.
898 upsweep_mod :: HscEnv
899             -> UnlinkedImage
900             -> ModSummary
901             -> [ModuleName]
902             -> IO (SuccessFlag, 
903                    HscEnv)              -- With updated HPT
904
905 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
906    = do 
907         let this_mod = ms_mod summary1
908             location = ms_location summary1
909             mod_name = moduleName this_mod
910             hpt1     = hsc_HPT hsc_env
911
912         let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
913                              Just mod_info -> Just (hm_iface mod_info)
914                              Nothing       -> Nothing
915
916         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
917             source_unchanged   = isJust maybe_old_linkable
918
919             reachable_only = filter (/= mod_name) reachable_inc_me
920
921            -- In interactive mode, all home modules below us *must* have an
922            -- interface in the HPT.  We never demand-load home interfaces in
923            -- interactive mode.
924             hpt1_strictDC
925                = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
926                  retainInTopLevelEnvs reachable_only hpt1
927             hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
928
929             old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
930
931             have_object 
932                | Just l <- maybe_old_linkable, isObjectLinkable l = True
933                | otherwise = False
934
935         compresult <- compile hsc_env_strictDC this_mod location 
936                               source_unchanged have_object mb_old_iface
937
938         case compresult of
939
940            -- Compilation "succeeded", and may or may not have returned a new
941            -- linkable (depending on whether compilation was actually performed
942            -- or not).
943            CompOK new_details new_globals new_iface maybe_new_linkable
944               -> do let 
945                         new_linkable = maybe_new_linkable `orElse` old_linkable
946                         new_info = HomeModInfo { hm_iface = new_iface,
947                                                  hm_globals = new_globals,
948                                                  hm_details = new_details,
949                                                  hm_linkable = new_linkable }
950                         hpt2      = extendModuleEnv hpt1 this_mod new_info
951
952                     return (Succeeded, hsc_env { hsc_HPT = hpt2 })
953
954            -- Compilation failed.  Compile may still have updated the PCS, tho.
955            CompErrs -> return (Failed, hsc_env)
956
957 -- Filter modules in the HPT
958 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
959 retainInTopLevelEnvs keep_these hpt
960    = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
961    where
962      maybeLookupUFM ufm u  = case lookupUFM ufm u of 
963                                 Nothing  -> []
964                                 Just val -> [(u, val)] 
965
966 -- Needed to clean up HPT so that we don't get duplicates in inst env
967 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
968 downwards_closure_of_module summaries root
969    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
970          toEdge summ = (modSummaryName summ, 
971                         filter (`elem` all_mods) (ms_allimps summ))
972
973          all_mods = map modSummaryName summaries
974
975          res = simple_transitive_closure (map toEdge summaries) [root]
976      in
977 --         trace (showSDoc (text "DC of mod" <+> ppr root
978 --                          <+> text "=" <+> ppr res)) $
979          res
980
981 -- Calculate transitive closures from a set of roots given an adjacency list
982 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
983 simple_transitive_closure graph set 
984    = let set2      = nub (concatMap dsts set ++ set)
985          dsts node = fromMaybe [] (lookup node graph)
986      in
987          if   length set == length set2
988          then set
989          else simple_transitive_closure graph set2
990
991
992 -- Calculate SCCs of the module graph, with or without taking into
993 -- account source imports.
994 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
995 topological_sort include_source_imports summaries
996    = let 
997          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
998          toEdge summ
999              = (summ, modSummaryName summ, 
1000                       (if include_source_imports 
1001                        then ms_srcimps summ else []) ++ ms_imps summ)
1002         
1003          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1004          mash_edge (summ, m, m_imports)
1005             = case lookup m key_map of
1006                  Nothing -> panic "reverse_topological_sort"
1007                  Just mk -> (summ, mk, 
1008                                 -- ignore imports not from the home package
1009                              mapCatMaybes (flip lookup key_map) m_imports)
1010
1011          edges     = map toEdge summaries
1012          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1013          scc_input = map mash_edge edges
1014          sccs      = stronglyConnComp scc_input
1015      in
1016          sccs
1017
1018
1019 -----------------------------------------------------------------------------
1020 -- Downsweep (dependency analysis)
1021
1022 -- Chase downwards from the specified root set, returning summaries
1023 -- for all home modules encountered.  Only follow source-import
1024 -- links.
1025
1026 -- We pass in the previous collection of summaries, which is used as a
1027 -- cache to avoid recalculating a module summary if the source is
1028 -- unchanged.
1029
1030 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1031 downsweep roots old_summaries
1032    = do rootSummaries <- mapM getRootSummary roots
1033         checkDuplicates rootSummaries
1034         all_summaries
1035            <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1036                                             (ms_imps m)) rootSummaries))
1037                 (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
1038                                           let mod = ms_mod s, isHomeModule mod 
1039                              ])
1040         return all_summaries
1041      where
1042         getRootSummary :: FilePath -> IO ModSummary
1043         getRootSummary file
1044            | isHaskellSrcFilename file
1045            = do exists <- doesFileExist file
1046                 if exists then summariseFile file else do
1047                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
1048            | otherwise
1049            = do exists <- doesFileExist hs_file
1050                 if exists then summariseFile hs_file else do
1051                 exists <- doesFileExist lhs_file
1052                 if exists then summariseFile lhs_file else do
1053                 let mod_name = mkModuleName file
1054                 maybe_summary <- getSummary (file, mod_name)
1055                 case maybe_summary of
1056                    Nothing -> packageModErr mod_name
1057                    Just s  -> return s
1058            where 
1059                  hs_file = file ++ ".hs"
1060                  lhs_file = file ++ ".lhs"
1061
1062         -- In a root module, the filename is allowed to diverge from the module
1063         -- name, so we have to check that there aren't multiple root files
1064         -- defining the same module (otherwise the duplicates will be silently
1065         -- ignored, leading to confusing behaviour).
1066         checkDuplicates :: [ModSummary] -> IO ()
1067         checkDuplicates summaries = mapM_ check summaries
1068           where check summ = 
1069                   case dups of
1070                         []     -> return ()
1071                         [_one] -> return ()
1072                         many   -> multiRootsErr modl many
1073                    where modl = ms_mod summ
1074                          dups = 
1075                            [ fromJust (ml_hs_file (ms_location summ'))
1076                            | summ' <- summaries, ms_mod summ' == modl ]
1077
1078         getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1079         getSummary (currentMod,nm)
1080            = do found <- findModule nm
1081                 case found of
1082                    Right (mod, location) -> do
1083                         let old_summary = findModInSummaries old_summaries mod
1084                         summarise mod location old_summary
1085
1086                    Left files -> do
1087                         dflags <- getDynFlags
1088                         throwDyn (noModError dflags currentMod nm files)
1089
1090         -- loop invariant: env doesn't contain package modules
1091         loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1092         loop [] env = return (moduleEnvElts env)
1093         loop imps env
1094            = do -- imports for modules we don't already have
1095                 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1096
1097                 -- summarise them
1098                 needed_summaries <- mapM getSummary needed_imps
1099
1100                 -- get just the "home" modules
1101                 let new_home_summaries = [ s | Just s <- needed_summaries ]
1102
1103                 -- loop, checking the new imports
1104                 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1105                                                        (ms_imps m)) new_home_summaries)
1106                 loop new_imps (extendModuleEnvList env 
1107                                 [ (ms_mod s, s) | s <- new_home_summaries ])
1108
1109 -- ToDo: we don't have a proper line number for this error
1110 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1111   hang (text loc <> colon) 4 $
1112     (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1113   ))
1114   where
1115    extra
1116     | verbosity dflags < 3 =
1117         text "(use -v to see a list of the files searched for)"
1118     | otherwise =
1119         hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1120
1121 -----------------------------------------------------------------------------
1122 -- Summarising modules
1123
1124 -- We have two types of summarisation:
1125 --
1126 --    * Summarise a file.  This is used for the root module(s) passed to
1127 --      cmLoadModules.  The file is read, and used to determine the root
1128 --      module name.  The module name may differ from the filename.
1129 --
1130 --    * Summarise a module.  We are given a module name, and must provide
1131 --      a summary.  The finder is used to locate the file in which the module
1132 --      resides.
1133
1134 summariseFile :: FilePath -> IO ModSummary
1135 summariseFile file
1136    = do hspp_fn <- preprocess file
1137         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1138
1139         let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1140             the_imps = filter (/= gHC_PRIM_Name) imps
1141
1142         (mod, location) <- mkHomeModLocation mod_name file
1143
1144         src_timestamp
1145            <- case ml_hs_file location of 
1146                  Nothing     -> noHsFileErr mod_name
1147                  Just src_fn -> getModificationTime src_fn
1148
1149         return (ModSummary { ms_mod = mod, 
1150                              ms_location = location{ml_hspp_file=Just hspp_fn},
1151                              ms_srcimps = srcimps, ms_imps = the_imps,
1152                              ms_hs_date = src_timestamp })
1153
1154 -- Summarise a module, and pick up source and timestamp.
1155 summarise :: Module -> ModLocation -> Maybe ModSummary
1156          -> IO (Maybe ModSummary)
1157 summarise mod location old_summary
1158    | not (isHomeModule mod) = return Nothing
1159    | otherwise
1160    = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1161
1162         case ml_hs_file location of {
1163            Nothing -> noHsFileErr mod;
1164            Just src_fn -> do
1165
1166         src_timestamp <- getModificationTime src_fn
1167
1168         -- return the cached summary if the source didn't change
1169         case old_summary of {
1170            Just s | ms_hs_date s == src_timestamp -> return (Just s);
1171            _ -> do
1172
1173         hspp_fn <- preprocess hs_fn
1174         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1175         let
1176              -- GHC.Prim doesn't exist physically, so don't go looking for it.
1177            the_imps = filter (/= gHC_PRIM_Name) imps
1178
1179         when (mod_name /= moduleName mod) $
1180                 throwDyn (ProgramError 
1181                    (showSDoc (text hs_fn
1182                               <>  text ": file name does not match module name"
1183                               <+> quotes (ppr (moduleName mod)))))
1184
1185         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1186                                  srcimps the_imps src_timestamp))
1187         }
1188       }
1189
1190
1191 noHsFileErr mod
1192   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1193
1194 packageModErr mod
1195   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1196                                    quotes (ppr mod) <+>
1197                                    text "is a package module")))
1198
1199 multiRootsErr mod files
1200   = throwDyn (ProgramError (showSDoc (
1201         text "module" <+> quotes (ppr mod) <+> 
1202         text "is defined in multiple files:" <+>
1203         sep (map text files))))
1204 \end{code}
1205
1206
1207 %************************************************************************
1208 %*                                                                      *
1209                 The ModSummary Type
1210 %*                                                                      *
1211 %************************************************************************
1212
1213 \begin{code}
1214 -- The ModLocation contains both the original source filename and the
1215 -- filename of the cleaned-up source file after all preprocessing has been
1216 -- done.  The point is that the summariser will have to cpp/unlit/whatever
1217 -- all files anyway, and there's no point in doing this twice -- just 
1218 -- park the result in a temp file, put the name of it in the location,
1219 -- and let @compile@ read from that file on the way back up.
1220
1221
1222 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
1223
1224 emptyMG :: ModuleGraph
1225 emptyMG = []
1226
1227 data ModSummary
1228    = ModSummary {
1229         ms_mod      :: Module,                  -- name, package
1230         ms_location :: ModLocation,             -- location
1231         ms_srcimps  :: [ModuleName],            -- source imports
1232         ms_imps     :: [ModuleName],            -- non-source imports
1233         ms_hs_date  :: ClockTime                -- timestamp of summarised file
1234      }
1235
1236 instance Outputable ModSummary where
1237    ppr ms
1238       = sep [text "ModSummary {",
1239              nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1240                           text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1241                           text "ms_imps =" <+> ppr (ms_imps ms),
1242                           text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1243              char '}'
1244             ]
1245
1246 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1247
1248 modSummaryName :: ModSummary -> ModuleName
1249 modSummaryName = moduleName . ms_mod
1250 \end{code}