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