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