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