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