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