[project @ 2005-03-31 15:16:53 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / GHC.hs
1 -- -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2005
4 --
5 -- The GHC API
6 --
7 -- -----------------------------------------------------------------------------
8
9 module GHC (
10         -- * Initialisation
11         Session,
12         defaultErrorHandler,
13         defaultCleanupHandler,
14         init,
15         newSession,
16
17         -- * Flags and settings
18         DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
19         parseDynamicFlags,
20         getSessionDynFlags,
21         setSessionDynFlags,
22         setMsgHandler,
23
24         -- * Targets
25         Target(..), TargetId(..),
26         setTargets,
27         getTargets,
28         addTarget,
29         removeTarget,
30         guessTarget,
31         
32         -- * Loading\/compiling the program
33         depanal,
34         load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
35         workingDirectoryChanged,
36         checkModule, CheckedModule(..),
37
38         -- * Inspecting the module structure of the program
39         ModuleGraph, ModSummary(..),
40         getModuleGraph,
41         isLoaded,
42         topSortModuleGraph,
43
44         -- * Interactive evaluation
45         getBindings, getPrintUnqual,
46 #ifdef GHCI
47         setContext, getContext, 
48         moduleIsInterpreted,
49         getInfo, GetInfoResult,
50         exprType,
51         typeKind,
52         lookupName,
53         RunResult(..),
54         runStmt,
55         browseModule,
56         showModule,
57         compileExpr, HValue,
58 #endif
59
60         -- * Abstract syntax elements
61         Module, mkModule, pprModule,
62         Type, dropForAlls,
63         Kind,
64         Name, Id, TyCon, Class, DataCon,
65         TyThing(..), 
66         idType,
67
68         -- used by DriverMkDepend:
69         sessionHscEnv,
70         cyclicModuleErr,
71   ) where
72
73 {-
74  ToDo:
75
76   * return error messages rather than printing them.
77   * inline bits of HscMain here to simplify layering: hscGetInfo,
78     hscTcExpr, hscStmt.
79   * implement second argument to load.
80   * we need to expose DynFlags, so should parseDynamicFlags really be
81     part of this interface?
82   * what StaticFlags should we expose, if any?
83 -}
84
85 #include "HsVersions.h"
86
87 #ifdef GHCI
88 import qualified Linker
89 import Linker           ( HValue, extendLinkEnv )
90 import NameEnv          ( lookupNameEnv )
91 import TcRnDriver       ( mkExportEnv, getModuleContents )
92 import RdrName          ( GlobalRdrEnv, plusGlobalRdrEnv )
93 import HscMain          ( hscGetInfo, GetInfoResult, 
94                           hscStmt, hscTcExpr, hscKcType )
95 import Type             ( tidyType )
96 import VarEnv           ( emptyTidyEnv )
97 import GHC.Exts         ( unsafeCoerce# )
98 import IfaceSyn         ( IfaceDecl )
99 #endif
100
101 import HsSyn            ( HsModule, LHsBinds )
102 import Type             ( Kind, Type, dropForAlls )
103 import Id               ( Id, idType )
104 import TyCon            ( TyCon )
105 import Class            ( Class )
106 import DataCon          ( DataCon )
107 import Name             ( Name )
108 import RdrName          ( RdrName )
109 import NameEnv          ( nameEnvElts )
110 import SrcLoc           ( Located )
111 import DriverPipeline
112 import DriverPhases     ( Phase(..), isHaskellSrcFilename, startPhase )
113 import GetImports       ( getImports )
114 import Packages         ( isHomePackage )
115 import Finder
116 import HscMain          ( newHscEnv, hscFileCheck, HscResult(..) )
117 import HscTypes
118 import DynFlags
119 import StaticFlags
120 import SysTools         ( initSysTools, cleanTempFiles )
121 import Module
122 import FiniteMap
123 import Panic
124 import Digraph
125 import ErrUtils         ( showPass, Messages )
126 import qualified ErrUtils
127 import Util
128 import StringBuffer     ( StringBuffer(..), hGetStringBuffer, lexemeToString )
129 import Outputable
130 import SysTools         ( cleanTempFilesExcept )
131 import BasicTypes       ( SuccessFlag(..), succeeded, failed )
132 import Maybes           ( orElse, expectJust, mapCatMaybes )
133
134 import Directory        ( getModificationTime, doesFileExist )
135 import Maybe            ( isJust, isNothing, fromJust )
136 import Maybes           ( expectJust )
137 import List             ( partition, nub )
138 import qualified List
139 import Monad            ( unless, when, foldM )
140 import System           ( exitWith, ExitCode(..) )
141 import Time             ( ClockTime )
142 import EXCEPTION as Exception hiding (handle)
143 import GLAEXTS          ( Int(..) )
144 import DATA_IOREF
145 import IO
146 import Prelude hiding (init)
147
148 -- -----------------------------------------------------------------------------
149 -- Exception handlers
150
151 -- | Install some default exception handlers and run the inner computation.
152 -- Unless you want to handle exceptions yourself, you should wrap this around
153 -- the top level of your program.  The default handlers output the error
154 -- message(s) to stderr and exit cleanly.
155 defaultErrorHandler :: IO a -> IO a
156 defaultErrorHandler inner = 
157   -- top-level exception handler: any unrecognised exception is a compiler bug.
158   handle (\exception -> do
159            hFlush stdout
160            case exception of
161                 -- an IO exception probably isn't our fault, so don't panic
162                 IOException _ ->  hPutStrLn stderr (show exception)
163                 AsyncException StackOverflow ->
164                         hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
165                 _other ->  hPutStr stderr (show (Panic (show exception)))
166            exitWith (ExitFailure 1)
167          ) $
168
169   -- all error messages are propagated as exceptions
170   handleDyn (\dyn -> do
171                 hFlush stdout
172                 case dyn of
173                      PhaseFailed _ code -> exitWith code
174                      Interrupted -> exitWith (ExitFailure 1)
175                      _ -> do hPutStrLn stderr (show (dyn :: GhcException))
176                              exitWith (ExitFailure 1)
177             ) $
178   inner
179
180 -- | Install a default cleanup handler to remove temporary files
181 -- deposited by a GHC run.  This is seperate from
182 -- 'defaultErrorHandler', because you might want to override the error
183 -- handling, but still get the ordinary cleanup behaviour.
184 defaultCleanupHandler :: DynFlags -> IO a -> IO a
185 defaultCleanupHandler dflags inner = 
186    -- make sure we clean up after ourselves
187    later (unless (dopt Opt_KeepTmpFiles dflags) $ 
188             cleanTempFiles dflags) 
189         -- exceptions will be blocked while we clean the temporary files,
190         -- so there shouldn't be any difficulty if we receive further
191         -- signals.
192    inner
193
194
195 -- | Initialises GHC.  This must be done /once/ only.  Takes the
196 -- command-line arguments.  All command-line arguments which aren't
197 -- understood by GHC will be returned.
198
199 init :: [String] -> IO [String]
200 init args = do
201    -- catch ^C
202    installSignalHandlers
203
204    -- Grab the -B option if there is one
205    let (minusB_args, argv1) = partition (prefixMatch "-B") args
206    dflags0 <- initSysTools minusB_args defaultDynFlags
207    writeIORef v_initDynFlags dflags0
208
209    -- Parse the static flags
210    argv2 <- parseStaticFlags argv1
211    return argv2
212
213 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
214         -- stores the DynFlags between the call to init and subsequent
215         -- calls to newSession.
216
217 -- | Starts a new session.  A session consists of a set of loaded
218 -- modules, a set of options (DynFlags), and an interactive context.
219 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
220 -- code".
221 newSession :: GhcMode -> IO Session
222 newSession mode = do
223   dflags0 <- readIORef v_initDynFlags
224   dflags <- initDynFlags dflags0
225   env <- newHscEnv dflags{ ghcMode=mode }
226   ref <- newIORef env
227   return (Session ref)
228
229 -- tmp: this breaks the abstraction, but required because DriverMkDepend
230 -- needs to call the Finder.  ToDo: untangle this.
231 sessionHscEnv :: Session -> IO HscEnv
232 sessionHscEnv (Session ref) = readIORef ref
233
234 withSession :: Session -> (HscEnv -> IO a) -> IO a
235 withSession (Session ref) f = do h <- readIORef ref; f h
236
237 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
238 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
239
240 -- -----------------------------------------------------------------------------
241 -- Flags & settings
242
243 -- | Grabs the DynFlags from the Session
244 getSessionDynFlags :: Session -> IO DynFlags
245 getSessionDynFlags s = withSession s (return . hsc_dflags)
246
247 -- | Updates the DynFlags in a Session
248 setSessionDynFlags :: Session -> DynFlags -> IO ()
249 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
250
251 -- | Messages during compilation (eg. warnings and progress messages)
252 -- are reported using this callback.  By default, these messages are
253 -- printed to stderr.
254 setMsgHandler :: (String -> IO ()) -> IO ()
255 setMsgHandler = ErrUtils.setMsgHandler
256
257 -- -----------------------------------------------------------------------------
258 -- Targets
259
260 -- ToDo: think about relative vs. absolute file paths. And what
261 -- happens when the current directory changes.
262
263 -- | Sets the targets for this session.  Each target may be a module name
264 -- or a filename.  The targets correspond to the set of root modules for
265 -- the program\/library.  Unloading the current program is achieved by
266 -- setting the current set of targets to be empty, followed by load.
267 setTargets :: Session -> [Target] -> IO ()
268 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
269
270 -- | returns the current set of targets
271 getTargets :: Session -> IO [Target]
272 getTargets s = withSession s (return . hsc_targets)
273
274 -- | Add another target
275 addTarget :: Session -> Target -> IO ()
276 addTarget s target
277   = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
278
279 -- | Remove a target
280 removeTarget :: Session -> TargetId -> IO ()
281 removeTarget s target_id
282   = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
283   where
284    filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
285
286 -- Attempts to guess what Target a string refers to.  This function implements
287 -- the --make/GHCi command-line syntax for filenames: 
288 --
289 --      - if the string looks like a Haskell source filename, then interpret
290 --        it as such
291 --      - if adding a .hs or .lhs suffix yields the name of an existing file,
292 --        then use that
293 --      - otherwise interpret the string as a module name
294 --
295 guessTarget :: String -> IO Target
296 guessTarget file
297    | isHaskellSrcFilename file
298    = return (Target (TargetFile file) Nothing)
299    | otherwise
300    = do exists <- doesFileExist hs_file
301         if exists then return (Target (TargetFile hs_file) Nothing) else do
302         exists <- doesFileExist lhs_file
303         if exists then return (Target (TargetFile lhs_file) Nothing) else do
304         return (Target (TargetModule (mkModule file)) Nothing)
305      where 
306          hs_file = file ++ ".hs"
307          lhs_file = file ++ ".lhs"
308
309 -- -----------------------------------------------------------------------------
310 -- Loading the program
311
312 -- Perform a dependency analysis starting from the current targets
313 -- and update the session with the new module graph.
314 depanal :: Session -> [Module] -> IO ()
315 depanal (Session ref) excluded_mods = do
316   hsc_env <- readIORef ref
317   let
318          dflags  = hsc_dflags hsc_env
319          gmode   = ghcMode (hsc_dflags hsc_env)
320          targets = hsc_targets hsc_env
321          old_graph = hsc_mod_graph hsc_env
322         
323   showPass dflags "Chasing dependencies"
324   when (verbosity dflags >= 1 && gmode == BatchCompile) $
325                hPutStrLn stderr (showSDoc (hcat [
326                      text "Chasing modules from: ",
327                         hcat (punctuate comma (map pprTarget targets))]))
328
329   graph <- downsweep hsc_env old_graph excluded_mods
330   writeIORef ref hsc_env{ hsc_mod_graph=graph }
331
332 {-
333 -- | The result of load.
334 data LoadResult
335   = LoadOk      Errors  -- ^ all specified targets were loaded successfully.
336   | LoadFailed  Errors  -- ^ not all modules were loaded.
337
338 type Errors = [String]
339
340 data ErrMsg = ErrMsg { 
341         errMsgSeverity  :: Severity,  -- warning, error, etc.
342         errMsgSpans     :: [SrcSpan],
343         errMsgShortDoc  :: Doc,
344         errMsgExtraInfo :: Doc
345         }
346 -}
347
348 data LoadHowMuch
349    = LoadAllTargets
350    | LoadUpTo Module
351    | LoadDependenciesOf Module
352
353 -- | Try to load the program.  If a Module is supplied, then just
354 -- attempt to load up to this target.  If no Module is supplied,
355 -- then try to load all targets.
356 load :: Session -> LoadHowMuch -> IO SuccessFlag
357 load s@(Session ref) how_much
358    = do 
359         -- Dependency analysis first.  Note that this fixes the module graph:
360         -- even if we don't get a fully successful upsweep, the full module
361         -- graph is still retained in the Session.  We can tell which modules
362         -- were successfully loaded by inspecting the Session's HPT.
363         depanal s []
364
365         hsc_env <- readIORef ref
366
367         let hpt1      = hsc_HPT hsc_env
368         let dflags    = hsc_dflags hsc_env
369         let mod_graph = hsc_mod_graph hsc_env
370
371         let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
372         let verb      = verbosity dflags
373
374         -- The "bad" boot modules are the ones for which we have
375         -- B.hs-boot in the module graph, but no B.hs
376         -- The downsweep should have ensured this does not happen
377         -- (see msDeps)
378         let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
379             bad_boot_mods = [s        | s <- mod_graph, isBootSummary s,
380                                         not (ms_mod s `elem` all_home_mods)]
381         ASSERT( null bad_boot_mods ) return ()
382
383         -- mg2_with_srcimps drops the hi-boot nodes, returning a 
384         -- graph with cycles.  Among other things, it is used for
385         -- backing out partially complete cycles following a failed
386         -- upsweep, and for removing from hpt all the modules
387         -- not in strict downwards closure, during calls to compile.
388         let mg2_with_srcimps :: [SCC ModSummary]
389             mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
390
391             -- check the stability property for each module.
392             stable_mods@(stable_obj,stable_bco)
393                 | BatchCompile <- ghci_mode = ([],[])
394                 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
395
396             -- prune bits of the HPT which are definitely redundant now,
397             -- to save space.
398             pruned_hpt = pruneHomePackageTable hpt1 
399                                 (flattenSCCs mg2_with_srcimps)
400                                 stable_mods
401
402         evaluate pruned_hpt
403
404         when (verb >= 2) $
405             putStrLn (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
406                                 text "Stable BCO:" <+> ppr stable_bco))
407
408         -- Unload any modules which are going to be re-linked this time around.
409         let stable_linkables = [ linkable
410                                | m <- stable_obj++stable_bco,
411                                  Just hmi <- [lookupModuleEnv pruned_hpt m],
412                                  Just linkable <- [hm_linkable hmi] ]
413         unload hsc_env stable_linkables
414
415         -- We could at this point detect cycles which aren't broken by
416         -- a source-import, and complain immediately, but it seems better
417         -- to let upsweep_mods do this, so at least some useful work gets
418         -- done before the upsweep is abandoned.
419         --hPutStrLn stderr "after tsort:\n"
420         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
421
422         -- Now do the upsweep, calling compile for each module in
423         -- turn.  Final result is version 3 of everything.
424
425         -- Topologically sort the module graph, this time including hi-boot
426         -- nodes, and possibly just including the portion of the graph
427         -- reachable from the module specified in the 2nd argument to load.
428         -- This graph should be cycle-free.
429         -- If we're restricting the upsweep to a portion of the graph, we
430         -- also want to retain everything that is still stable.
431         let full_mg :: [SCC ModSummary]
432             full_mg    = topSortModuleGraph False mod_graph Nothing
433
434             maybe_top_mod = case how_much of
435                                 LoadUpTo m           -> Just m
436                                 LoadDependenciesOf m -> Just m
437                                 _                    -> Nothing
438
439             partial_mg0 :: [SCC ModSummary]
440             partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
441
442             -- LoadDependenciesOf m: we want the upsweep to stop just
443             -- short of the specified module (unless the specified module
444             -- is stable).
445             partial_mg
446                 | LoadDependenciesOf mod <- how_much
447                 = ASSERT( case last partial_mg0 of 
448                             AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
449                   List.init partial_mg0
450                 | otherwise
451                 = partial_mg0
452
453             stable_mg = 
454                 [ AcyclicSCC ms
455                 | AcyclicSCC ms <- full_mg,
456                   ms_mod ms `elem` stable_obj++stable_bco,
457                   ms_mod ms `notElem` [ ms_mod ms' | 
458                                         AcyclicSCC ms' <- partial_mg ] ]
459
460             mg = stable_mg ++ partial_mg
461
462         -- clean up between compilations
463         let cleanup = cleanTempFilesExcept dflags
464                           (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
465
466         (upsweep_ok, hsc_env1, modsUpswept)
467            <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
468                            pruned_hpt stable_mods cleanup mg
469
470         -- Make modsDone be the summaries for each home module now
471         -- available; this should equal the domain of hpt3.
472         -- Get in in a roughly top .. bottom order (hence reverse).
473
474         let modsDone = reverse modsUpswept
475
476         -- Try and do linking in some form, depending on whether the
477         -- upsweep was completely or only partially successful.
478
479         if succeeded upsweep_ok
480
481          then 
482            -- Easy; just relink it all.
483            do when (verb >= 2) $ 
484                  hPutStrLn stderr "Upsweep completely successful."
485
486               -- Clean up after ourselves
487               cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
488
489               -- Issue a warning for the confusing case where the user
490               -- said '-o foo' but we're not going to do any linking.
491               -- We attempt linking if either (a) one of the modules is
492               -- called Main, or (b) the user said -no-hs-main, indicating
493               -- that main() is going to come from somewhere else.
494               --
495               let ofile = outputFile dflags
496               let no_hs_main = dopt Opt_NoHsMain dflags
497               let mb_main_mod = mainModIs dflags
498               let 
499                 main_mod = mb_main_mod `orElse` "Main"
500                 a_root_is_Main 
501                     = any ((==main_mod).moduleUserString.ms_mod) 
502                           mod_graph
503                 do_linking = a_root_is_Main || no_hs_main
504
505               when (ghci_mode == BatchCompile && isJust ofile && not do_linking
506                      && verb > 0) $
507                  hPutStrLn stderr ("Warning: output was redirected with -o, " ++
508                                    "but no output will be generated\n" ++
509                                    "because there is no " ++ main_mod ++ " module.")
510
511               -- link everything together
512               linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
513
514               loadFinish Succeeded linkresult ref hsc_env1
515
516          else 
517            -- Tricky.  We need to back out the effects of compiling any
518            -- half-done cycles, both so as to clean up the top level envs
519            -- and to avoid telling the interactive linker to link them.
520            do when (verb >= 2) $
521                 hPutStrLn stderr "Upsweep partially successful."
522
523               let modsDone_names
524                      = map ms_mod modsDone
525               let mods_to_zap_names 
526                      = findPartiallyCompletedCycles modsDone_names 
527                           mg2_with_srcimps
528               let mods_to_keep
529                      = filter ((`notElem` mods_to_zap_names).ms_mod) 
530                           modsDone
531
532               let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep) 
533                                               (hsc_HPT hsc_env1)
534
535               -- Clean up after ourselves
536               cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
537
538               -- there should be no Nothings where linkables should be, now
539               ASSERT(all (isJust.hm_linkable) 
540                         (moduleEnvElts (hsc_HPT hsc_env))) do
541         
542               -- Link everything together
543               linkresult <- link ghci_mode dflags False hpt4
544
545               let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
546               loadFinish Failed linkresult ref hsc_env4
547
548 -- Finish up after a load.
549
550 -- If the link failed, unload everything and return.
551 loadFinish all_ok Failed ref hsc_env
552   = do unload hsc_env []
553        writeIORef ref $! discardProg hsc_env
554        return Failed
555
556 -- Empty the interactive context and set the module context to the topmost
557 -- newly loaded module, or the Prelude if none were loaded.
558 loadFinish all_ok Succeeded ref hsc_env
559   = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
560        return all_ok
561
562
563 -- Forget the current program, but retain the persistent info in HscEnv
564 discardProg :: HscEnv -> HscEnv
565 discardProg hsc_env
566   = hsc_env { hsc_mod_graph = emptyMG, 
567               hsc_IC = emptyInteractiveContext,
568               hsc_HPT = emptyHomePackageTable }
569
570 -- used to fish out the preprocess output files for the purposes of
571 -- cleaning up.  The preprocessed file *might* be the same as the
572 -- source file, but that doesn't do any harm.
573 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
574
575 -- -----------------------------------------------------------------------------
576 -- Check module
577
578 data CheckedModule = 
579   CheckedModule { parsedSource      :: ParsedSource,
580                   typecheckedSource :: Maybe TypecheckedSource
581                 }
582
583 type ParsedSource  = Located (HsModule RdrName)
584 type TypecheckedSource = (LHsBinds Id, GlobalRdrEnv)
585
586 -- | This is the way to get access to parsed and typechecked source code
587 -- for a module.  'checkModule' loads all the dependencies of the specified
588 -- module in the Session, and then attempts to typecheck the module.  If
589 -- successful, it returns the abstract syntax for the module.
590 checkModule :: Session -> Module -> (Messages -> IO ()) 
591         -> IO (Maybe CheckedModule)
592 checkModule session@(Session ref) mod msg_act = do
593         -- load up the dependencies first
594    r <- load session (LoadDependenciesOf mod)
595    if (failed r) then return Nothing else do
596
597         -- now parse & typecheck the module
598    hsc_env <- readIORef ref   
599    let mg  = hsc_mod_graph hsc_env
600    case [ ms | ms <- mg, ms_mod ms == mod ] of
601         [] -> return Nothing
602         (ms:_) -> do 
603            r <- hscFileCheck hsc_env msg_act ms
604            case r of
605                 HscFail -> 
606                    return Nothing
607                 HscChecked parsed tcd -> 
608                    return (Just (CheckedModule parsed tcd)   )
609
610 -----------------------------------------------------------------------------
611 -- Unloading
612
613 unload :: HscEnv -> [Linkable] -> IO ()
614 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
615   = case ghcMode (hsc_dflags hsc_env) of
616         BatchCompile -> return ()
617 #ifdef GHCI
618         Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
619 #else
620         Interactive -> panic "unload: no interpreter"
621 #endif
622         other -> panic "unload: strange mode"
623
624 -- -----------------------------------------------------------------------------
625 -- checkStability
626
627 {-
628   Stability tells us which modules definitely do not need to be recompiled.
629   There are two main reasons for having stability:
630   
631    - avoid doing a complete upsweep of the module graph in GHCi when
632      modules near the bottom of the tree have not changed.
633
634    - to tell GHCi when it can load object code: we can only load object code
635      for a module when we also load object code fo  all of the imports of the
636      module.  So we need to know that we will definitely not be recompiling
637      any of these modules, and we can use the object code.
638
639   NB. stability is of no importance to BatchCompile at all, only Interactive.
640   (ToDo: what about JustTypecheck?)
641
642   The stability check is as follows.  Both stableObject and
643   stableBCO are used during the upsweep phase later.
644
645   -------------------
646   stable m = stableObject m || stableBCO m
647
648   stableObject m = 
649         all stableObject (imports m)
650         && old linkable does not exist, or is == on-disk .o
651         && date(on-disk .o) > date(.hs)
652
653   stableBCO m =
654         all stable (imports m)
655         && date(BCO) > date(.hs)
656   -------------------    
657
658   These properties embody the following ideas:
659
660     - if a module is stable:
661         - if it has been compiled in a previous pass (present in HPT)
662           then it does not need to be compiled or re-linked.
663         - if it has not been compiled in a previous pass,
664           then we only need to read its .hi file from disk and
665           link it to produce a ModDetails.
666
667     - if a modules is not stable, we will definitely be at least
668       re-linking, and possibly re-compiling it during the upsweep.
669       All non-stable modules can (and should) therefore be unlinked
670       before the upsweep.
671
672     - Note that objects are only considered stable if they only depend
673       on other objects.  We can't link object code against byte code.
674 -}
675
676 checkStability
677         :: HomePackageTable             -- HPT from last compilation
678         -> [SCC ModSummary]             -- current module graph (cyclic)
679         -> [Module]                     -- all home modules
680         -> ([Module],                   -- stableObject
681             [Module])                   -- stableBCO
682
683 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
684   where
685    checkSCC (stable_obj, stable_bco) scc0
686      | stableObjects = (scc_mods ++ stable_obj, stable_bco)
687      | stableBCOs    = (stable_obj, scc_mods ++ stable_bco)
688      | otherwise     = (stable_obj, stable_bco)
689      where
690         scc = flattenSCC scc0
691         scc_mods = map ms_mod scc
692         home_module m   = m `elem` all_home_mods && m `notElem` scc_mods
693
694         scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
695             -- all imports outside the current SCC, but in the home pkg
696         
697         stable_obj_imps = map (`elem` stable_obj) scc_allimps
698         stable_bco_imps = map (`elem` stable_bco) scc_allimps
699
700         stableObjects = 
701            and stable_obj_imps
702            && all object_ok scc
703
704         stableBCOs = 
705            and (zipWith (||) stable_obj_imps stable_bco_imps)
706            && all bco_ok scc
707
708         object_ok ms
709           | Just t <- ms_obj_date ms  =  t >= ms_hs_date ms 
710                                          && same_as_prev t
711           | otherwise = False
712           where
713              same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
714                                 Nothing  -> True
715                                 Just hmi  | Just l <- hm_linkable hmi
716                                  -> isObjectLinkable l && t == linkableTime l
717                 -- why '>=' rather than '>' above?  If the filesystem stores
718                 -- times to the nearset second, we may occasionally find that
719                 -- the object & source have the same modification time, 
720                 -- especially if the source was automatically generated
721                 -- and compiled.  Using >= is slightly unsafe, but it matches
722                 -- make's behaviour.
723
724         bco_ok ms
725           = case lookupModuleEnv hpt (ms_mod ms) of
726                 Nothing  -> False
727                 Just hmi  | Just l <- hm_linkable hmi ->
728                         not (isObjectLinkable l) && 
729                         linkableTime l >= ms_hs_date ms
730
731 ms_allimps :: ModSummary -> [Module]
732 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
733
734 -- -----------------------------------------------------------------------------
735 -- Prune the HomePackageTable
736
737 -- Before doing an upsweep, we can throw away:
738 --
739 --   - For non-stable modules:
740 --      - all ModDetails, all linked code
741 --   - all unlinked code that is out of date with respect to
742 --     the source file
743 --
744 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
745 -- space at the end of the upsweep, because the topmost ModDetails of the
746 -- old HPT holds on to the entire type environment from the previous
747 -- compilation.
748
749 pruneHomePackageTable
750    :: HomePackageTable
751    -> [ModSummary]
752    -> ([Module],[Module])
753    -> HomePackageTable
754
755 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
756   = mapModuleEnv prune hpt
757   where prune hmi
758           | is_stable modl = hmi'
759           | otherwise      = hmi'{ hm_details = emptyModDetails }
760           where
761            modl = mi_module (hm_iface hmi)
762            hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
763                 = hmi{ hm_linkable = Nothing }
764                 | otherwise
765                 = hmi
766                 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
767
768         ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
769
770         is_stable m = m `elem` stable_obj || m `elem` stable_bco
771
772 -- -----------------------------------------------------------------------------
773
774 -- Return (names of) all those in modsDone who are part of a cycle
775 -- as defined by theGraph.
776 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
777 findPartiallyCompletedCycles modsDone theGraph
778    = chew theGraph
779      where
780         chew [] = []
781         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
782         chew ((CyclicSCC vs):rest)
783            = let names_in_this_cycle = nub (map ms_mod vs)
784                  mods_in_this_cycle  
785                     = nub ([done | done <- modsDone, 
786                                    done `elem` names_in_this_cycle])
787                  chewed_rest = chew rest
788              in 
789              if   notNull mods_in_this_cycle
790                   && length mods_in_this_cycle < length names_in_this_cycle
791              then mods_in_this_cycle ++ chewed_rest
792              else chewed_rest
793
794 -- -----------------------------------------------------------------------------
795 -- The upsweep
796
797 -- This is where we compile each module in the module graph, in a pass
798 -- from the bottom to the top of the graph.
799
800 -- There better had not be any cyclic groups here -- we check for them.
801
802 upsweep
803     :: HscEnv                   -- Includes initially-empty HPT
804     -> HomePackageTable         -- HPT from last time round (pruned)
805     -> ([Module],[Module])      -- stable modules (see checkStability)
806     -> IO ()                    -- How to clean up unwanted tmp files
807     -> [SCC ModSummary]         -- Mods to do (the worklist)
808     -> IO (SuccessFlag,
809            HscEnv,              -- With an updated HPT
810            [ModSummary])        -- Mods which succeeded
811
812 upsweep hsc_env old_hpt stable_mods cleanup
813      []
814    = return (Succeeded, hsc_env, [])
815
816 upsweep hsc_env old_hpt stable_mods cleanup
817      (CyclicSCC ms:_)
818    = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
819         return (Failed, hsc_env, [])
820
821 upsweep hsc_env old_hpt stable_mods cleanup
822      (AcyclicSCC mod:mods)
823    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
824         --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
825         --                     (moduleEnvElts (hsc_HPT hsc_env)))
826
827         mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
828
829         cleanup         -- Remove unwanted tmp files between compilations
830
831         case mb_mod_info of
832             Nothing -> return (Failed, hsc_env, [])
833             Just mod_info -> do 
834                 { let this_mod = ms_mod mod
835
836                         -- Add new info to hsc_env
837                       hpt1     = extendModuleEnv (hsc_HPT hsc_env) 
838                                         this_mod mod_info
839                       hsc_env1 = hsc_env { hsc_HPT = hpt1 }
840
841                         -- Space-saving: delete the old HPT entry
842                         -- for mod BUT if mod is a hs-boot
843                         -- node, don't delete it.  For the
844                         -- interface, the HPT entry is probaby for the
845                         -- main Haskell source file.  Deleting it
846                         -- would force .. (what?? --SDM)
847                       old_hpt1 | isBootSummary mod = old_hpt
848                                | otherwise = delModuleEnv old_hpt this_mod
849
850                 ; (restOK, hsc_env2, modOKs) 
851                         <- upsweep hsc_env1 old_hpt1 stable_mods cleanup mods
852                 ; return (restOK, hsc_env2, mod:modOKs)
853                 }
854
855
856 -- Compile a single module.  Always produce a Linkable for it if 
857 -- successful.  If no compilation happened, return the old Linkable.
858 upsweep_mod :: HscEnv
859             -> HomePackageTable
860             -> ([Module],[Module])
861             -> ModSummary
862             -> IO (Maybe HomeModInfo)   -- Nothing => Failed
863
864 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary
865    = do 
866         let 
867             this_mod    = ms_mod summary
868             mb_obj_date = ms_obj_date summary
869             obj_fn      = ml_obj_file (ms_location summary)
870             hs_date     = ms_hs_date summary
871
872             compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
873             compile_it  = upsweep_compile hsc_env old_hpt this_mod summary
874
875         case ghcMode (hsc_dflags hsc_env) of
876             BatchCompile ->
877                 case () of
878                    -- Batch-compilating is easy: just check whether we have
879                    -- an up-to-date object file.  If we do, then the compiler
880                    -- needs to do a recompilation check.
881                    _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
882                            linkable <- 
883                                 findObjectLinkable this_mod obj_fn obj_date
884                            compile_it (Just linkable)
885
886                      | otherwise ->
887                            compile_it Nothing
888
889             interactive ->
890                 case () of
891                     _ | is_stable_obj, isJust old_hmi ->
892                            return old_hmi
893                         -- object is stable, and we have an entry in the
894                         -- old HPT: nothing to do
895
896                       | is_stable_obj, isNothing old_hmi -> do
897                            linkable <-
898                                 findObjectLinkable this_mod obj_fn 
899                                         (expectJust "upseep1" mb_obj_date)
900                            compile_it (Just linkable)
901                         -- object is stable, but we need to load the interface
902                         -- off disk to make a HMI.
903
904                       | is_stable_bco -> 
905                            ASSERT(isJust old_hmi) -- must be in the old_hpt
906                            return old_hmi
907                         -- BCO is stable: nothing to do
908
909                       | Just hmi <- old_hmi,
910                         Just l <- hm_linkable hmi, not (isObjectLinkable l),
911                         linkableTime l >= ms_hs_date summary ->
912                            compile_it (Just l)
913                         -- we have an old BCO that is up to date with respect
914                         -- to the source: do a recompilation check as normal.
915
916                       | otherwise ->
917                           compile_it Nothing
918                         -- no existing code at all: we must recompile.
919                    where
920                     is_stable_obj = this_mod `elem` stable_obj
921                     is_stable_bco = this_mod `elem` stable_bco
922
923                     old_hmi = lookupModuleEnv old_hpt this_mod
924
925 -- Run hsc to compile a module
926 upsweep_compile hsc_env old_hpt this_mod summary mb_old_linkable = do
927   let
928         -- The old interface is ok if it's in the old HPT 
929         --      a) we're compiling a source file, and the old HPT
930         --      entry is for a source file
931         --      b) we're compiling a hs-boot file
932         -- Case (b) allows an hs-boot file to get the interface of its
933         -- real source file on the second iteration of the compilation
934         -- manager, but that does no harm.  Otherwise the hs-boot file
935         -- will always be recompiled
936
937         mb_old_iface 
938                 = case lookupModuleEnv old_hpt this_mod of
939                      Nothing                              -> Nothing
940                      Just hm_info | isBootSummary summary -> Just iface
941                                   | not (mi_boot iface)   -> Just iface
942                                   | otherwise             -> Nothing
943                                    where 
944                                      iface = hm_iface hm_info
945
946   compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
947
948   case compresult of
949         -- Compilation failed.  Compile may still have updated the PCS, tho.
950         CompErrs -> return Nothing
951
952         -- Compilation "succeeded", and may or may not have returned a new
953         -- linkable (depending on whether compilation was actually performed
954         -- or not).
955         CompOK new_details new_iface new_linkable
956               -> do let new_info = HomeModInfo { hm_iface = new_iface,
957                                                  hm_details = new_details,
958                                                  hm_linkable = new_linkable }
959                     return (Just new_info)
960
961
962 -- Filter modules in the HPT
963 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
964 retainInTopLevelEnvs keep_these hpt
965    = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
966                  | mod <- keep_these
967                  , let mb_mod_info = lookupModuleEnv hpt mod
968                  , isJust mb_mod_info ]
969
970 -- ---------------------------------------------------------------------------
971 -- Topological sort of the module graph
972
973 topSortModuleGraph
974           :: Bool               -- Drop hi-boot nodes? (see below)
975           -> [ModSummary]
976           -> Maybe Module
977           -> [SCC ModSummary]
978 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
979 --
980 -- Drop hi-boot nodes (first boolean arg)? 
981 --
982 --   False:     treat the hi-boot summaries as nodes of the graph,
983 --              so the graph must be acyclic
984 --
985 --   True:      eliminate the hi-boot nodes, and instead pretend
986 --              the a source-import of Foo is an import of Foo
987 --              The resulting graph has no hi-boot nodes, but can by cyclic
988
989 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
990   = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
991 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
992   = stronglyConnComp (map vertex_fn (reachable graph root))
993   where 
994         -- restrict the graph to just those modules reachable from
995         -- the specified module.  We do this by building a graph with
996         -- the full set of nodes, and determining the reachable set from
997         -- the specified node.
998         (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
999         (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1000         root 
1001           | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1002           | otherwise  = throwDyn (ProgramError "module does not exist")
1003
1004 moduleGraphNodes :: Bool -> [ModSummary]
1005   -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1006 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1007    where
1008         -- Drop hs-boot nodes by using HsSrcFile as the key
1009         hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1010                     | otherwise          = HsBootFile   
1011
1012         -- We use integers as the keys for the SCC algorithm
1013         nodes :: [(ModSummary, Int, [Int])]     
1014         nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)), 
1015                      out_edge_keys hs_boot_key (ms_srcimps s) ++
1016                      out_edge_keys HsSrcFile   (ms_imps s)    )
1017                 | s <- summaries
1018                 , not (isBootSummary s && drop_hs_boot_nodes) ]
1019                 -- Drop the hi-boot ones if told to do so
1020
1021         key_map :: NodeMap Int
1022         key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1023                            `zip` [1..])
1024
1025         lookup_key :: HscSource -> Module -> Maybe Int
1026         lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1027
1028         out_edge_keys :: HscSource -> [Module] -> [Int]
1029         out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1030                 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1031                 -- the IsBootInterface parameter True; else False
1032
1033
1034 type NodeKey   = (Module, HscSource)      -- The nodes of the graph are 
1035 type NodeMap a = FiniteMap NodeKey a      -- keyed by (mod, src_file_type) pairs
1036
1037 msKey :: ModSummary -> NodeKey
1038 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1039
1040 emptyNodeMap :: NodeMap a
1041 emptyNodeMap = emptyFM
1042
1043 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1044 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1045         
1046 nodeMapElts :: NodeMap a -> [a]
1047 nodeMapElts = eltsFM
1048
1049 -- -----------------------------------------------------------------
1050 -- The unlinked image
1051 -- 
1052 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1053 -- binaries (byte code or object code).  Even when it links bytecode
1054 -- it keeps the unlinked version so it can re-link it later without
1055 -- recompiling.
1056
1057 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1058
1059 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1060 findModuleLinkable_maybe lis mod
1061    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1062         []   -> Nothing
1063         [li] -> Just li
1064         many -> pprPanic "findModuleLinkable" (ppr mod)
1065
1066 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1067 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1068
1069 -----------------------------------------------------------------------------
1070 -- Downsweep (dependency analysis)
1071
1072 -- Chase downwards from the specified root set, returning summaries
1073 -- for all home modules encountered.  Only follow source-import
1074 -- links.
1075
1076 -- We pass in the previous collection of summaries, which is used as a
1077 -- cache to avoid recalculating a module summary if the source is
1078 -- unchanged.
1079 --
1080 -- The returned list of [ModSummary] nodes has one node for each home-package
1081 -- module, plus one for any hs-boot files.  The imports of these nodes 
1082 -- are all there, including the imports of non-home-package modules.
1083
1084 downsweep :: HscEnv
1085           -> [ModSummary]       -- Old summaries
1086           -> [Module]           -- Ignore dependencies on these; treat them as
1087                                 -- if they were package modules
1088           -> IO [ModSummary]
1089 downsweep hsc_env old_summaries excl_mods
1090    = do rootSummaries <- mapM getRootSummary roots
1091         checkDuplicates rootSummaries
1092         loop (concatMap msDeps rootSummaries) 
1093              (mkNodeMap rootSummaries)
1094      where
1095         roots = hsc_targets hsc_env
1096
1097         old_summary_map :: NodeMap ModSummary
1098         old_summary_map = mkNodeMap old_summaries
1099
1100         getRootSummary :: Target -> IO ModSummary
1101         getRootSummary (Target (TargetFile file) maybe_buf)
1102            = do exists <- doesFileExist file
1103                 if exists then summariseFile hsc_env file maybe_buf else do
1104                 throwDyn (CmdLineError ("can't find file: " ++ file))   
1105         getRootSummary (Target (TargetModule modl) maybe_buf)
1106            = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False 
1107                                            modl maybe_buf excl_mods
1108                 case maybe_summary of
1109                    Nothing -> packageModErr modl
1110                    Just s  -> return s
1111
1112         -- In a root module, the filename is allowed to diverge from the module
1113         -- name, so we have to check that there aren't multiple root files
1114         -- defining the same module (otherwise the duplicates will be silently
1115         -- ignored, leading to confusing behaviour).
1116         checkDuplicates :: [ModSummary] -> IO ()
1117         checkDuplicates summaries = mapM_ check summaries
1118           where check summ = 
1119                   case dups of
1120                         []     -> return ()
1121                         [_one] -> return ()
1122                         many   -> multiRootsErr modl many
1123                    where modl = ms_mod summ
1124                          dups = 
1125                            [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1126                            | summ' <- summaries, ms_mod summ' == modl ]
1127
1128         loop :: [(FilePath,Module,IsBootInterface)]
1129                         -- Work list: process these modules
1130              -> NodeMap ModSummary
1131                         -- Visited set
1132              -> IO [ModSummary]
1133                         -- The result includes the worklist, except
1134                         -- for those mentioned in the visited set
1135         loop [] done      = return (nodeMapElts done)
1136         loop ((cur_path, wanted_mod, is_boot) : ss) done 
1137           | key `elemFM` done = loop ss done
1138           | otherwise         = do { mb_s <- summarise hsc_env old_summary_map 
1139                                                  (Just cur_path) is_boot 
1140                                                  wanted_mod Nothing excl_mods
1141                                    ; case mb_s of
1142                                         Nothing -> loop ss done
1143                                         Just s  -> loop (msDeps s ++ ss) 
1144                                                         (addToFM done key s) }
1145           where
1146             key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1147
1148 msDeps :: ModSummary -> [(FilePath,             -- Importing module
1149                           Module,               -- Imported module
1150                           IsBootInterface)]      -- {-# SOURCE #-} import or not
1151 -- (msDeps s) returns the dependencies of the ModSummary s.
1152 -- A wrinkle is that for a {-# SOURCE #-} import we return
1153 --      *both* the hs-boot file
1154 --      *and* the source file
1155 -- as "dependencies".  That ensures that the list of all relevant
1156 -- modules always contains B.hs if it contains B.hs-boot.
1157 -- Remember, this pass isn't doing the topological sort.  It's
1158 -- just gathering the list of all relevant ModSummaries
1159 msDeps s =  concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s] 
1160          ++ [(f,m,False) | m <- ms_imps    s] 
1161         where
1162           f = msHsFilePath s    -- Keep the importing module for error reporting
1163
1164
1165 -----------------------------------------------------------------------------
1166 -- Summarising modules
1167
1168 -- We have two types of summarisation:
1169 --
1170 --    * Summarise a file.  This is used for the root module(s) passed to
1171 --      cmLoadModules.  The file is read, and used to determine the root
1172 --      module name.  The module name may differ from the filename.
1173 --
1174 --    * Summarise a module.  We are given a module name, and must provide
1175 --      a summary.  The finder is used to locate the file in which the module
1176 --      resides.
1177
1178 summariseFile :: HscEnv -> FilePath
1179    -> Maybe (StringBuffer,ClockTime)
1180    -> IO ModSummary
1181 -- Used for Haskell source only, I think
1182 -- We know the file name, and we know it exists,
1183 -- but we don't necessarily know the module name (might differ)
1184 summariseFile hsc_env file maybe_buf
1185    = do let dflags = hsc_dflags hsc_env
1186
1187         (dflags', hspp_fn, buf)
1188             <- preprocessFile dflags file maybe_buf
1189
1190         (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1191
1192         -- Make a ModLocation for this file
1193         location <- mkHomeModLocation dflags mod file
1194
1195         -- Tell the Finder cache where it is, so that subsequent calls
1196         -- to findModule will find it, even if it's not on any search path
1197         addHomeModuleToFinder hsc_env mod location
1198
1199         src_timestamp <- case maybe_buf of
1200                            Just (_,t) -> return t
1201                            Nothing    -> getModificationTime file
1202
1203         obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1204
1205         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1206                              ms_location = location,
1207                              ms_hspp_file = Just hspp_fn,
1208                              ms_hspp_buf  = Just buf,
1209                              ms_srcimps = srcimps, ms_imps = the_imps,
1210                              ms_hs_date = src_timestamp,
1211                              ms_obj_date = obj_timestamp })
1212
1213 -- Summarise a module, and pick up source and timestamp.
1214 summarise :: HscEnv
1215           -> NodeMap ModSummary -- Map of old summaries
1216           -> Maybe FilePath     -- Importing module (for error messages)
1217           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1218           -> Module             -- Imported module to be summarised
1219           -> Maybe (StringBuffer, ClockTime)
1220           -> [Module]           -- Modules to exclude
1221           -> IO (Maybe ModSummary)      -- Its new summary
1222
1223 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1224   | wanted_mod `elem` excl_mods
1225   = return Nothing
1226
1227   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1228   = do          -- Find its new timestamp; all the 
1229                 -- ModSummaries in the old map have valid ml_hs_files
1230         let location = ms_location old_summary
1231             src_fn = expectJust "summarise" (ml_hs_file location)
1232
1233                 -- return the cached summary if the source didn't change
1234         src_timestamp <- case maybe_buf of
1235                            Just (_,t) -> return t
1236                            Nothing    -> getModificationTime src_fn
1237
1238         if ms_hs_date old_summary == src_timestamp 
1239            then do -- update the object-file timestamp
1240                   obj_timestamp <- getObjTimestamp location is_boot
1241                   return (Just old_summary{ ms_obj_date = obj_timestamp })
1242            else
1243                 -- source changed: re-summarise
1244                 new_summary location src_fn maybe_buf src_timestamp
1245
1246   | otherwise
1247   = do  found <- findModule hsc_env wanted_mod True {-explicit-}
1248         case found of
1249              Found location pkg 
1250                 | not (isHomePackage pkg) -> return Nothing
1251                         -- Drop external-pkg
1252                 | isJust (ml_hs_file location) -> just_found location
1253                         -- Home package
1254              err -> noModError dflags cur_mod wanted_mod err
1255                         -- Not found
1256   where
1257     dflags = hsc_dflags hsc_env
1258
1259     hsc_src = if is_boot then HsBootFile else HsSrcFile
1260
1261     just_found location = do
1262                 -- Adjust location to point to the hs-boot source file, 
1263                 -- hi file, object file, when is_boot says so
1264         let location' | is_boot   = addBootSuffixLocn location
1265                       | otherwise = location
1266             src_fn = expectJust "summarise2" (ml_hs_file location')
1267
1268                 -- Check that it exists
1269                 -- It might have been deleted since the Finder last found it
1270         maybe_t <- modificationTimeIfExists src_fn
1271         case maybe_t of
1272           Nothing -> noHsFileErr cur_mod src_fn
1273           Just t  -> new_summary location' src_fn Nothing t
1274
1275
1276     new_summary location src_fn maybe_bug src_timestamp
1277       = do
1278         -- Preprocess the source file and get its imports
1279         -- The dflags' contains the OPTIONS pragmas
1280         (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1281         (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1282
1283         when (mod_name /= wanted_mod) $
1284                 throwDyn (ProgramError 
1285                    (showSDoc (text src_fn
1286                               <>  text ": file name does not match module name"
1287                               <+> quotes (ppr mod_name))))
1288
1289                 -- Find the object timestamp, and return the summary
1290         obj_timestamp <- getObjTimestamp location is_boot
1291
1292         return (Just ( ModSummary { ms_mod       = wanted_mod, 
1293                                     ms_hsc_src   = hsc_src,
1294                                     ms_location  = location,
1295                                     ms_hspp_file = Just hspp_fn,
1296                                     ms_hspp_buf  = Just buf,
1297                                     ms_srcimps   = srcimps,
1298                                     ms_imps      = the_imps,
1299                                     ms_hs_date   = src_timestamp,
1300                                     ms_obj_date  = obj_timestamp }))
1301
1302
1303 getObjTimestamp location is_boot
1304   = if is_boot then return Nothing
1305                else modificationTimeIfExists (ml_obj_file location)
1306
1307
1308 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1309   -> IO (DynFlags, FilePath, StringBuffer)
1310 preprocessFile dflags src_fn Nothing
1311   = do
1312         (dflags', hspp_fn) <- preprocess dflags src_fn
1313         buf <- hGetStringBuffer hspp_fn
1314         return (dflags', hspp_fn, buf)
1315
1316 preprocessFile dflags src_fn (Just (buf, time))
1317   = do
1318         -- case we bypass the preprocessing stage?
1319         let 
1320             local_opts = getOptionsFromStringBuffer buf
1321         --
1322         (dflags', errs) <- parseDynamicFlags dflags local_opts
1323
1324         let
1325             needs_preprocessing
1326                 | Unlit _ <- startPhase src_fn  = True
1327                   -- note: local_opts is only required if there's no Unlit phase
1328                 | dopt Opt_Cpp dflags'          = True
1329                 | dopt Opt_Pp  dflags'          = True
1330                 | otherwise                     = False
1331
1332         when needs_preprocessing $
1333            ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1334
1335         return (dflags', "<buffer>", buf)
1336
1337
1338 -- code adapted from the file-based version in DriverUtil
1339 getOptionsFromStringBuffer :: StringBuffer -> [String]
1340 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) = 
1341   let 
1342         ls = lines (lexemeToString buffer (I# len#))  -- lazy, so it's ok
1343   in
1344   look ls
1345   where
1346         look [] = []
1347         look (l':ls) = do
1348             let l = removeSpaces l'
1349             case () of
1350                 () | null l -> look ls
1351                    | prefixMatch "#" l -> look ls
1352                    | prefixMatch "{-# LINE" l -> look ls   -- -}
1353                    | Just opts <- matchOptions l
1354                         -> opts ++ look ls
1355                    | otherwise -> []
1356
1357 -----------------------------------------------------------------------------
1358 --                      Error messages
1359 -----------------------------------------------------------------------------
1360
1361 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1362 -- ToDo: we don't have a proper line number for this error
1363 noModError dflags cur_mod wanted_mod err
1364   = throwDyn $ ProgramError $ showSDoc $
1365     vcat [cantFindError dflags wanted_mod err,
1366           nest 2 (parens (pp_where cur_mod))]
1367                                 
1368 noHsFileErr cur_mod path
1369   = throwDyn $ CmdLineError $ showSDoc $
1370     vcat [text "Can't find" <+> text path,
1371           nest 2 (parens (pp_where cur_mod))]
1372  
1373 pp_where Nothing  = text "one of the roots of the dependency analysis"
1374 pp_where (Just p) = text "imported from" <+> text p
1375
1376 packageModErr mod
1377   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1378                                    quotes (ppr mod) <+>
1379                                    text "is a package module")))
1380
1381 multiRootsErr mod files
1382   = throwDyn (ProgramError (showSDoc (
1383         text "module" <+> quotes (ppr mod) <+> 
1384         text "is defined in multiple files:" <+>
1385         sep (map text files))))
1386
1387 cyclicModuleErr :: [ModSummary] -> SDoc
1388 cyclicModuleErr ms
1389   = hang (ptext SLIT("Module imports form a cycle for modules:"))
1390        2 (vcat (map show_one ms))
1391   where
1392     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1393                         nest 2 $ ptext SLIT("imports:") <+> 
1394                                    (pp_imps HsBootFile (ms_srcimps ms)
1395                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
1396     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1397     pp_imps src mods = fsep (map (show_mod src) mods)
1398
1399
1400 -- | Inform GHC that the working directory has changed.  GHC will flush
1401 -- its cache of module locations, since it may no longer be valid.
1402 -- Note: if you change the working directory, you should also unload
1403 -- the current program (set targets to empty, followed by load).
1404 workingDirectoryChanged :: Session -> IO ()
1405 workingDirectoryChanged s = withSession s $ \hsc_env ->
1406   flushFinderCache (hsc_FC hsc_env)
1407
1408 -- -----------------------------------------------------------------------------
1409 -- inspecting the session
1410
1411 -- | Get the module dependency graph.
1412 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1413 getModuleGraph s = withSession s (return . hsc_mod_graph)
1414
1415 isLoaded :: Session -> Module -> IO Bool
1416 isLoaded s m = withSession s $ \hsc_env ->
1417   return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1418
1419 getBindings :: Session -> IO [TyThing]
1420 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1421
1422 getPrintUnqual :: Session -> IO PrintUnqualified
1423 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1424
1425 #if 0
1426 getModuleInfo :: Session -> Module -> IO ModuleInfo
1427
1428 data ObjectCode
1429   = ByteCode
1430   | BinaryCode FilePath
1431
1432 data ModuleInfo = ModuleInfo {
1433   lm_modulename :: Module,
1434   lm_summary    :: ModSummary,
1435   lm_interface  :: ModIface,
1436   lm_tc_code    :: Maybe TypecheckedCode,
1437   lm_rn_code    :: Maybe RenamedCode,
1438   lm_obj        :: Maybe ObjectCode
1439   }
1440
1441 type TypecheckedCode = HsTypecheckedGroup
1442 type RenamedCode     = [HsGroup Name]
1443
1444 -- ToDo: typechecks abstract syntax or renamed abstract syntax.  Issues:
1445 --   - typechecked syntax includes extra dictionary translation and
1446 --     AbsBinds which need to be translated back into something closer to
1447 --     the original source.
1448 --   - renamed syntax currently doesn't exist in a single blob, since
1449 --     renaming and typechecking are interleaved at splice points.  We'd
1450 --     need a restriction that there are no splices in the source module.
1451
1452 -- ToDo:
1453 --   - Data and Typeable instances for HsSyn.
1454
1455 -- ToDo:
1456 --   - things that aren't in the output of the renamer:
1457 --     - the export list
1458 --     - the imports
1459
1460 -- ToDo:
1461 --   - things that aren't in the output of the typechecker right now:
1462 --     - the export list
1463 --     - the imports
1464 --     - type signatures
1465 --     - type/data/newtype declarations
1466 --     - class declarations
1467 --     - instances
1468 --   - extra things in the typechecker's output:
1469 --     - default methods are turned into top-level decls.
1470 --     - dictionary bindings
1471
1472 -- ToDo: check for small transformations that happen to the syntax in
1473 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1474
1475 -- ToDo: maybe use TH syntax instead of IfaceSyn?  There's already a way
1476 -- to get from TyCons, Ids etc. to TH syntax (reify).
1477
1478 -- :browse will use either lm_toplev or inspect lm_interface, depending
1479 -- on whether the module is interpreted or not.
1480
1481 -- various abstract syntax types (perhaps IfaceBlah)
1482 data Type = ...
1483 data Kind = ...
1484
1485 -- This is for reconstructing refactored source code
1486 -- Calls the lexer repeatedly.
1487 -- ToDo: add comment tokens to token stream
1488 getTokenStream :: Session -> Module -> IO [Located Token]
1489 #endif
1490
1491 -- -----------------------------------------------------------------------------
1492 -- Interactive evaluation
1493
1494 #ifdef GHCI
1495
1496 -- | Set the interactive evaluation context.
1497 --
1498 -- Setting the context doesn't throw away any bindings; the bindings
1499 -- we've built up in the InteractiveContext simply move to the new
1500 -- module.  They always shadow anything in scope in the current context.
1501 setContext :: Session
1502            -> [Module]  -- entire top level scope of these modules
1503            -> [Module]  -- exports only of these modules
1504            -> IO ()
1505 setContext (Session ref) toplevs exports = do 
1506   hsc_env <- readIORef ref
1507   let old_ic  = hsc_IC     hsc_env
1508       hpt     = hsc_HPT    hsc_env
1509
1510   mapM_ (checkModuleExists hsc_env hpt) exports
1511   export_env  <- mkExportEnv hsc_env exports
1512   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1513   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1514   writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1515                                             ic_exports      = exports,
1516                                             ic_rn_gbl_env   = all_env } }
1517
1518 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1519 checkModuleExists hsc_env hpt mod = 
1520   case lookupModuleEnv hpt mod of
1521     Just mod_info -> return ()
1522     _not_a_home_module -> do
1523           res <- findPackageModule hsc_env mod True
1524           case res of
1525             Found _ _ -> return  ()
1526             err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1527                    throwDyn (CmdLineError (showSDoc msg))
1528
1529 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1530 mkTopLevEnv hpt modl
1531  = case lookupModuleEnv hpt modl of
1532       Nothing ->        
1533          throwDyn (ProgramError ("mkTopLevEnv: not a home module " 
1534                         ++ showSDoc (pprModule modl)))
1535       Just details ->
1536          case mi_globals (hm_iface details) of
1537                 Nothing  -> 
1538                    throwDyn (ProgramError ("mkTopLevEnv: not interpreted " 
1539                                                 ++ showSDoc (pprModule modl)))
1540                 Just env -> return env
1541
1542 -- | Get the interactive evaluation context, consisting of a pair of the
1543 -- set of modules from which we take the full top-level scope, and the set
1544 -- of modules from which we take just the exports respectively.
1545 getContext :: Session -> IO ([Module],[Module])
1546 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1547                                 return (ic_toplev_scope ic, ic_exports ic))
1548
1549 -- | Returns 'True' if the specified module is interpreted, and hence has
1550 -- its full top-level scope available.
1551 moduleIsInterpreted :: Session -> Module -> IO Bool
1552 moduleIsInterpreted s modl = withSession s $ \h ->
1553  case lookupModuleEnv (hsc_HPT h) modl of
1554       Just details       -> return (isJust (mi_globals (hm_iface details)))
1555       _not_a_home_module -> return False
1556
1557 -- | Looks up an identifier in the current interactive context (for :info)
1558 getInfo :: Session -> String -> IO [GetInfoResult]
1559 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1560
1561 -- -----------------------------------------------------------------------------
1562 -- Getting the type of an expression
1563
1564 -- | Get the type of an expression
1565 exprType :: Session -> String -> IO (Maybe Type)
1566 exprType s expr = withSession s $ \hsc_env -> do
1567    maybe_stuff <- hscTcExpr hsc_env expr
1568    case maybe_stuff of
1569         Nothing -> return Nothing
1570         Just ty -> return (Just tidy_ty)
1571              where 
1572                 tidy_ty = tidyType emptyTidyEnv ty
1573                 dflags  = hsc_dflags hsc_env
1574
1575 -- -----------------------------------------------------------------------------
1576 -- Getting the kind of a type
1577
1578 -- | Get the kind of a  type
1579 typeKind  :: Session -> String -> IO (Maybe Kind)
1580 typeKind s str = withSession s $ \hsc_env -> do
1581    maybe_stuff <- hscKcType hsc_env str
1582    case maybe_stuff of
1583         Nothing -> return Nothing
1584         Just kind -> return (Just kind)
1585
1586 -----------------------------------------------------------------------------
1587 -- lookupName: returns the TyThing for a Name in the interactive context.
1588 -- ToDo: should look it up in the full environment
1589
1590 lookupName :: Session -> Name -> IO (Maybe TyThing)
1591 lookupName s name = withSession s $ \hsc_env -> do
1592   return $! lookupNameEnv (ic_type_env (hsc_IC hsc_env)) name
1593
1594 -----------------------------------------------------------------------------
1595 -- cmCompileExpr: compile an expression and deliver an HValue
1596
1597 compileExpr :: Session -> String -> IO (Maybe HValue)
1598 compileExpr s expr = withSession s $ \hsc_env -> do
1599   maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1600   case maybe_stuff of
1601         Nothing -> return Nothing
1602         Just (new_ic, names, hval) -> do
1603                         -- Run it!
1604                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1605
1606                 case (names,hvals) of
1607                   ([n],[hv]) -> return (Just hv)
1608                   _          -> panic "compileExpr"
1609
1610 -- -----------------------------------------------------------------------------
1611 -- running a statement interactively
1612
1613 data RunResult
1614   = RunOk [Name]                -- ^ names bound by this evaluation
1615   | RunFailed                   -- ^ statement failed compilation
1616   | RunException Exception      -- ^ statement raised an exception
1617
1618 -- | Run a statement in the current interactive context.  Statemenet
1619 -- may bind multple values.
1620 runStmt :: Session -> String -> IO RunResult
1621 runStmt (Session ref) expr
1622    = do 
1623         hsc_env <- readIORef ref
1624
1625         -- Turn off -fwarn-unused-bindings when running a statement, to hide
1626         -- warnings about the implicit bindings we introduce.
1627         let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1628             hsc_env' = hsc_env{ hsc_dflags = dflags' }
1629
1630         maybe_stuff <- hscStmt hsc_env' expr
1631
1632         case maybe_stuff of
1633            Nothing -> return RunFailed
1634            Just (new_hsc_env, names, hval) -> do
1635
1636                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1637                 either_hvals <- sandboxIO thing_to_run
1638
1639                 case either_hvals of
1640                     Left e -> do
1641                         -- on error, keep the *old* interactive context,
1642                         -- so that 'it' is not bound to something
1643                         -- that doesn't exist.
1644                         return (RunException e)
1645
1646                     Right hvals -> do
1647                         -- Get the newly bound things, and bind them.  
1648                         -- Don't need to delete any shadowed bindings;
1649                         -- the new ones override the old ones. 
1650                         extendLinkEnv (zip names hvals)
1651                         
1652                         writeIORef ref new_hsc_env
1653                         return (RunOk names)
1654
1655
1656 -- We run the statement in a "sandbox" to protect the rest of the
1657 -- system from anything the expression might do.  For now, this
1658 -- consists of just wrapping it in an exception handler, but see below
1659 -- for another version.
1660
1661 sandboxIO :: IO a -> IO (Either Exception a)
1662 sandboxIO thing = Exception.try thing
1663
1664 {-
1665 -- This version of sandboxIO runs the expression in a completely new
1666 -- RTS main thread.  It is disabled for now because ^C exceptions
1667 -- won't be delivered to the new thread, instead they'll be delivered
1668 -- to the (blocked) GHCi main thread.
1669
1670 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1671
1672 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1673 sandboxIO thing = do
1674   st_thing <- newStablePtr (Exception.try thing)
1675   alloca $ \ p_st_result -> do
1676     stat <- rts_evalStableIO st_thing p_st_result
1677     freeStablePtr st_thing
1678     if stat == 1
1679         then do st_result <- peek p_st_result
1680                 result <- deRefStablePtr st_result
1681                 freeStablePtr st_result
1682                 return (Right result)
1683         else do
1684                 return (Left (fromIntegral stat))
1685
1686 foreign import "rts_evalStableIO"  {- safe -}
1687   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1688   -- more informative than the C type!
1689 -}
1690
1691 -- ---------------------------------------------------------------------------
1692 -- cmBrowseModule: get all the TyThings defined in a module
1693
1694 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1695 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1696   mb_decls <- getModuleContents hsc_env modl exports_only
1697   case mb_decls of
1698         Nothing -> return []            -- An error of some kind
1699         Just ds -> return ds
1700
1701
1702 -----------------------------------------------------------------------------
1703 -- show a module and it's source/object filenames
1704
1705 showModule :: Session -> ModSummary -> IO String
1706 showModule s mod_summary = withSession s $ \hsc_env -> do
1707   case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1708         Nothing       -> panic "missing linkable"
1709         Just mod_info -> return (showModMsg obj_linkable mod_summary)
1710                       where
1711                          obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))
1712
1713 #endif /* GHCI */