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