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