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