[project @ 2002-10-01 08:59:43 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 )
92 import Id               ( idType )
93 import Type             ( tidyType )
94 import VarEnv           ( emptyTidyEnv )
95 import BasicTypes       ( Fixity, FixitySig(..), defaultFixity )
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         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 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       emptyHomeDirCache
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 case ml_obj_file (ms_location summary) of
805                         Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
806                         Nothing     -> return Nothing
807
808         let old_linkable = findModuleLinkable_maybe old_linkables mod_name
809
810             new_linkables' = 
811              case (old_linkable, maybe_disk_linkable) of
812                 (Nothing, Nothing)                      -> []
813
814                 -- new object linkable just appeared
815                 (Nothing, Just l)                       -> up_to_date l True
816
817                 (Just l,  Nothing)
818                   | isObjectLinkable l                  -> []
819                     -- object linkable disappeared!  In case we need to
820                     -- relink the module, disregard the old linkable and
821                     -- just interpret the module from now on.
822                   | otherwise                           -> up_to_date l False
823                     -- old byte code linkable
824
825                 (Just l, Just l') 
826                   | not (isObjectLinkable l)            -> up_to_date l  False
827                     -- if the previous linkable was interpreted, then we
828                     -- ignore a newly compiled version, because the version
829                     -- numbers in the interface file will be out-of-sync with
830                     -- our internal ones.
831                   | linkableTime l' >  linkableTime l   -> up_to_date l' True
832                   | linkableTime l' == linkableTime l   -> up_to_date l  False
833                   | otherwise                           -> []
834                     -- on-disk linkable has been replaced by an older one!
835                     -- again, disregard the previous one.
836
837             up_to_date l b
838                 | linkableTime l < ms_hs_date summary = []
839                 | otherwise = [(l,b)]
840                 -- why '<' rather than '<=' above?  If the filesystem stores
841                 -- times to the nearset second, we may occasionally find that
842                 -- the object & source have the same modification time, 
843                 -- especially if the source was automatically generated
844                 -- and compiled.  Using >= is slightly unsafe, but it matches
845                 -- make's behaviour.
846
847         return (new_linkables' ++ new_linkables)
848
849
850 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
851 maybe_getFileLinkable mod obj_fn
852    = do obj_exist <- doesFileExist obj_fn
853         if not obj_exist 
854          then return Nothing 
855          else 
856          do let stub_fn = case splitFilename3 obj_fn of
857                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
858             stub_exist <- doesFileExist stub_fn
859             obj_time <- getModificationTime obj_fn
860             if stub_exist
861              then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
862              else return (Just (LM obj_time mod [DotO obj_fn]))
863
864 hptLinkables :: HomePackageTable -> [Linkable]
865 -- Get all the linkables from the home package table, one for each module
866 -- Once the HPT is up to date, these are the ones we should link
867 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
868
869
870 -----------------------------------------------------------------------------
871 -- Do a pre-upsweep without use of "compile", to establish a 
872 -- (downward-closed) set of stable modules for which we won't call compile.
873
874 -- a stable module:
875 --      * has a valid linkable (see getValidLinkables above)
876 --      * depends only on stable modules
877 --      * has an interface in the HPT (interactive mode only)
878
879 preUpsweep :: [Linkable]        -- new valid linkables
880            -> [ModuleName]      -- names of all mods encountered in downsweep
881            -> [ModuleName]      -- accumulating stable modules
882            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
883            -> IO [ModuleName]   -- stable modules
884
885 preUpsweep valid_lis all_home_mods stable []  = return stable
886 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
887    = do let scc = flattenSCC scc0
888             scc_allhomeimps :: [ModuleName]
889             scc_allhomeimps 
890                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
891             all_imports_in_scc_or_stable
892                = all in_stable_or_scc scc_allhomeimps
893             scc_names
894                 = map modSummaryName scc
895             in_stable_or_scc m
896                = m `elem` scc_names || m `elem` stable
897
898             -- now we check for valid linkables: each module in the SCC must 
899             -- have a valid linkable (see getValidLinkables above).
900             has_valid_linkable new_summary
901               = isJust (findModuleLinkable_maybe valid_lis modname)
902                where modname = modSummaryName new_summary
903
904             scc_is_stable = all_imports_in_scc_or_stable
905                           && all has_valid_linkable scc
906
907         if scc_is_stable
908          then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
909          else preUpsweep valid_lis all_home_mods stable sccs
910
911
912 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
913 -- stable (in the sense of preUpsweep), determine if new_summary is itself
914 -- stable, and, if so, in batch mode, return its linkable.
915 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
916 findInSummaries old_summaries mod_name
917    = [s | s <- old_summaries, modSummaryName s == mod_name]
918
919 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
920 findModInSummaries old_summaries mod
921    = case [s | s <- old_summaries, ms_mod s == mod] of
922          [] -> Nothing
923          (s:_) -> Just s
924
925 -- Return (names of) all those in modsDone who are part of a cycle
926 -- as defined by theGraph.
927 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
928 findPartiallyCompletedCycles modsDone theGraph
929    = chew theGraph
930      where
931         chew [] = []
932         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
933         chew ((CyclicSCC vs):rest)
934            = let names_in_this_cycle = nub (map modSummaryName vs)
935                  mods_in_this_cycle  
936                     = nub ([done | done <- modsDone, 
937                                    done `elem` names_in_this_cycle])
938                  chewed_rest = chew rest
939              in 
940              if   notNull mods_in_this_cycle
941                   && length mods_in_this_cycle < length names_in_this_cycle
942              then mods_in_this_cycle ++ chewed_rest
943              else chewed_rest
944
945
946 data CmThreaded  -- stuff threaded through individual module compilations
947    = CmThreaded PersistentCompilerState HomePackageTable
948
949
950 -- Compile multiple modules, stopping as soon as an error appears.
951 -- There better had not be any cyclic groups here -- we check for them.
952 upsweep_mods :: GhciMode
953              -> DynFlags
954              -> [Linkable]              -- Valid linkables
955              -> (ModuleName -> [ModuleName])  -- to construct downward closures
956              -> CmThreaded            -- PCS & HPT
957              -> IO ()                 -- how to clean up unwanted tmp files
958              -> [SCC ModSummary]      -- mods to do (the worklist)
959                                       -- ...... RETURNING ......
960              -> IO (SuccessFlag,
961                     CmThreaded,         -- Includes linkables
962                     [ModSummary])       -- Mods which succeeded
963
964 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
965      []
966    = return (Succeeded, threaded, [])
967
968 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
969      ((CyclicSCC ms):_)
970    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
971                           unwords (map (moduleNameUserString.modSummaryName) ms))
972         return (Failed, threaded, [])
973
974 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
975      ((AcyclicSCC mod):mods)
976    = do --case threaded of
977         --   CmThreaded pcsz hptz
978         --      -> putStrLn ("UPSWEEP_MOD: hpt = " ++ 
979         --                   show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
980
981         (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod 
982                                             (reachable_from (modSummaryName mod))
983
984         cleanup         -- Remove unwanted tmp files between compilations
985
986         if failed ok_flag then
987              return (Failed, threaded1, [])
988           else do 
989              (restOK, threaded2, modOKs) 
990                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
991                                        threaded1 cleanup mods
992              return (restOK, threaded2, mod:modOKs)
993
994
995 -- Compile a single module.  Always produce a Linkable for it if 
996 -- successful.  If no compilation happened, return the old Linkable.
997 upsweep_mod :: GhciMode 
998             -> DynFlags
999             -> UnlinkedImage
1000             -> CmThreaded
1001             -> ModSummary
1002             -> [ModuleName]
1003             -> IO (SuccessFlag, CmThreaded)
1004
1005 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1006    = do 
1007         let this_mod = ms_mod summary1
1008             location = ms_location summary1
1009             mod_name = moduleName this_mod
1010
1011         let (CmThreaded pcs1 hpt1) = threaded1
1012         let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
1013                              Just mod_info -> Just (hm_iface mod_info)
1014                              Nothing       -> Nothing
1015
1016         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1017             source_unchanged   = isJust maybe_old_linkable
1018
1019             reachable_only = filter (/= mod_name) reachable_inc_me
1020
1021            -- In interactive mode, all home modules below us *must* have an
1022            -- interface in the HPT.  We never demand-load home interfaces in
1023            -- interactive mode.
1024             hpt1_strictDC
1025                = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1026                  retainInTopLevelEnvs reachable_only hpt1
1027
1028             old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1029
1030             have_object 
1031                | Just l <- maybe_old_linkable, isObjectLinkable l = True
1032                | otherwise = False
1033
1034         compresult <- compile ghci_mode this_mod location source_unchanged
1035                          have_object mb_old_iface hpt1_strictDC pcs1
1036
1037         case compresult of
1038
1039            -- Compilation "succeeded", and may or may not have returned a new
1040            -- linkable (depending on whether compilation was actually performed
1041            -- or not).
1042            CompOK pcs2 new_details new_iface maybe_new_linkable
1043               -> do let 
1044                         new_linkable = maybe_new_linkable `orElse` old_linkable
1045                         new_info = HomeModInfo { hm_iface = new_iface,
1046                                                  hm_details = new_details,
1047                                                  hm_linkable = new_linkable }
1048                         hpt2      = extendModuleEnv hpt1 this_mod new_info
1049
1050                     return (Succeeded, CmThreaded pcs2 hpt2)
1051
1052            -- Compilation failed.  Compile may still have updated the PCS, tho.
1053            CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1054
1055 -- Filter modules in the HPT
1056 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1057 retainInTopLevelEnvs keep_these hpt
1058    = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1059    where
1060      maybeLookupUFM ufm u  = case lookupUFM ufm u of 
1061                                 Nothing  -> []
1062                                 Just val -> [(u, val)] 
1063
1064 -- Needed to clean up HPT so that we don't get duplicates in inst env
1065 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1066 downwards_closure_of_module summaries root
1067    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1068          toEdge summ = (modSummaryName summ, 
1069                         filter (`elem` all_mods) (ms_allimps summ))
1070
1071          all_mods = map modSummaryName summaries
1072
1073          res = simple_transitive_closure (map toEdge summaries) [root]
1074      in
1075 --         trace (showSDoc (text "DC of mod" <+> ppr root
1076 --                          <+> text "=" <+> ppr res)) $
1077          res
1078
1079 -- Calculate transitive closures from a set of roots given an adjacency list
1080 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1081 simple_transitive_closure graph set 
1082    = let set2      = nub (concatMap dsts set ++ set)
1083          dsts node = fromMaybe [] (lookup node graph)
1084      in
1085          if   length set == length set2
1086          then set
1087          else simple_transitive_closure graph set2
1088
1089
1090 -- Calculate SCCs of the module graph, with or without taking into
1091 -- account source imports.
1092 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1093 topological_sort include_source_imports summaries
1094    = let 
1095          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1096          toEdge summ
1097              = (summ, modSummaryName summ, 
1098                       (if include_source_imports 
1099                        then ms_srcimps summ else []) ++ ms_imps summ)
1100         
1101          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1102          mash_edge (summ, m, m_imports)
1103             = case lookup m key_map of
1104                  Nothing -> panic "reverse_topological_sort"
1105                  Just mk -> (summ, mk, 
1106                                 -- ignore imports not from the home package
1107                                 catMaybes (map (flip lookup key_map) m_imports))
1108
1109          edges     = map toEdge summaries
1110          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1111          scc_input = map mash_edge edges
1112          sccs      = stronglyConnComp scc_input
1113      in
1114          sccs
1115
1116
1117 -----------------------------------------------------------------------------
1118 -- Downsweep (dependency analysis)
1119
1120 -- Chase downwards from the specified root set, returning summaries
1121 -- for all home modules encountered.  Only follow source-import
1122 -- links.
1123
1124 -- We pass in the previous collection of summaries, which is used as a
1125 -- cache to avoid recalculating a module summary if the source is
1126 -- unchanged.
1127
1128 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1129 downsweep roots old_summaries
1130    = do rootSummaries <- mapM getRootSummary roots
1131         checkDuplicates rootSummaries
1132         all_summaries
1133            <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1134                                             (ms_imps m)) rootSummaries))
1135                 (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
1136                                           let mod = ms_mod s, isHomeModule mod 
1137                              ])
1138         return all_summaries
1139      where
1140         getRootSummary :: FilePath -> IO ModSummary
1141         getRootSummary file
1142            | haskellish_src_file file
1143            = do exists <- doesFileExist file
1144                 if exists then summariseFile file else do
1145                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
1146            | otherwise
1147            = do exists <- doesFileExist hs_file
1148                 if exists then summariseFile hs_file else do
1149                 exists <- doesFileExist lhs_file
1150                 if exists then summariseFile lhs_file else do
1151                 let mod_name = mkModuleName file
1152                 maybe_summary <- getSummary (file, mod_name)
1153                 case maybe_summary of
1154                    Nothing -> packageModErr mod_name
1155                    Just s  -> return s
1156            where 
1157                  hs_file = file ++ ".hs"
1158                  lhs_file = file ++ ".lhs"
1159
1160         -- In a root module, the filename is allowed to diverge from the module
1161         -- name, so we have to check that there aren't multiple root files
1162         -- defining the same module (otherwise the duplicates will be silently
1163         -- ignored, leading to confusing behaviour).
1164         checkDuplicates :: [ModSummary] -> IO ()
1165         checkDuplicates summaries = mapM_ check summaries
1166           where check summ = 
1167                   case dups of
1168                         []     -> return ()
1169                         [_one] -> return ()
1170                         many   -> multiRootsErr modl many
1171                    where modl = ms_mod summ
1172                          dups = 
1173                            [ fromJust (ml_hs_file (ms_location summ'))
1174                            | summ' <- summaries, ms_mod summ' == modl ]
1175
1176         getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1177         getSummary (currentMod,nm)
1178            = do found <- findModule nm
1179                 case found of
1180                    Just (mod, location) -> do
1181                         let old_summary = findModInSummaries old_summaries mod
1182                         summarise mod location old_summary
1183
1184                    Nothing -> 
1185                         throwDyn (CmdLineError 
1186                                    ("can't find module `" 
1187                                      ++ showSDoc (ppr nm) ++ "' (while processing " 
1188                                      ++ show currentMod ++ ")"))
1189
1190         -- loop invariant: env doesn't contain package modules
1191         loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1192         loop [] env = return (moduleEnvElts env)
1193         loop imps env
1194            = do -- imports for modules we don't already have
1195                 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1196
1197                 -- summarise them
1198                 needed_summaries <- mapM getSummary needed_imps
1199
1200                 -- get just the "home" modules
1201                 let new_home_summaries = [ s | Just s <- needed_summaries ]
1202
1203                 -- loop, checking the new imports
1204                 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1205                                                        (ms_imps m)) new_home_summaries)
1206                 loop new_imps (extendModuleEnvList env 
1207                                 [ (ms_mod s, s) | s <- new_home_summaries ])
1208
1209 -----------------------------------------------------------------------------
1210 -- Summarising modules
1211
1212 -- We have two types of summarisation:
1213 --
1214 --    * Summarise a file.  This is used for the root module(s) passed to
1215 --      cmLoadModules.  The file is read, and used to determine the root
1216 --      module name.  The module name may differ from the filename.
1217 --
1218 --    * Summarise a module.  We are given a module name, and must provide
1219 --      a summary.  The finder is used to locate the file in which the module
1220 --      resides.
1221
1222 summariseFile :: FilePath -> IO ModSummary
1223 summariseFile file
1224    = do hspp_fn <- preprocess file
1225         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1226
1227         let (path, basename, _ext) = splitFilename3 file
1228              -- GHC.Prim doesn't exist physically, so don't go looking for it.
1229             the_imps = filter (/= gHC_PRIM_Name) imps
1230
1231         (mod, location)
1232            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1233
1234         src_timestamp
1235            <- case ml_hs_file location of 
1236                  Nothing     -> noHsFileErr mod_name
1237                  Just src_fn -> getModificationTime src_fn
1238
1239         return (ModSummary { ms_mod = mod, 
1240                              ms_location = location{ml_hspp_file=Just hspp_fn},
1241                              ms_srcimps = srcimps, ms_imps = the_imps,
1242                              ms_hs_date = src_timestamp })
1243
1244 -- Summarise a module, and pick up source and timestamp.
1245 summarise :: Module -> ModLocation -> Maybe ModSummary
1246          -> IO (Maybe ModSummary)
1247 summarise mod location old_summary
1248    | not (isHomeModule mod) = return Nothing
1249    | otherwise
1250    = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1251
1252         case ml_hs_file location of {
1253            Nothing -> noHsFileErr mod;
1254            Just src_fn -> do
1255
1256         src_timestamp <- getModificationTime src_fn
1257
1258         -- return the cached summary if the source didn't change
1259         case old_summary of {
1260            Just s | ms_hs_date s == src_timestamp -> return (Just s);
1261            _ -> do
1262
1263         hspp_fn <- preprocess hs_fn
1264         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1265         let
1266              -- GHC.Prim doesn't exist physically, so don't go looking for it.
1267            the_imps = filter (/= gHC_PRIM_Name) imps
1268
1269         when (mod_name /= moduleName mod) $
1270                 throwDyn (ProgramError 
1271                    (showSDoc (text hs_fn
1272                               <>  text ": file name does not match module name"
1273                               <+> quotes (ppr (moduleName mod)))))
1274
1275         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1276                                  srcimps the_imps src_timestamp))
1277         }
1278       }
1279
1280
1281 noHsFileErr mod
1282   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1283
1284 packageModErr mod
1285   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1286                                    quotes (ppr mod) <+>
1287                                    text "is a package module")))
1288
1289 multiRootsErr mod files
1290   = throwDyn (ProgramError (showSDoc (
1291         text "module" <+> quotes (ppr mod) <+> 
1292         text "is defined in multiple files:" <+>
1293         sep (map text files))))
1294 \end{code}
1295
1296
1297 %************************************************************************
1298 %*                                                                      *
1299                 The ModSummary Type
1300 %*                                                                      *
1301 %************************************************************************
1302
1303 \begin{code}
1304 -- The ModLocation contains both the original source filename and the
1305 -- filename of the cleaned-up source file after all preprocessing has been
1306 -- done.  The point is that the summariser will have to cpp/unlit/whatever
1307 -- all files anyway, and there's no point in doing this twice -- just 
1308 -- park the result in a temp file, put the name of it in the location,
1309 -- and let @compile@ read from that file on the way back up.
1310
1311
1312 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
1313
1314 emptyMG :: ModuleGraph
1315 emptyMG = []
1316
1317 data ModSummary
1318    = ModSummary {
1319         ms_mod      :: Module,                  -- name, package
1320         ms_location :: ModLocation,             -- location
1321         ms_srcimps  :: [ModuleName],            -- source imports
1322         ms_imps     :: [ModuleName],            -- non-source imports
1323         ms_hs_date  :: ClockTime                -- timestamp of summarised file
1324      }
1325
1326 instance Outputable ModSummary where
1327    ppr ms
1328       = sep [text "ModSummary {",
1329              nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1330                           text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1331                           text "ms_imps =" <+> ppr (ms_imps ms),
1332                           text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1333              char '}'
1334             ]
1335
1336 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1337
1338 modSummaryName :: ModSummary -> ModuleName
1339 modSummaryName = moduleName . ms_mod
1340 \end{code}