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