[project @ 2001-08-01 12:07:50 by simonmar]
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CompManager]{The Compilation Manager}
5
6 \begin{code}
7 module CompManager ( 
8     cmInit,       -- :: GhciMode -> IO CmState
9
10     cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
11
12     cmUnload,     -- :: CmState -> DynFlags -> IO CmState
13
14     cmSetContext, -- :: CmState -> String -> IO CmState
15
16     cmGetContext, -- :: CmState -> IO String
17
18 #ifdef GHCI
19     cmInfoThing,  -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
20
21     cmRunStmt,    -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
22
23     cmTypeOfExpr, -- :: CmState -> DynFlags -> String
24                   -- -> IO (CmState, Maybe String)
25
26     cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
27
28     cmCompileExpr,-- :: CmState -> DynFlags -> String 
29                   -- -> IO (CmState, Maybe HValue)#endif
30 #endif
31     CmState, emptyCmState  -- abstract
32   )
33 where
34
35 #include "HsVersions.h"
36
37 import CmLink
38 import CmTypes
39 import DriverPipeline
40 import DriverFlags      ( getDynFlags )
41 import DriverPhases
42 import DriverUtil
43 import Finder
44 #ifdef GHCI
45 import HscMain          ( initPersistentCompilerState, hscThing )
46 #else
47 import HscMain          ( initPersistentCompilerState )
48 #endif
49 import HscTypes
50 import RnEnv            ( unQualInScope )
51 import Id               ( idType, idName )
52 import Name             ( Name, NamedThing(..), nameRdrName )
53 import NameEnv
54 import RdrName          ( lookupRdrEnv, emptyRdrEnv )
55 import Module
56 import GetImports
57 import Type             ( tidyType )
58 import VarEnv           ( emptyTidyEnv )
59 import UniqFM
60 import Unique           ( Uniquable )
61 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC )
62 import ErrUtils         ( showPass )
63 import SysTools         ( cleanTempFilesExcept )
64 import Util
65 import Outputable
66 import Panic
67 import CmdLineOpts      ( DynFlags(..) )
68 import IOExts
69
70 #ifdef GHCI
71 import Interpreter      ( HValue )
72 import HscMain          ( hscStmt )
73 import PrelGHC          ( unsafeCoerce# )
74 #endif
75
76 -- lang
77 import Exception        ( throwDyn )
78
79 -- std
80 import Directory        ( getModificationTime, doesFileExist )
81 import IO
82 import Monad
83 import List             ( nub )
84 import Maybe
85 \end{code}
86
87
88 \begin{code}
89 -- Persistent state for the entire system
90 data CmState
91    = CmState {
92         hst   :: HomeSymbolTable,    -- home symbol table
93         hit   :: HomeIfaceTable,     -- home interface table
94         ui    :: UnlinkedImage,      -- the unlinked images
95         mg    :: ModuleGraph,        -- the module graph
96         gmode :: GhciMode,           -- NEVER CHANGES
97         ic    :: InteractiveContext, -- command-line binding info
98
99         pcs    :: PersistentCompilerState, -- compile's persistent state
100         pls    :: PersistentLinkerState    -- link's persistent state
101      }
102
103 emptyCmState :: GhciMode -> Module -> IO CmState
104 emptyCmState gmode mod
105     = do pcs     <- initPersistentCompilerState
106          pls     <- emptyPLS
107          return (CmState { hst    = emptySymbolTable,
108                            hit    = emptyIfaceTable,
109                            ui     = emptyUI,
110                            mg     = emptyMG, 
111                            gmode  = gmode,
112                            ic     = emptyInteractiveContext mod,
113                            pcs    = pcs,
114                            pls    = pls })
115
116 emptyInteractiveContext mod
117   = InteractiveContext { ic_module = mod, 
118                          ic_rn_env = emptyRdrEnv,
119                          ic_type_env = emptyTypeEnv }
120
121 defaultCurrentModuleName = mkModuleName "Prelude"
122 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
123
124 -- CM internal types
125 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
126 emptyUI :: UnlinkedImage
127 emptyUI = []
128
129 type ModuleGraph = [ModSummary]  -- the module graph, topologically sorted
130 emptyMG :: ModuleGraph
131 emptyMG = []
132
133 -----------------------------------------------------------------------------
134 -- Produce an initial CmState.
135
136 cmInit :: GhciMode -> IO CmState
137 cmInit mode = do
138    prel <- moduleNameToModule defaultCurrentModuleName
139    writeIORef defaultCurrentModule prel
140    emptyCmState mode prel
141
142 -----------------------------------------------------------------------------
143 -- Setting the context doesn't throw away any bindings; the bindings
144 -- we've built up in the InteractiveContext simply move to the new
145 -- module.  They always shadow anything in scope in the current context.
146
147 cmSetContext :: CmState -> String -> IO CmState
148 cmSetContext cmstate str
149    = do let mn = mkModuleName str
150             modules_loaded = [ (name_of_summary s, ms_mod s)  | s <- mg cmstate ]
151
152         m <- case lookup mn modules_loaded of
153                 Just m  -> return m
154                 Nothing -> do
155                    mod <- moduleNameToModule mn
156                    if isHomeModule mod 
157                         then throwDyn (CmdLineError (showSDoc 
158                                 (quotes (ppr (moduleName mod))
159                                   <+> text "is not currently loaded")))
160                         else return mod
161
162         return cmstate{ ic = (ic cmstate){ic_module=m} }
163                 
164 cmGetContext :: CmState -> IO String
165 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
166
167 moduleNameToModule :: ModuleName -> IO Module
168 moduleNameToModule mn
169  = do maybe_stuff <- findModule mn
170       case maybe_stuff of
171         Nothing -> throwDyn (CmdLineError ("can't find module `"
172                                     ++ moduleNameUserString mn ++ "'"))
173         Just (m,_) -> return m
174
175 -----------------------------------------------------------------------------
176 -- cmRunStmt:  Run a statement/expr.
177
178 #ifdef GHCI
179 cmInfoThing :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
180 cmInfoThing CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } dflags id
181    = do (pcs, thing) <- hscThing dflags hst hit pcs icontext id
182         return thing
183
184 cmRunStmt :: CmState -> DynFlags -> String
185         -> IO (CmState,                 -- new state
186                [Name])                  -- names bound by this evaluation
187 cmRunStmt cmstate dflags expr
188    = do 
189         let InteractiveContext { 
190                 ic_rn_env = rn_env, 
191                 ic_type_env = type_env,
192                 ic_module   = this_mod } = icontext
193
194         (new_pcs, maybe_stuff) 
195             <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
196
197         case maybe_stuff of
198            Nothing -> return (cmstate{ pcs=new_pcs }, [])
199            Just (ids, _, bcos) -> do
200
201                 -- update the interactive context
202                 let 
203                     names = map idName ids
204
205                     -- these names have just been shadowed
206                     shadowed = [ n | r <- map nameRdrName names,
207                                      Just n <- [lookupRdrEnv rn_env r] ]
208                     
209                     new_rn_env   = extendLocalRdrEnv rn_env names
210
211                     -- remove any shadowed bindings from the type_env
212                     filtered_type_env = delListFromNameEnv type_env shadowed
213
214                     new_type_env = extendNameEnvList filtered_type_env  
215                                         [ (getName id, AnId id) | id <- ids]
216
217                     new_ic = icontext { ic_rn_env   = new_rn_env, 
218                                         ic_type_env = new_type_env }
219
220                 -- link it
221                 hval <- linkExpr pls bcos
222
223                 -- run it!
224                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
225                 hvals <- thing_to_run
226
227                 -- Get the newly bound things, and bind them.  Don't forget
228                 -- to delete any shadowed bindings from the closure_env, lest
229                 -- we end up with a space leak.
230                 pls <- delListFromClosureEnv pls shadowed
231                 new_pls <- addListToClosureEnv pls (zip names hvals)
232
233                 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
234    where
235        CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
236 #endif
237
238 -----------------------------------------------------------------------------
239 -- cmTypeOfExpr: returns a string representing the type of an expression
240
241 #ifdef GHCI
242 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
243 cmTypeOfExpr cmstate dflags expr
244    = do (new_pcs, maybe_stuff) 
245           <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
246
247         let new_cmstate = cmstate{pcs = new_pcs}
248
249         case maybe_stuff of
250            Nothing -> return (new_cmstate, Nothing)
251            Just (_, ty, _) ->
252              let pit = pcs_PIT pcs
253                  modname = moduleName (ic_module ic)
254                  tidy_ty = tidyType emptyTidyEnv ty
255                  str = case lookupIfaceByModName hit pit modname of
256                           Nothing    -> showSDoc (ppr tidy_ty)
257                           Just iface -> showSDocForUser unqual (ppr tidy_ty)
258                              where unqual = unQualInScope (mi_globals iface)
259              in return (new_cmstate, Just str)
260    where
261        CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
262 #endif
263
264 -----------------------------------------------------------------------------
265 -- cmTypeOfName: returns a string representing the type of a name.
266
267 #ifdef GHCI
268 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
269 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
270  = case lookupNameEnv (ic_type_env ic) name of
271         Nothing -> return Nothing
272         Just (AnId id) -> 
273            let pit = pcs_PIT pcs
274                modname = moduleName (ic_module ic)
275                ty = tidyType emptyTidyEnv (idType id)
276                str = case lookupIfaceByModName hit pit modname of
277                         Nothing    -> showSDoc (ppr ty)
278                         Just iface -> showSDocForUser unqual (ppr ty)
279                            where unqual = unQualInScope (mi_globals iface)
280            in return (Just str)
281
282         _ -> panic "cmTypeOfName"
283 #endif
284
285 -----------------------------------------------------------------------------
286 -- cmCompileExpr: compile an expression and deliver an HValue
287
288 #ifdef GHCI
289 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
290 cmCompileExpr cmstate dflags expr
291    = do 
292         let InteractiveContext { 
293                 ic_rn_env = rn_env, 
294                 ic_type_env = type_env,
295                 ic_module   = this_mod } = icontext
296
297         (new_pcs, maybe_stuff) 
298             <- hscStmt dflags hst hit pcs icontext 
299                   ("let __cmCompileExpr = "++expr) False{-stmt-}
300
301         case maybe_stuff of
302            Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
303            Just (ids, _, bcos) -> do
304
305                 -- link it
306                 hval <- linkExpr pls bcos
307
308                 -- run it!
309                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
310                 hvals <- thing_to_run
311
312                 case (ids,hvals) of
313                   ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
314                   _ -> panic "cmCompileExpr"
315
316    where
317        CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
318 #endif
319
320 -----------------------------------------------------------------------------
321 -- cmInfo: return "info" about an expression.  The info might be:
322 --
323 --      * its type, for an expression,
324 --      * the class definition, for a class
325 --      * the datatype definition, for a tycon (or synonym)
326 --      * the export list, for a module
327 --
328 -- Can be used to find the type of the last expression compiled, by looking
329 -- for "it".
330
331 cmInfo :: CmState -> String -> IO (Maybe String)
332 cmInfo cmstate str 
333  = do error "cmInfo not implemented yet"
334
335 -----------------------------------------------------------------------------
336 -- Unload the compilation manager's state: everything it knows about the
337 -- current collection of modules in the Home package.
338
339 cmUnload :: CmState -> DynFlags -> IO CmState
340 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
341  = do -- Throw away the old home dir cache
342       emptyHomeDirCache
343
344       -- Unload everything the linker knows about
345       new_pls <- CmLink.unload mode dflags [] pls 
346
347       -- Start with a fresh CmState, but keep the PersistentCompilerState
348       new_state <- cmInit mode
349       return new_state{ pcs=pcs, pls=new_pls }
350
351 -----------------------------------------------------------------------------
352 -- The real business of the compilation manager: given a system state and
353 -- a module name, try and bring the module up to date, probably changing
354 -- the system state at the same time.
355
356 cmLoadModule :: CmState 
357              -> [FilePath]
358              -> IO (CmState,            -- new state
359                     Bool,               -- was successful
360                     [String])           -- list of modules loaded
361
362 cmLoadModule cmstate1 rootnames
363    = do -- version 1's are the original, before downsweep
364         let pls1      = pls    cmstate1
365         let pcs1      = pcs    cmstate1
366         let hst1      = hst    cmstate1
367         let hit1      = hit    cmstate1
368         -- similarly, ui1 is the (complete) set of linkables from
369         -- the previous pass, if any.
370         let ui1       = ui     cmstate1
371         let mg1       = mg     cmstate1
372         let ic1       = ic     cmstate1
373
374         let ghci_mode = gmode cmstate1 -- this never changes
375
376         -- Do the downsweep to reestablish the module graph
377         dflags <- getDynFlags
378         let verb = verbosity dflags
379
380         showPass dflags "Chasing dependencies"
381         when (verb >= 1 && ghci_mode == Batch) $
382            hPutStrLn stderr (showSDoc (hcat [
383              text progName, text ": chasing modules from: ",
384              hcat (punctuate comma (map text rootnames))]))
385
386         (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
387         let mg2unsorted_names = map name_of_summary mg2unsorted
388
389         -- reachable_from follows source as well as normal imports
390         let reachable_from :: ModuleName -> [ModuleName]
391             reachable_from = downwards_closure_of_module mg2unsorted
392  
393         -- should be cycle free; ignores 'import source's
394         let mg2 = topological_sort False mg2unsorted
395         -- ... whereas this takes them into account.  Used for
396         -- backing out partially complete cycles following a failed
397         -- upsweep, and for removing from hst/hit all the modules
398         -- not in strict downwards closure, during calls to compile.
399         let mg2_with_srcimps = topological_sort True mg2unsorted
400
401         -- Sort out which linkables we wish to keep in the unlinked image.
402         -- See getValidLinkables below for details.
403         valid_linkables <- getValidLinkables ui1 mg2unsorted_names 
404                                 mg2_with_srcimps
405         -- when (verb >= 2) $
406         --    putStrLn (showSDoc (text "Valid linkables:" 
407         --                       <+> ppr valid_linkables))
408
409         -- Figure out a stable set of modules which can be retained
410         -- the top level envs, to avoid upsweeping them.  Goes to a
411         -- bit of trouble to avoid upsweeping module cycles.
412         --
413         -- Construct a set S of stable modules like this:
414         -- Travel upwards, over the sccified graph.  For each scc
415         -- of modules ms, add ms to S only if:
416         -- 1.  All home imports of ms are either in ms or S
417         -- 2.  A valid linkable exists for each module in ms
418
419         stable_mods <- preUpsweep valid_linkables hit1 
420                                   mg2unsorted_names [] mg2_with_srcimps
421
422         let stable_summaries
423                = concatMap (findInSummaries mg2unsorted) stable_mods
424
425             stable_linkables
426                = filter (\m -> linkableModName m `elem` stable_mods) 
427                     valid_linkables
428
429         when (verb >= 2) $
430            putStrLn (showSDoc (text "Stable modules:" 
431                                <+> sep (map (text.moduleNameUserString) stable_mods)))
432
433         -- unload any modules which aren't going to be re-linked this
434         -- time around.
435         pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
436
437         -- We could at this point detect cycles which aren't broken by
438         -- a source-import, and complain immediately, but it seems better
439         -- to let upsweep_mods do this, so at least some useful work gets
440         -- done before the upsweep is abandoned.
441         let upsweep_these
442                = filter (\scc -> any (`notElem` stable_mods) 
443                                      (map name_of_summary (flattenSCC scc)))
444                         mg2
445
446         --hPutStrLn stderr "after tsort:\n"
447         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
448
449         -- Because we don't take into account source imports when doing
450         -- the topological sort, there shouldn't be any cycles in mg2.
451         -- If there is, we complain and give up -- the user needs to
452         -- break the cycle using a boot file.
453
454         -- Now do the upsweep, calling compile for each module in
455         -- turn.  Final result is version 3 of everything.
456
457         let threaded2 = CmThreaded pcs1 hst1 hit1
458
459         (upsweep_complete_success, threaded3, modsUpswept, newLis)
460            <- upsweep_mods ghci_mode dflags valid_linkables reachable_from 
461                            threaded2 upsweep_these
462
463         let ui3 = add_to_ui valid_linkables newLis
464         let (CmThreaded pcs3 hst3 hit3) = threaded3
465
466         -- At this point, modsUpswept and newLis should have the same
467         -- length, so there is one new (or old) linkable for each 
468         -- mod which was processed (passed to compile).
469
470         -- Make modsDone be the summaries for each home module now
471         -- available; this should equal the domains of hst3 and hit3.
472         -- (NOT STRICTLY TRUE if an interactive session was started
473         --  with some object on disk ???)
474         -- Get in in a roughly top .. bottom order (hence reverse).
475
476         let modsDone = reverse modsUpswept ++ stable_summaries
477
478         -- Try and do linking in some form, depending on whether the
479         -- upsweep was completely or only partially successful.
480
481         if upsweep_complete_success
482
483          then 
484            -- Easy; just relink it all.
485            do when (verb >= 2) $ 
486                  hPutStrLn stderr "Upsweep completely successful."
487
488               -- clean up after ourselves
489               cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
490
491               -- link everything together
492               linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
493
494               cmLoadFinish True linkresult 
495                         hst3 hit3 ui3 modsDone ghci_mode pcs3
496
497          else 
498            -- Tricky.  We need to back out the effects of compiling any
499            -- half-done cycles, both so as to clean up the top level envs
500            -- and to avoid telling the interactive linker to link them.
501            do when (verb >= 2) $
502                 hPutStrLn stderr "Upsweep partially successful."
503
504               let modsDone_names
505                      = map name_of_summary modsDone
506               let mods_to_zap_names 
507                      = findPartiallyCompletedCycles modsDone_names 
508                           mg2_with_srcimps
509               let mods_to_keep
510                      = filter ((`notElem` mods_to_zap_names).name_of_summary) 
511                           modsDone
512
513               let (hst4, hit4, ui4)
514                      = retainInTopLevelEnvs (map name_of_summary mods_to_keep) 
515                                             (hst3,hit3,ui3)
516
517               -- clean up after ourselves
518               cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
519
520               -- link everything together
521               linkresult <- link ghci_mode dflags False ui4 pls2
522
523               cmLoadFinish False linkresult 
524                     hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
525
526
527 -- Finish up after a cmLoad.
528 --
529 -- Empty the interactive context and set the module context to the topmost
530 -- newly loaded module, or the Prelude if none were loaded.
531 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
532   = do case linkresult of {
533           LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
534           LinkOK pls   -> do
535
536        def_mod <- readIORef defaultCurrentModule
537        let current_mod = case mods of 
538                                 []    -> def_mod
539                                 (x:_) -> ms_mod x
540
541            new_ic = emptyInteractiveContext current_mod
542
543            new_cmstate = CmState{ hst=hst, hit=hit, 
544                                   ui=ui, mg=mods,
545                                   gmode=ghci_mode, pcs=pcs, 
546                                   pls=pls,
547                                   ic = new_ic }
548            mods_loaded = map (moduleNameUserString.name_of_summary) mods
549
550        return (new_cmstate, ok, mods_loaded)
551     }
552
553 -- used to fish out the preprocess output files for the purposes
554 -- of cleaning up.
555 ppFilesFromSummaries summaries
556   = [ fn | Just fn <- map toPpFile summaries ]
557   where
558    toPpFile sum
559      | hspp /= ml_hs_file loc = hspp
560      | otherwise              = Nothing
561     where
562       loc  = ms_location sum
563       hspp = ml_hspp_file loc
564
565
566 -----------------------------------------------------------------------------
567 -- getValidLinkables
568
569 -- For each module (or SCC of modules), we take:
570 --
571 --      - an on-disk linkable, if this is the first time around and one
572 --        is available.
573 --
574 --      - the old linkable, otherwise (and if one is available).
575 --
576 -- and we throw away the linkable if it is older than the source
577 -- file.  We ignore the on-disk linkables unless all of the dependents
578 -- of this SCC also have on-disk linkables.
579 --
580 -- If a module has a valid linkable, then it may be STABLE (see below),
581 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
582 -- compile.
583 --
584 -- ToDo: this pass could be merged with the preUpsweep.
585
586 getValidLinkables
587         :: [Linkable]           -- old linkables
588         -> [ModuleName]         -- all home modules
589         -> [SCC ModSummary]     -- all modules in the program, dependency order
590         -> IO [Linkable]        -- still-valid linkables 
591
592 getValidLinkables old_linkables all_home_mods module_graph
593   = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
594
595 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
596    = let 
597           scc             = flattenSCC scc0
598           scc_names       = map name_of_summary scc
599           home_module m   = m `elem` all_home_mods && m `notElem` scc_names
600           scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
601                 -- NOTE: ms_imps, not ms_allimps above.  We don't want to
602                 -- force a module's SOURCE imports to be already compiled for
603                 -- its object linkable to be valid.
604
605           has_object m = case findModuleLinkable_maybe new_linkables m of
606                             Nothing -> False
607                             Just l  -> isObjectLinkable l
608
609           objects_allowed = all has_object scc_allhomeimps
610      in do
611
612      these_linkables 
613         <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
614
615         -- since an scc can contain only all objects or no objects at all,
616         -- we have to check whether we got all objects or not, and re-do
617         -- the linkable check if not.
618      adjusted_linkables 
619         <- if objects_allowed && not (all isObjectLinkable these_linkables)
620               then foldM (getValidLinkable old_linkables False) [] scc
621               else return these_linkables
622
623      return (adjusted_linkables ++ new_linkables)
624
625
626 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary 
627         -> IO [Linkable]
628 getValidLinkable old_linkables objects_allowed new_linkables summary 
629   = do let mod_name = name_of_summary summary
630
631        maybe_disk_linkable
632           <- if (not objects_allowed)
633                 then return Nothing
634                 else case ml_obj_file (ms_location summary) of
635                         Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
636                         Nothing -> return Nothing
637
638        let old_linkable = findModuleLinkable_maybe old_linkables mod_name
639            maybe_old_linkable =
640                 case old_linkable of
641                     Just l | not (isObjectLinkable l) || stillThere l 
642                                 -> old_linkable
643                                 -- ToDo: emit a warning if not (stillThere l)
644                     other -> Nothing
645
646            -- make sure that if we had an old disk linkable around, that it's
647            -- still there on the disk (in case we need to re-link it).
648            stillThere l = 
649                 case maybe_disk_linkable of
650                    Nothing    -> False
651                    Just l_disk -> linkableTime l == linkableTime l_disk
652
653            -- we only look for objects on disk the first time around;
654            -- if the user compiles a module on the side during a GHCi session,
655            -- it won't be picked up until the next ":load".  This is what the
656            -- "null old_linkables" test below is.
657            linkable | null old_linkables = maybeToList maybe_disk_linkable
658                     | otherwise          = maybeToList maybe_old_linkable
659
660            -- only linkables newer than the source code are valid
661            src_date = ms_hs_date summary
662
663            valid_linkable
664               =  filter (\l -> linkableTime l >= src_date) linkable
665                 -- why '>=' rather than '>' above?  If the filesystem stores
666                 -- times to the nearset second, we may occasionally find that
667                 -- the object & source have the same modification time, 
668                 -- especially if the source was automatically generated
669                 -- and compiled.  Using >= is slightly unsafe, but it matches
670                 -- make's behaviour.
671
672        return (valid_linkable ++ new_linkables)
673
674
675 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
676 maybe_getFileLinkable mod_name obj_fn
677    = do obj_exist <- doesFileExist obj_fn
678         if not obj_exist 
679          then return Nothing 
680          else 
681          do let stub_fn = case splitFilename3 obj_fn of
682                              (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
683             stub_exist <- doesFileExist stub_fn
684             obj_time <- getModificationTime obj_fn
685             if stub_exist
686              then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
687              else return (Just (LM obj_time mod_name [DotO obj_fn]))
688
689
690 -----------------------------------------------------------------------------
691 -- Do a pre-upsweep without use of "compile", to establish a 
692 -- (downward-closed) set of stable modules for which we won't call compile.
693
694 -- a stable module:
695 --      * has a valid linkable (see getValidLinkables above)
696 --      * depends only on stable modules
697 --      * has an interface in the HIT (interactive mode only)
698
699 preUpsweep :: [Linkable]        -- new valid linkables
700            -> HomeIfaceTable
701            -> [ModuleName]      -- names of all mods encountered in downsweep
702            -> [ModuleName]      -- accumulating stable modules
703            -> [SCC ModSummary]  -- scc-ified mod graph, including src imps
704            -> IO [ModuleName]   -- stable modules
705
706 preUpsweep valid_lis hit all_home_mods stable []  = return stable
707 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
708    = do let scc = flattenSCC scc0
709             scc_allhomeimps :: [ModuleName]
710             scc_allhomeimps 
711                = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
712             all_imports_in_scc_or_stable
713                = all in_stable_or_scc scc_allhomeimps
714             scc_names
715                = map name_of_summary scc
716             in_stable_or_scc m
717                = m `elem` scc_names || m `elem` stable
718
719             -- now we check for valid linkables: each module in the SCC must 
720             -- have a valid linkable (see getValidLinkables above).
721             has_valid_linkable new_summary
722               = isJust (findModuleLinkable_maybe valid_lis modname)
723                where modname = name_of_summary new_summary
724
725             has_interface summary = ms_mod summary `elemUFM` hit
726
727             scc_is_stable = all_imports_in_scc_or_stable
728                           && all has_valid_linkable scc
729                           && all has_interface scc
730
731         if scc_is_stable
732          then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
733          else preUpsweep valid_lis hit all_home_mods stable sccs
734
735
736 -- Helper for preUpsweep.  Assuming that new_summary's imports are all
737 -- stable (in the sense of preUpsweep), determine if new_summary is itself
738 -- stable, and, if so, in batch mode, return its linkable.
739 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
740 findInSummaries old_summaries mod_name
741    = [s | s <- old_summaries, name_of_summary s == mod_name]
742
743 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
744 findModInSummaries old_summaries mod
745    = case [s | s <- old_summaries, ms_mod s == mod] of
746          [] -> Nothing
747          (s:_) -> Just s
748
749 -- Return (names of) all those in modsDone who are part of a cycle
750 -- as defined by theGraph.
751 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
752 findPartiallyCompletedCycles modsDone theGraph
753    = chew theGraph
754      where
755         chew [] = []
756         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
757         chew ((CyclicSCC vs):rest)
758            = let names_in_this_cycle = nub (map name_of_summary vs)
759                  mods_in_this_cycle  
760                     = nub ([done | done <- modsDone, 
761                                    done `elem` names_in_this_cycle])
762                  chewed_rest = chew rest
763              in 
764              if   not (null mods_in_this_cycle) 
765                   && length mods_in_this_cycle < length names_in_this_cycle
766              then mods_in_this_cycle ++ chewed_rest
767              else chewed_rest
768
769
770 -- Add the given (LM-form) Linkables to the UI, overwriting previous
771 -- versions if they exist.
772 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
773 add_to_ui ui lis
774    = filter (not_in lis) ui ++ lis
775      where
776         not_in :: [Linkable] -> Linkable -> Bool
777         not_in lis li
778            = all (\l -> linkableModName l /= mod) lis
779            where mod = linkableModName li
780                                   
781
782 data CmThreaded  -- stuff threaded through individual module compilations
783    = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
784
785
786 -- Compile multiple modules, stopping as soon as an error appears.
787 -- There better had not be any cyclic groups here -- we check for them.
788 upsweep_mods :: GhciMode
789              -> DynFlags
790              -> UnlinkedImage         -- valid linkables
791              -> (ModuleName -> [ModuleName])  -- to construct downward closures
792              -> CmThreaded            -- PCS & HST & HIT
793              -> [SCC ModSummary]      -- mods to do (the worklist)
794                                       -- ...... RETURNING ......
795              -> IO (Bool{-complete success?-},
796                     CmThreaded,
797                     [ModSummary],     -- mods which succeeded
798                     [Linkable])       -- new linkables
799
800 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
801      []
802    = return (True, threaded, [], [])
803
804 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
805      ((CyclicSCC ms):_)
806    = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
807                           unwords (map (moduleNameUserString.name_of_summary) ms))
808         return (False, threaded, [], [])
809
810 upsweep_mods ghci_mode dflags oldUI reachable_from threaded 
811      ((AcyclicSCC mod):mods)
812    = do --case threaded of
813         --   CmThreaded pcsz hstz hitz
814         --      -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
815
816         (threaded1, maybe_linkable) 
817            <- upsweep_mod ghci_mode dflags oldUI threaded mod 
818                           (reachable_from (name_of_summary mod))
819         case maybe_linkable of
820            Just linkable 
821               -> -- No errors; do the rest
822                  do (restOK, threaded2, modOKs, linkables) 
823                        <- upsweep_mods ghci_mode dflags oldUI reachable_from 
824                                        threaded1 mods
825                     return (restOK, threaded2, mod:modOKs, linkable:linkables)
826            Nothing -- we got a compilation error; give up now
827               -> return (False, threaded1, [], [])
828
829
830 -- Compile a single module.  Always produce a Linkable for it if 
831 -- successful.  If no compilation happened, return the old Linkable.
832 upsweep_mod :: GhciMode 
833             -> DynFlags
834             -> UnlinkedImage
835             -> CmThreaded
836             -> ModSummary
837             -> [ModuleName]
838             -> IO (CmThreaded, Maybe Linkable)
839
840 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
841    = do 
842         let mod_name = name_of_summary summary1
843         let verb = verbosity dflags
844
845         let (CmThreaded pcs1 hst1 hit1) = threaded1
846         let old_iface = lookupUFM hit1 mod_name
847
848         let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
849
850             source_unchanged = isJust maybe_old_linkable
851
852             reachable_only = filter (/= (name_of_summary summary1)) 
853                                 reachable_inc_me
854
855            -- in interactive mode, all home modules below us *must* have an
856            -- interface in the HIT.  We never demand-load home interfaces in
857            -- interactive mode.
858             (hst1_strictDC, hit1_strictDC, [])
859                = ASSERT(ghci_mode == Batch || 
860                         all (`elemUFM` hit1) reachable_only)
861                  retainInTopLevelEnvs reachable_only (hst1,hit1,[])
862
863             old_linkable 
864                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
865
866             have_object 
867                | Just l <- maybe_old_linkable, isObjectLinkable l = True
868                | otherwise = False
869
870         compresult <- compile ghci_mode summary1 source_unchanged
871                          have_object old_iface hst1_strictDC hit1_strictDC pcs1
872
873         case compresult of
874
875            -- Compilation "succeeded", and may or may not have returned a new
876            -- linkable (depending on whether compilation was actually performed
877            -- or not).
878            CompOK pcs2 new_details new_iface maybe_new_linkable
879               -> do let hst2      = addToUFM hst1 mod_name new_details
880                         hit2      = addToUFM hit1 mod_name new_iface
881                         threaded2 = CmThreaded pcs2 hst2 hit2
882
883                     return (threaded2, if isJust maybe_new_linkable
884                                           then maybe_new_linkable
885                                           else Just old_linkable)
886
887            -- Compilation failed.  compile may still have updated
888            -- the PCS, tho.
889            CompErrs pcs2
890               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
891                     return (threaded2, Nothing)
892
893 -- Filter modules in the top level envs (HST, HIT, UI).
894 retainInTopLevelEnvs :: [ModuleName]
895                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
896                         -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
897 retainInTopLevelEnvs keep_these (hst, hit, ui)
898    = (retainInUFM hst keep_these,
899       retainInUFM hit keep_these,
900       filterModuleLinkables (`elem` keep_these) ui
901      )
902      where
903         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
904         retainInUFM ufm keys_to_keep
905            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
906         maybeLookupUFM ufm u 
907            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
908
909 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
910 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
911 downwards_closure_of_module summaries root
912    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
913          toEdge summ = (name_of_summary summ, 
914                         filter (`elem` all_mods) (ms_allimps summ))
915
916          all_mods = map name_of_summary summaries
917
918          res = simple_transitive_closure (map toEdge summaries) [root]
919      in
920 --         trace (showSDoc (text "DC of mod" <+> ppr root
921 --                          <+> text "=" <+> ppr res)) $
922          res
923
924 -- Calculate transitive closures from a set of roots given an adjacency list
925 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
926 simple_transitive_closure graph set 
927    = let set2      = nub (concatMap dsts set ++ set)
928          dsts node = fromMaybe [] (lookup node graph)
929      in
930          if   length set == length set2
931          then set
932          else simple_transitive_closure graph set2
933
934
935 -- Calculate SCCs of the module graph, with or without taking into
936 -- account source imports.
937 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
938 topological_sort include_source_imports summaries
939    = let 
940          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
941          toEdge summ
942              = (summ, name_of_summary summ, 
943                       (if include_source_imports 
944                        then ms_srcimps summ else []) ++ ms_imps summ)
945         
946          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
947          mash_edge (summ, m, m_imports)
948             = case lookup m key_map of
949                  Nothing -> panic "reverse_topological_sort"
950                  Just mk -> (summ, mk, 
951                                 -- ignore imports not from the home package
952                                 catMaybes (map (flip lookup key_map) m_imports))
953
954          edges     = map toEdge summaries
955          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
956          scc_input = map mash_edge edges
957          sccs      = stronglyConnComp scc_input
958      in
959          sccs
960
961
962 -- Chase downwards from the specified root set, returning summaries
963 -- for all home modules encountered.  Only follow source-import
964 -- links.  Also returns a Bool to indicate whether any of the roots
965 -- are module Main.
966 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
967 downsweep rootNm old_summaries
968    = do rootSummaries <- mapM getRootSummary rootNm
969         let a_root_is_Main 
970                = any ((=="Main").moduleNameUserString.name_of_summary) 
971                      rootSummaries
972         all_summaries
973            <- loop (concat (map ms_imps rootSummaries))
974                 (mkModuleEnv [ (mod, s) | s <- rootSummaries, 
975                                           let mod = ms_mod s, isHomeModule mod 
976                              ])
977         return (all_summaries, a_root_is_Main)
978      where
979         getRootSummary :: FilePath -> IO ModSummary
980         getRootSummary file
981            | haskellish_src_file file
982            = do exists <- doesFileExist file
983                 if exists then summariseFile file else do
984                 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))    
985            | otherwise
986            = do exists <- doesFileExist hs_file
987                 if exists then summariseFile hs_file else do
988                 exists <- doesFileExist lhs_file
989                 if exists then summariseFile lhs_file else do
990                 let mod_name = mkModuleName file
991                 maybe_summary <- getSummary mod_name
992                 case maybe_summary of
993                    Nothing -> packageModErr mod_name
994                    Just s  -> return s
995            where 
996                  hs_file = file ++ ".hs"
997                  lhs_file = file ++ ".lhs"
998
999         getSummary :: ModuleName -> IO (Maybe ModSummary)
1000         getSummary nm
1001            = do found <- findModule nm
1002                 case found of
1003                    Just (mod, location) -> do
1004                         let old_summary = findModInSummaries old_summaries mod
1005                         summarise mod location old_summary
1006
1007                    Nothing -> throwDyn (CmdLineError 
1008                                    ("can't find module `" 
1009                                      ++ showSDoc (ppr nm) ++ "'"))
1010
1011         -- loop invariant: env doesn't contain package modules
1012         loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1013         loop [] env = return (moduleEnvElts env)
1014         loop imps env
1015            = do -- imports for modules we don't already have
1016                 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1017
1018                 -- summarise them
1019                 needed_summaries <- mapM getSummary needed_imps
1020
1021                 -- get just the "home" modules
1022                 let new_home_summaries = [ s | Just s <- needed_summaries ]
1023
1024                 -- loop, checking the new imports
1025                 let new_imps = concat (map ms_imps new_home_summaries)
1026                 loop new_imps (extendModuleEnvList env 
1027                                 [ (ms_mod s, s) | s <- new_home_summaries ])
1028
1029 -----------------------------------------------------------------------------
1030 -- Summarising modules
1031
1032 -- We have two types of summarisation:
1033 --
1034 --    * Summarise a file.  This is used for the root module passed to
1035 --      cmLoadModule.  The file is read, and used to determine the root
1036 --      module name.  The module name may differ from the filename.
1037 --
1038 --    * Summarise a module.  We are given a module name, and must provide
1039 --      a summary.  The finder is used to locate the file in which the module
1040 --      resides.
1041
1042 summariseFile :: FilePath -> IO ModSummary
1043 summariseFile file
1044    = do hspp_fn <- preprocess file
1045         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1046
1047         let (path, basename, ext) = splitFilename3 file
1048
1049         Just (mod, location)
1050            <- mkHomeModuleLocn mod_name (path ++ '/':basename) (Just file)
1051
1052         src_timestamp
1053            <- case ml_hs_file location of 
1054                  Nothing     -> noHsFileErr mod_name
1055                  Just src_fn -> getModificationTime src_fn
1056
1057         return (ModSummary mod
1058                            location{ml_hspp_file=Just hspp_fn}
1059                            srcimps imps src_timestamp)
1060
1061 -- Summarise a module, and pick up source and timestamp.
1062 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1063          -> IO (Maybe ModSummary)
1064 summarise mod location old_summary
1065    | not (isHomeModule mod) = return Nothing
1066    | otherwise
1067    = do let hs_fn = unJust "summarise" (ml_hs_file location)
1068
1069         case ml_hs_file location of {
1070            Nothing -> do {
1071                 dflags <- getDynFlags;
1072                 when (verbosity dflags >= 1) $
1073                     hPutStrLn stderr ("WARNING: module `" ++ 
1074                         moduleUserString mod ++ "' has no source file.");
1075                 return Nothing;
1076              };
1077
1078            Just src_fn -> do
1079
1080         src_timestamp <- getModificationTime src_fn
1081
1082         -- return the cached summary if the source didn't change
1083         case old_summary of {
1084            Just s | ms_hs_date s == src_timestamp -> return (Just s);
1085            _ -> do
1086
1087         hspp_fn <- preprocess hs_fn
1088         (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1089
1090         when (mod_name /= moduleName mod) $
1091                 throwDyn (ProgramError 
1092                    (showSDoc (text hs_fn
1093                               <>  text ": file name does not match module name"
1094                               <+> quotes (ppr (moduleName mod)))))
1095
1096         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1097                                  srcimps imps src_timestamp))
1098         }
1099       }
1100
1101
1102 noHsFileErr mod
1103   = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1104
1105 packageModErr mod
1106   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1107                                    quotes (ppr mod) <+>
1108                                    text "is a package module")))
1109 \end{code}