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