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