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