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