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