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