[project @ 2003-11-05 11:39:38 by simonpj]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2002
3 %
4 % The Compilation Manager
5 %
6 \begin{code}
7 {-# OPTIONS -fvia-C #-}
8 module CompManager ( 
9     ModuleGraph, ModSummary(..),
10
11     CmState,            -- abstract
12
13     cmInit,        -- :: GhciMode -> DynFlags -> IO CmState
14
15     cmDepAnal,     -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
16
17     cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18                    --    -> IO (CmState, Bool, [String])
19
20     cmUnload,      -- :: CmState -> DynFlags -> IO CmState
21
22 #ifdef GHCI
23     cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24
25     cmSetContext,  -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26     cmGetContext,  -- :: CmState -> IO ([String],[String])
27
28     cmInfoThing,   -- :: CmState -> DynFlags -> String
29                    --   -> IO (CmState, [(TyThing,Fixity)])
30
31     cmBrowseModule, -- :: CmState -> IO [TyThing]
32
33     CmRunResult(..),
34     cmRunStmt,     -- :: CmState -> DynFlags -> String
35                    --    -> IO (CmState, CmRunResult)
36
37     cmTypeOfExpr,  -- :: CmState -> DynFlags -> String
38                    --   -> IO (CmState, Maybe String)
39
40     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     findModuleLinkable_maybe,   -- Exported to InteractiveUI
48
49     cmSetDFlags,
50     cmGetBindings,      -- :: CmState -> [TyThing]
51     cmGetPrintUnqual,   -- :: CmState -> PrintUnqualified
52
53     sandboxIO           -- Should be somewhere else
54 #endif
55   )
56 where
57
58 #include "HsVersions.h"
59
60 import DriverPipeline   ( CompResult(..), preprocess, compile, link )
61 import HscMain          ( newHscEnv )
62 import DriverState      ( v_Output_file, v_NoHsMain )
63 import DriverPhases
64 import Finder
65 import HscTypes
66 import PrelNames        ( gHC_PRIM_Name )
67 import Module           ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
68                           ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
69                           extendModuleEnvList, extendModuleEnv,
70                           moduleNameUserString,
71                           ModLocation(..) )
72 import RdrName          ( GlobalRdrEnv, plusGlobalRdrEnv )
73 import GetImports
74 import UniqFM
75 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
76 import ErrUtils         ( showPass )
77 import SysTools         ( cleanTempFilesExcept )
78 import BasicTypes       ( SuccessFlag(..), succeeded, failed )
79 import Util
80 import Outputable
81 import Panic
82 import CmdLineOpts      ( DynFlags(..), getDynFlags )
83 import Maybes           ( expectJust, orElse, mapCatMaybes )
84
85 import DATA_IOREF       ( readIORef )
86
87 #ifdef GHCI
88 import HscMain          ( hscThing, hscStmt, hscTcExpr )
89 import TcRnDriver       ( mkExportEnv, getModuleContents )
90 import IfaceSyn         ( IfaceDecl )
91 import Name             ( Name )
92 import NameEnv
93 import Id               ( idType )
94 import Type             ( tidyType )
95 import VarEnv           ( emptyTidyEnv )
96 import BasicTypes       ( Fixity )
97 import Linker           ( HValue, unload, extendLinkEnv )
98 import GHC.Exts         ( unsafeCoerce# )
99 import Foreign
100 import Control.Exception as Exception ( Exception, try )
101 #endif
102
103 import EXCEPTION        ( throwDyn )
104
105 -- std
106 import Directory        ( getModificationTime, doesFileExist )
107 import IO
108 import Monad
109 import List             ( nub )
110 import Maybe
111 import Time             ( ClockTime )
112 \end{code}
113
114
115 \begin{code}
116 -- Persistent state for the entire system
117 data CmState
118    = CmState {
119         cm_hsc :: HscEnv,               -- Includes the home-package table
120         cm_mg  :: ModuleGraph,          -- The module graph
121         cm_ic  :: InteractiveContext    -- Command-line binding info
122      }
123
124 #ifdef GHCI
125 cmGetModInfo     cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
126 cmGetBindings    cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
127 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
128 cmHPT            cmstate = hsc_HPT (cm_hsc cmstate)
129 #endif
130
131 cmInit :: GhciMode -> DynFlags -> IO CmState
132 cmInit ghci_mode dflags
133    = do { hsc_env <- newHscEnv ghci_mode dflags
134         ; return (CmState { cm_hsc = hsc_env,
135                             cm_mg  = emptyMG, 
136                             cm_ic  = emptyInteractiveContext })}
137
138 discardCMInfo :: CmState -> CmState
139 -- Forget the compilation manager's state, including the home package table
140 -- but retain the persistent info in HscEnv
141 discardCMInfo cm_state
142   = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
143                cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
144
145 -------------------------------------------------------------------
146 --                      The unlinked image
147 -- 
148 -- The compilation manager keeps a list of compiled, but as-yet unlinked
149 -- binaries (byte code or object code).  Even when it links bytecode
150 -- it keeps the unlinked version so it can re-link it later without
151 -- recompiling.
152
153 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
154
155 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
156 findModuleLinkable_maybe lis mod
157    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
158         []   -> Nothing
159         [li] -> Just li
160         many -> pprPanic "findModuleLinkable" (ppr mod)
161 \end{code}
162
163
164 %************************************************************************
165 %*                                                                      *
166         GHCI stuff
167 %*                                                                      *
168 %************************************************************************
169
170 \begin{code}
171 #ifdef GHCI
172 -----------------------------------------------------------------------------
173 -- Setting the context doesn't throw away any bindings; the bindings
174 -- we've built up in the InteractiveContext simply move to the new
175 -- module.  They always shadow anything in scope in the current context.
176
177 cmSetContext
178         :: CmState
179         -> [String]             -- take the top-level scopes of these modules
180         -> [String]             -- and the just the exports from these
181         -> IO CmState
182 cmSetContext cmstate toplevs exports = do 
183   let old_ic  = cm_ic cmstate
184       hsc_env = cm_hsc cmstate
185       hpt     = hsc_HPT hsc_env
186
187   export_env  <- mkExportEnv hsc_env (map mkModuleName exports)
188   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
189
190   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
191   return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
192                                    ic_exports      = exports,
193                                    ic_rn_gbl_env   = all_env } }
194
195 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
196 mkTopLevEnv hpt mod
197  = case lookupModuleEnvByName hpt (mkModuleName mod) of
198       Nothing      -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
199       Just details -> case hm_globals details of
200                         Nothing  -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
201                         Just env -> return env
202
203 cmGetContext :: CmState -> IO ([String],[String])
204 cmGetContext CmState{cm_ic=ic} = 
205   return (ic_toplev_scope ic, ic_exports ic)
206
207 cmModuleIsInterpreted :: CmState -> String -> IO Bool
208 cmModuleIsInterpreted cmstate str 
209  = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
210       Just details       -> return (isJust (hm_globals details))
211       _not_a_home_module -> return False
212
213 -----------------------------------------------------------------------------
214 cmSetDFlags :: CmState -> DynFlags -> CmState
215 cmSetDFlags cm_state dflags 
216   = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
217
218 -----------------------------------------------------------------------------
219 -- cmInfoThing: convert a String to a TyThing
220
221 -- A string may refer to more than one TyThing (eg. a constructor,
222 -- and type constructor), so we return a list of all the possible TyThings.
223
224 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity)]
225 cmInfoThing cmstate id
226    = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
227
228 -- ---------------------------------------------------------------------------
229 -- cmBrowseModule: get all the TyThings defined in a module
230
231 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
232 cmBrowseModule cmstate str exports_only
233   = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate) 
234                                        (mkModuleName str) exports_only
235        ; case mb_decls of
236            Nothing -> return []         -- An error of some kind
237            Just ds -> return ds
238    }
239
240
241 -----------------------------------------------------------------------------
242 -- cmRunStmt:  Run a statement/expr.
243
244 data CmRunResult
245   = CmRunOk [Name]              -- names bound by this evaluation
246   | CmRunFailed 
247   | CmRunException Exception    -- statement raised an exception
248
249 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)             
250 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
251    = do 
252         maybe_stuff <- hscStmt hsc_env icontext expr
253
254         case maybe_stuff of
255            Nothing -> return (cmstate, CmRunFailed)
256            Just (new_ic, names, hval) -> do
257
258                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
259                 either_hvals <- sandboxIO thing_to_run
260
261                 case either_hvals of
262                     Left e -> do
263                         -- on error, keep the *old* interactive context,
264                         -- so that 'it' is not bound to something
265                         -- that doesn't exist.
266                         return ( cmstate, CmRunException e )
267
268                     Right hvals -> do
269                         -- Get the newly bound things, and bind them.  
270                         -- Don't need to delete any shadowed bindings;
271                         -- the new ones override the old ones. 
272                         extendLinkEnv (zip names hvals)
273                         
274                         return (cmstate{ cm_ic=new_ic }, 
275                                 CmRunOk names)
276
277
278 -- We run the statement in a "sandbox" to protect the rest of the
279 -- system from anything the expression might do.  For now, this
280 -- consists of just wrapping it in an exception handler, but see below
281 -- for another version.
282
283 sandboxIO :: IO a -> IO (Either Exception a)
284 sandboxIO thing = Exception.try thing
285
286 {-
287 -- This version of sandboxIO runs the expression in a completely new
288 -- RTS main thread.  It is disabled for now because ^C exceptions
289 -- won't be delivered to the new thread, instead they'll be delivered
290 -- to the (blocked) GHCi main thread.
291
292 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
293
294 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
295 sandboxIO thing = do
296   st_thing <- newStablePtr (Exception.try thing)
297   alloca $ \ p_st_result -> do
298     stat <- rts_evalStableIO st_thing p_st_result
299     freeStablePtr st_thing
300     if stat == 1
301         then do st_result <- peek p_st_result
302                 result <- deRefStablePtr st_result
303                 freeStablePtr st_result
304                 return (Right result)
305         else do
306                 return (Left (fromIntegral stat))
307
308 foreign import "rts_evalStableIO"  {- safe -}
309   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
310   -- more informative than the C type!
311 -}
312
313 -----------------------------------------------------------------------------
314 -- cmTypeOfExpr: returns a string representing the type of an expression
315
316 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
317 cmTypeOfExpr cmstate expr
318    = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
319
320         case maybe_stuff of
321            Nothing -> return Nothing
322            Just ty -> return (Just str)
323              where 
324                 str     = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
325                 unqual  = icPrintUnqual (cm_ic cmstate)
326                 tidy_ty = tidyType emptyTidyEnv ty
327
328
329 -----------------------------------------------------------------------------
330 -- cmTypeOfName: returns a string representing the type of a name.
331
332 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
333 cmTypeOfName CmState{ cm_ic=ic } name
334  = do 
335     hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
336     case lookupNameEnv (ic_type_env ic) name of
337         Nothing        -> return Nothing
338         Just (AnId id) -> return (Just str)
339            where
340              unqual = icPrintUnqual ic
341              ty = tidyType emptyTidyEnv (idType id)
342              str = showSDocForUser unqual (ppr ty)
343
344         _ -> panic "cmTypeOfName"
345
346 -----------------------------------------------------------------------------
347 -- cmCompileExpr: compile an expression and deliver an HValue
348
349 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
350 cmCompileExpr cmstate expr
351    = do 
352         maybe_stuff 
353             <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
354                        ("let __cmCompileExpr = "++expr)
355
356         case maybe_stuff of
357            Nothing -> return Nothing
358            Just (new_ic, names, hval) -> do
359
360                         -- Run it!
361                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
362
363                 case (names,hvals) of
364                   ([n],[hv]) -> return (Just hv)
365                   _          -> panic "cmCompileExpr"
366
367 #endif /* GHCI */
368 \end{code}
369
370
371 %************************************************************************
372 %*                                                                      *
373         Loading and unloading
374 %*                                                                      *
375 %************************************************************************
376
377 \begin{code}
378 -----------------------------------------------------------------------------
379 -- Unload the compilation manager's state: everything it knows about the
380 -- current collection of modules in the Home package.
381
382 cmUnload :: CmState -> IO CmState
383 cmUnload state@CmState{ cm_hsc = hsc_env }
384  = do -- Throw away the old home dir cache
385       flushFinderCache
386
387       -- Unload everything the linker knows about
388       cm_unload hsc_env []
389
390       -- Start with a fresh CmState, but keep the PersistentCompilerState
391       return (discardCMInfo state)
392
393 cm_unload hsc_env linkables
394   = case hsc_mode hsc_env of
395         Batch -> return ()
396 #ifdef GHCI
397         Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
398 #else
399         Interactive -> panic "unload: no interpreter"
400 #endif
401     
402
403 -----------------------------------------------------------------------------
404 -- Trace dependency graph
405
406 -- This is a seperate pass so that the caller can back off and keep
407 -- the current state if the downsweep fails.  Typically the caller
408 -- might go     cmDepAnal
409 --              cmUnload
410 --              cmLoadModules
411 -- He wants to do the dependency analysis before the unload, so that
412 -- if the former fails he can use the later
413
414 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
415 cmDepAnal cmstate rootnames
416   = do showPass dflags "Chasing dependencies"
417        when (verbosity dflags >= 1 && gmode == Batch) $
418            hPutStrLn stderr (showSDoc (hcat [
419              text "Chasing modules from: ",
420              hcat (punctuate comma (map text rootnames))]))
421        downsweep rootnames (cm_mg cmstate)
422   where
423     hsc_env = cm_hsc cmstate
424     dflags  = hsc_dflags hsc_env
425     gmode   = hsc_mode hsc_env
426
427 -----------------------------------------------------------------------------
428 -- The real business of the compilation manager: given a system state and
429 -- a module name, try and bring the module up to date, probably changing
430 -- the system state at the same time.
431
432 cmLoadModules :: CmState                -- The HPT may not be as up to date
433               -> ModuleGraph            -- Bang up to date
434               -> IO (CmState,           -- new state
435                      SuccessFlag,       -- was successful
436                      [String])          -- list of modules loaded
437
438 cmLoadModules cmstate1 mg2unsorted
439    = do -- version 1's are the original, before downsweep
440         let hsc_env   = cm_hsc cmstate1
441         let hpt1      = hsc_HPT hsc_env
442         let ghci_mode = hsc_mode   hsc_env -- this never changes
443         let dflags    = hsc_dflags hsc_env -- this never changes
444
445         -- Do the downsweep to reestablish the module graph
446         let verb = verbosity dflags
447
448         -- Find out if we have a Main module
449         let a_root_is_Main 
450                = any ((=="Main").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}