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