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