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