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