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