[project @ 2001-03-15 11:26:27 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, NamedThing(..) )
41 import NameEnv
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_inc_me
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             reachable_only = filter (/= (name_of_summary summary1)) 
817                                 reachable_inc_me
818
819            -- in interactive mode, all home modules below us *must* have an
820            -- interface in the HIT.  We never demand-load home interfaces in
821            -- interactive mode.
822             (hst1_strictDC, hit1_strictDC)
823                = ASSERT(ghci_mode == Batch || 
824                         all (`elemUFM` hit1) reachable_only)
825                  retainInTopLevelEnvs reachable_only (hst1,hit1)
826
827             old_linkable 
828                = unJust "upsweep_mod:old_linkable" maybe_old_linkable
829
830             have_object 
831                | Just l <- maybe_old_linkable, isObjectLinkable l = True
832                | otherwise = False
833
834         compresult <- compile ghci_mode summary1 source_unchanged
835                          have_object old_iface hst1_strictDC hit1_strictDC pcs1
836
837         case compresult of
838
839            -- Compilation "succeeded", and may or may not have returned a new
840            -- linkable (depending on whether compilation was actually performed
841            -- or not).
842            CompOK pcs2 new_details new_iface maybe_new_linkable
843               -> do let hst2      = addToUFM hst1 mod_name new_details
844                         hit2      = addToUFM hit1 mod_name new_iface
845                         threaded2 = CmThreaded pcs2 hst2 hit2
846
847                     return (threaded2, if isJust maybe_new_linkable
848                                           then maybe_new_linkable
849                                           else Just old_linkable)
850
851            -- Compilation failed.  compile may still have updated
852            -- the PCS, tho.
853            CompErrs pcs2
854               -> do let threaded2 = CmThreaded pcs2 hst1 hit1
855                     return (threaded2, Nothing)
856
857 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
858 removeFromTopLevelEnvs :: [ModuleName]
859                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
860                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
861 removeFromTopLevelEnvs zap_these (hst, hit, ui)
862    = (delListFromUFM hst zap_these,
863       delListFromUFM hit zap_these,
864       filterModuleLinkables (`notElem` zap_these) ui
865      )
866
867 retainInTopLevelEnvs :: [ModuleName]
868                         -> (HomeSymbolTable, HomeIfaceTable)
869                         -> (HomeSymbolTable, HomeIfaceTable)
870 retainInTopLevelEnvs keep_these (hst, hit)
871    = (retainInUFM hst keep_these,
872       retainInUFM hit keep_these
873      )
874      where
875         retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
876         retainInUFM ufm keys_to_keep
877            = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
878         maybeLookupUFM ufm u 
879            = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)] 
880
881 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
882 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
883 downwards_closure_of_module summaries root
884    = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
885          toEdge summ = (name_of_summary summ, ms_allimps summ)
886          res = simple_transitive_closure (map toEdge summaries) [root]             
887      in
888          --trace (showSDoc (text "DC of mod" <+> ppr root
889          --                 <+> text "=" <+> ppr res)) (
890          res
891          --)
892
893 -- Calculate transitive closures from a set of roots given an adjacency list
894 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
895 simple_transitive_closure graph set 
896    = let set2      = nub (concatMap dsts set ++ set)
897          dsts node = fromMaybe [] (lookup node graph)
898      in
899          if   length set == length set2
900          then set
901          else simple_transitive_closure graph set2
902
903
904 -- Calculate SCCs of the module graph, with or without taking into
905 -- account source imports.
906 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
907 topological_sort include_source_imports summaries
908    = let 
909          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
910          toEdge summ
911              = (summ, name_of_summary summ, 
912                       (if include_source_imports 
913                        then ms_srcimps summ else []) ++ ms_imps summ)
914         
915          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
916          mash_edge (summ, m, m_imports)
917             = case lookup m key_map of
918                  Nothing -> panic "reverse_topological_sort"
919                  Just mk -> (summ, mk, 
920                                 -- ignore imports not from the home package
921                                 catMaybes (map (flip lookup key_map) m_imports))
922
923          edges     = map toEdge summaries
924          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
925          scc_input = map mash_edge edges
926          sccs      = stronglyConnComp scc_input
927      in
928          sccs
929
930
931 -- Chase downwards from the specified root set, returning summaries
932 -- for all home modules encountered.  Only follow source-import
933 -- links.  Also returns a Bool to indicate whether any of the roots
934 -- are module Main.
935 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
936 downsweep rootNm old_summaries
937    = do rootSummaries <- mapM getRootSummary rootNm
938         let a_root_is_Main 
939                = any ((=="Main").moduleNameUserString.name_of_summary) 
940                      rootSummaries
941         all_summaries
942            <- loop (concat (map ms_imps rootSummaries))
943                 (filter (isHomeModule.ms_mod) rootSummaries)
944         return (all_summaries, a_root_is_Main)
945      where
946         getRootSummary :: FilePath -> IO ModSummary
947         getRootSummary file
948            | haskellish_file file
949            = do exists <- doesFileExist file
950                 if exists then summariseFile file else do
951                 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))      
952            | otherwise
953            = do exists <- doesFileExist hs_file
954                 if exists then summariseFile hs_file else do
955                 exists <- doesFileExist lhs_file
956                 if exists then summariseFile lhs_file else do
957                 getSummary (mkModuleName file)
958            where 
959                  hs_file = file ++ ".hs"
960                  lhs_file = file ++ ".lhs"
961
962         getSummary :: ModuleName -> IO ModSummary
963         getSummary nm
964            = do found <- findModule nm
965                 case found of
966                    Just (mod, location) -> do
967                         let old_summary = findModInSummaries old_summaries mod
968                         new_summary <- summarise mod location old_summary
969                         case new_summary of
970                            Nothing -> return (fromJust old_summary)
971                            Just s  -> return s
972
973                    Nothing -> throwDyn (OtherError 
974                                    ("can't find module `" 
975                                      ++ showSDoc (ppr nm) ++ "'"))
976                                  
977         -- loop invariant: home_summaries doesn't contain package modules
978         loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
979         loop [] home_summaries = return home_summaries
980         loop imps home_summaries
981            = do -- all modules currently in homeSummaries
982                 let all_home = map (moduleName.ms_mod) home_summaries
983
984                 -- imports for modules we don't already have
985                 let needed_imps = nub (filter (`notElem` all_home) imps)
986
987                 -- summarise them
988                 needed_summaries <- mapM getSummary needed_imps
989
990                 -- get just the "home" modules
991                 let new_home_summaries
992                        = filter (isHomeModule.ms_mod) needed_summaries
993
994                 -- loop, checking the new imports
995                 let new_imps = concat (map ms_imps new_home_summaries)
996                 loop new_imps (new_home_summaries ++ home_summaries)
997
998 -----------------------------------------------------------------------------
999 -- Summarising modules
1000
1001 -- We have two types of summarisation:
1002 --
1003 --    * Summarise a file.  This is used for the root module passed to
1004 --      cmLoadModule.  The file is read, and used to determine the root
1005 --      module name.  The module name may differ from the filename.
1006 --
1007 --    * Summarise a module.  We are given a module name, and must provide
1008 --      a summary.  The finder is used to locate the file in which the module
1009 --      resides.
1010
1011 summariseFile :: FilePath -> IO ModSummary
1012 summariseFile file
1013    = do hspp_fn <- preprocess file
1014         modsrc <- readFile hspp_fn
1015
1016         let (srcimps,imps,mod_name) = getImports modsrc
1017             (path, basename, ext) = splitFilename3 file
1018
1019         Just (mod, location)
1020            <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1021            
1022         maybe_src_timestamp
1023            <- case ml_hs_file location of 
1024                  Nothing     -> return Nothing
1025                  Just src_fn -> maybe_getModificationTime src_fn
1026
1027         return (ModSummary mod
1028                            location{ml_hspp_file=Just hspp_fn}
1029                            srcimps imps
1030                            maybe_src_timestamp)
1031
1032 -- Summarise a module, and pick up source and timestamp.
1033 summarise :: Module -> ModuleLocation -> Maybe ModSummary 
1034     -> IO (Maybe ModSummary)
1035 summarise mod location old_summary
1036    | isHomeModule mod
1037    = do let hs_fn = unJust "summarise" (ml_hs_file location)
1038
1039         maybe_src_timestamp
1040            <- case ml_hs_file location of 
1041                  Nothing     -> return Nothing
1042                  Just src_fn -> maybe_getModificationTime src_fn
1043
1044         -- return the cached summary if the source didn't change
1045         case old_summary of {
1046            Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
1047            _ -> do
1048
1049         hspp_fn <- preprocess hs_fn
1050         modsrc <- readFile hspp_fn
1051         let (srcimps,imps,mod_name) = getImports modsrc
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         when (mod_name /= moduleName mod) $
1059                 throwDyn (OtherError 
1060                    (showSDoc (text "file name does not match module name: "
1061                               <+> ppr (moduleName mod) <+> text "vs" 
1062                               <+> ppr mod_name)))
1063
1064         return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn} 
1065                                  srcimps imps
1066                                  maybe_src_timestamp))
1067         }
1068
1069    | otherwise
1070    = return (Just (ModSummary mod location [] [] Nothing))
1071
1072 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
1073 maybe_getModificationTime fn
1074    = (do time <- getModificationTime fn
1075          return (Just time)) 
1076      `catch`
1077      (\err -> return Nothing)
1078 \end{code}