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