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