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