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