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