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