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