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