Various cleanups and improvements to the breakpoint support
[ghc-hetmet.git] / 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         newSession,
15
16         -- * Flags and settings
17         DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18         GhcMode(..), GhcLink(..),
19         parseDynamicFlags,
20         getSessionDynFlags,
21         setSessionDynFlags,
22
23         -- * Targets
24         Target(..), TargetId(..), Phase,
25         setTargets,
26         getTargets,
27         addTarget,
28         removeTarget,
29         guessTarget,
30         
31         -- * Extending the program scope 
32         extendGlobalRdrScope,  -- :: Session -> [GlobalRdrElt] -> IO ()
33         setGlobalRdrScope,     -- :: Session -> [GlobalRdrElt] -> IO ()
34         extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
35         setGlobalTypeScope,    -- :: Session -> [Id] -> IO ()
36
37         -- * Loading\/compiling the program
38         depanal,
39         load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
40         workingDirectoryChanged,
41         checkModule, CheckedModule(..),
42         TypecheckedSource, ParsedSource, RenamedSource,
43
44         -- * Parsing Haddock comments
45         parseHaddockComment,
46
47         -- * Inspecting the module structure of the program
48         ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
49         getModuleGraph,
50         isLoaded,
51         topSortModuleGraph,
52
53         -- * Inspecting modules
54         ModuleInfo,
55         getModuleInfo,
56         modInfoTyThings,
57         modInfoTopLevelScope,
58         modInfoPrintUnqualified,
59         modInfoExports,
60         modInfoInstances,
61         modInfoIsExportedName,
62         modInfoLookupName,
63         lookupGlobalName,
64
65         -- * Printing
66         PrintUnqualified, alwaysQualify,
67
68         -- * Interactive evaluation
69         getBindings, getPrintUnqual,
70         findModule,
71 #ifdef GHCI
72         setContext, getContext, 
73         getNamesInScope,
74         getRdrNamesInScope,
75         moduleIsInterpreted,
76         getInfo,
77         exprType,
78         typeKind,
79         parseName,
80         RunResult(..),  ResumeHandle,
81         runStmt,
82         resume,
83         showModule,
84         isModuleInterpreted,
85         compileExpr, HValue, dynCompileExpr,
86         lookupName,
87         obtainTerm, obtainTerm1,
88         ModBreaks(..), BreakIndex,
89         BreakInfo(breakInfo_number, breakInfo_module),
90         modInfoModBreaks, 
91 #endif
92
93         -- * Abstract syntax elements
94
95         -- ** Packages
96         PackageId,
97
98         -- ** Modules
99         Module, mkModule, pprModule, moduleName, modulePackageId,
100         ModuleName, mkModuleName, moduleNameString,
101
102         -- ** Names
103         Name, 
104         nameModule, pprParenSymName, nameSrcLoc,
105         NamedThing(..),
106         RdrName(Qual,Unqual),
107         
108         -- ** Identifiers
109         Id, idType,
110         isImplicitId, isDeadBinder,
111         isExportedId, isLocalId, isGlobalId,
112         isRecordSelector,
113         isPrimOpId, isFCallId, isClassOpId_maybe,
114         isDataConWorkId, idDataCon,
115         isBottomingId, isDictonaryId,
116         recordSelectorFieldLabel,
117
118         -- ** Type constructors
119         TyCon, 
120         tyConTyVars, tyConDataCons, tyConArity,
121         isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
122         isOpenTyCon,
123         synTyConDefn, synTyConType, synTyConResKind,
124
125         -- ** Type variables
126         TyVar,
127         alphaTyVars,
128
129         -- ** Data constructors
130         DataCon,
131         dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
132         dataConIsInfix, isVanillaDataCon,
133         dataConStrictMarks,  
134         StrictnessMark(..), isMarkedStrict,
135
136         -- ** Classes
137         Class, 
138         classMethods, classSCTheta, classTvsFds,
139         pprFundeps,
140
141         -- ** Instances
142         Instance, 
143         instanceDFunId, pprInstance, pprInstanceHdr,
144
145         -- ** Types and Kinds
146         Type, dropForAlls, splitForAllTys, funResultTy, 
147         pprParendType, pprTypeApp,
148         Kind,
149         PredType,
150         ThetaType, pprThetaArrow,
151
152         -- ** Entities
153         TyThing(..), 
154
155         -- ** Syntax
156         module HsSyn, -- ToDo: remove extraneous bits
157
158         -- ** Fixities
159         FixityDirection(..), 
160         defaultFixity, maxPrecedence, 
161         negateFixity,
162         compareFixity,
163
164         -- ** Source locations
165         SrcLoc, pprDefnLoc,
166
167         -- * Exceptions
168         GhcException(..), showGhcException,
169
170         -- * Miscellaneous
171         sessionHscEnv,
172         cyclicModuleErr,
173   ) where
174
175 {-
176  ToDo:
177
178   * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
179   * what StaticFlags should we expose, if any?
180 -}
181
182 #include "HsVersions.h"
183
184 #ifdef GHCI
185 import RtClosureInspect ( cvObtainTerm, Term )
186 import TcRnDriver       ( tcRnLookupRdrName, tcRnGetInfo,
187                           tcRnLookupName, getModuleExports )
188 import VarEnv           ( emptyTidyEnv )
189 import GHC.Exts         ( unsafeCoerce#, Ptr )
190 import Foreign.StablePtr( deRefStablePtr, StablePtr, newStablePtr, freeStablePtr )
191 import Foreign          ( poke )
192 import qualified Linker
193
194 import Data.Dynamic     ( Dynamic )
195 import Linker           ( HValue, getHValue, extendLinkEnv )
196
197 import ByteCodeInstr
198 import DebuggerTys
199 import IdInfo
200 import HscMain          ( hscParseIdentifier, hscTcExpr, hscKcType, hscStmt )
201 #endif
202
203 import Packages
204 import NameSet
205 import RdrName
206 import HsSyn 
207 import Type             hiding (typeKind)
208 import Id
209 import Var              hiding (setIdType)
210 import TysPrim          ( alphaTyVars )
211 import TyCon
212 import Class
213 import FunDeps
214 import DataCon
215 import Name             hiding ( varName )
216 import OccName          ( parenSymOcc )
217 import NameEnv
218 import InstEnv          ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
219 import SrcLoc
220 import DriverPipeline
221 import DriverPhases     ( Phase(..), isHaskellSrcFilename, startPhase )
222 import HeaderInfo       ( getImports, getOptions )
223 import Finder
224 import HscMain          ( newHscEnv, hscFileCheck, HscChecked(..) )
225 import HscTypes
226 import DynFlags
227 import SysTools     ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
228                       cleanTempDirs )
229 import Module
230 import UniqFM
231 import PackageConfig
232 import FiniteMap
233 import Panic
234 import Digraph
235 import Bag              ( unitBag, listToBag )
236 import ErrUtils         ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
237                           mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
238                           WarnMsg )
239 import qualified ErrUtils
240 import Util
241 import StringBuffer     ( StringBuffer, hGetStringBuffer )
242 import Outputable
243 import BasicTypes
244 import TcType           ( tcSplitSigmaTy, isDictTy )
245 import Maybes           ( expectJust, mapCatMaybes )
246 import HaddockParse
247 import HaddockLex       ( tokenise )
248
249 import Control.Concurrent
250 import System.Directory ( getModificationTime, doesFileExist )
251 import Data.Maybe
252 import Data.List
253 import qualified Data.List as List
254 import Control.Monad
255 import System.Exit      ( exitWith, ExitCode(..) )
256 import System.Time      ( ClockTime )
257 import Control.Exception as Exception hiding (handle)
258 import Data.IORef
259 import System.IO
260 import System.IO.Error  ( isDoesNotExistError )
261 import Prelude hiding (init)
262
263 #if __GLASGOW_HASKELL__ < 600
264 import System.IO as System.IO.Error ( try )
265 #else
266 import System.IO.Error  ( try )
267 #endif
268
269 -- -----------------------------------------------------------------------------
270 -- Exception handlers
271
272 -- | Install some default exception handlers and run the inner computation.
273 -- Unless you want to handle exceptions yourself, you should wrap this around
274 -- the top level of your program.  The default handlers output the error
275 -- message(s) to stderr and exit cleanly.
276 defaultErrorHandler :: DynFlags -> IO a -> IO a
277 defaultErrorHandler dflags inner = 
278   -- top-level exception handler: any unrecognised exception is a compiler bug.
279   handle (\exception -> do
280            hFlush stdout
281            case exception of
282                 -- an IO exception probably isn't our fault, so don't panic
283                 IOException _ ->
284                   fatalErrorMsg dflags (text (show exception))
285                 AsyncException StackOverflow ->
286                   fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
287                 _other ->
288                   fatalErrorMsg dflags (text (show (Panic (show exception))))
289            exitWith (ExitFailure 1)
290          ) $
291
292   -- program errors: messages with locations attached.  Sometimes it is
293   -- convenient to just throw these as exceptions.
294   handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
295                         exitWith (ExitFailure 1)) $
296
297   -- error messages propagated as exceptions
298   handleDyn (\dyn -> do
299                 hFlush stdout
300                 case dyn of
301                      PhaseFailed _ code -> exitWith code
302                      Interrupted -> exitWith (ExitFailure 1)
303                      _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
304                              exitWith (ExitFailure 1)
305             ) $
306   inner
307
308 -- | Install a default cleanup handler to remove temporary files
309 -- deposited by a GHC run.  This is seperate from
310 -- 'defaultErrorHandler', because you might want to override the error
311 -- handling, but still get the ordinary cleanup behaviour.
312 defaultCleanupHandler :: DynFlags -> IO a -> IO a
313 defaultCleanupHandler dflags inner = 
314     -- make sure we clean up after ourselves
315     later (do cleanTempFiles dflags
316               cleanTempDirs dflags
317           )
318           -- exceptions will be blocked while we clean the temporary files,
319           -- so there shouldn't be any difficulty if we receive further
320           -- signals.
321     inner
322
323
324 #if defined(GHCI) 
325 GLOBAL_VAR(v_bkptLinkEnv, [], [(Name, HValue)])
326         -- stores the current breakpoint handler to help setContext to
327         -- restore it after a context change
328 #endif
329
330 -- | Starts a new session.  A session consists of a set of loaded
331 -- modules, a set of options (DynFlags), and an interactive context.
332 newSession :: Maybe FilePath -> IO Session
333 newSession mb_top_dir = do
334   -- catch ^C
335   main_thread <- myThreadId
336   modifyMVar_ interruptTargetThread (return . (main_thread :))
337   installSignalHandlers
338
339   dflags0 <- initSysTools mb_top_dir defaultDynFlags
340   dflags  <- initDynFlags dflags0
341   env <- newHscEnv dflags
342   ref <- newIORef env
343   return (Session ref)
344
345 -- tmp: this breaks the abstraction, but required because DriverMkDepend
346 -- needs to call the Finder.  ToDo: untangle this.
347 sessionHscEnv :: Session -> IO HscEnv
348 sessionHscEnv (Session ref) = readIORef ref
349
350 withSession :: Session -> (HscEnv -> IO a) -> IO a
351 withSession (Session ref) f = do h <- readIORef ref; f h
352
353 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
354 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
355
356 -- -----------------------------------------------------------------------------
357 -- Flags & settings
358
359 -- | Grabs the DynFlags from the Session
360 getSessionDynFlags :: Session -> IO DynFlags
361 getSessionDynFlags s = withSession s (return . hsc_dflags)
362
363 -- | Updates the DynFlags in a Session.  This also reads
364 -- the package database (unless it has already been read),
365 -- and prepares the compilers knowledge about packages.  It
366 -- can be called again to load new packages: just add new
367 -- package flags to (packageFlags dflags).
368 --
369 -- Returns a list of new packages that may need to be linked in using
370 -- the dynamic linker (see 'linkPackages') as a result of new package
371 -- flags.  If you are not doing linking or doing static linking, you
372 -- can ignore the list of packages returned.
373 --
374 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
375 setSessionDynFlags (Session ref) dflags = do
376   hsc_env <- readIORef ref
377   (dflags', preload) <- initPackages dflags
378   writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
379   return preload
380
381 -- | If there is no -o option, guess the name of target executable
382 -- by using top-level source file name as a base.
383 guessOutputFile :: Session -> IO ()
384 guessOutputFile s = modifySession s $ \env ->
385     let dflags = hsc_dflags env
386         mod_graph = hsc_mod_graph env
387         mainModuleSrcPath, guessedName :: Maybe String
388         mainModuleSrcPath = do
389             let isMain = (== mainModIs dflags) . ms_mod
390             [ms] <- return (filter isMain mod_graph)
391             ml_hs_file (ms_location ms)
392         guessedName = fmap basenameOf mainModuleSrcPath
393     in
394     case outputFile dflags of
395         Just _ -> env
396         Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
397
398 -- -----------------------------------------------------------------------------
399 -- Targets
400
401 -- ToDo: think about relative vs. absolute file paths. And what
402 -- happens when the current directory changes.
403
404 -- | Sets the targets for this session.  Each target may be a module name
405 -- or a filename.  The targets correspond to the set of root modules for
406 -- the program\/library.  Unloading the current program is achieved by
407 -- setting the current set of targets to be empty, followed by load.
408 setTargets :: Session -> [Target] -> IO ()
409 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
410
411 -- | returns the current set of targets
412 getTargets :: Session -> IO [Target]
413 getTargets s = withSession s (return . hsc_targets)
414
415 -- | Add another target
416 addTarget :: Session -> Target -> IO ()
417 addTarget s target
418   = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
419
420 -- | Remove a target
421 removeTarget :: Session -> TargetId -> IO ()
422 removeTarget s target_id
423   = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
424   where
425    filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
426
427 -- Attempts to guess what Target a string refers to.  This function implements
428 -- the --make/GHCi command-line syntax for filenames: 
429 --
430 --      - if the string looks like a Haskell source filename, then interpret
431 --        it as such
432 --      - if adding a .hs or .lhs suffix yields the name of an existing file,
433 --        then use that
434 --      - otherwise interpret the string as a module name
435 --
436 guessTarget :: String -> Maybe Phase -> IO Target
437 guessTarget file (Just phase)
438    = return (Target (TargetFile file (Just phase)) Nothing)
439 guessTarget file Nothing
440    | isHaskellSrcFilename file
441    = return (Target (TargetFile file Nothing) Nothing)
442    | otherwise
443    = do exists <- doesFileExist hs_file
444         if exists
445            then return (Target (TargetFile hs_file Nothing) Nothing)
446            else do
447         exists <- doesFileExist lhs_file
448         if exists
449            then return (Target (TargetFile lhs_file Nothing) Nothing)
450            else do
451         return (Target (TargetModule (mkModuleName file)) Nothing)
452      where 
453          hs_file  = file `joinFileExt` "hs"
454          lhs_file = file `joinFileExt` "lhs"
455
456 -- -----------------------------------------------------------------------------
457 -- Extending the program scope
458
459 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
460 extendGlobalRdrScope session rdrElts
461     = modifySession session $ \hscEnv ->
462       let global_rdr = hsc_global_rdr_env hscEnv
463       in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
464
465 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
466 setGlobalRdrScope session rdrElts
467     = modifySession session $ \hscEnv ->
468       hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
469
470 extendGlobalTypeScope :: Session -> [Id] -> IO ()
471 extendGlobalTypeScope session ids
472     = modifySession session $ \hscEnv ->
473       let global_type = hsc_global_type_env hscEnv
474       in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
475
476 setGlobalTypeScope :: Session -> [Id] -> IO ()
477 setGlobalTypeScope session ids
478     = modifySession session $ \hscEnv ->
479       hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
480
481 -- -----------------------------------------------------------------------------
482 -- Parsing Haddock comments
483
484 parseHaddockComment :: String -> Either String (HsDoc RdrName)
485 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
486
487 -- -----------------------------------------------------------------------------
488 -- Loading the program
489
490 -- Perform a dependency analysis starting from the current targets
491 -- and update the session with the new module graph.
492 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
493 depanal (Session ref) excluded_mods allow_dup_roots = do
494   hsc_env <- readIORef ref
495   let
496          dflags  = hsc_dflags hsc_env
497          gmode   = ghcMode (hsc_dflags hsc_env)
498          targets = hsc_targets hsc_env
499          old_graph = hsc_mod_graph hsc_env
500         
501   showPass dflags "Chasing dependencies"
502   debugTraceMsg dflags 2 (hcat [
503              text "Chasing modules from: ",
504              hcat (punctuate comma (map pprTarget targets))])
505
506   r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
507   case r of
508     Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
509     _ -> return ()
510   return r
511
512 {-
513 -- | The result of load.
514 data LoadResult
515   = LoadOk      Errors  -- ^ all specified targets were loaded successfully.
516   | LoadFailed  Errors  -- ^ not all modules were loaded.
517
518 type Errors = [String]
519
520 data ErrMsg = ErrMsg { 
521         errMsgSeverity  :: Severity,  -- warning, error, etc.
522         errMsgSpans     :: [SrcSpan],
523         errMsgShortDoc  :: Doc,
524         errMsgExtraInfo :: Doc
525         }
526 -}
527
528 data LoadHowMuch
529    = LoadAllTargets
530    | LoadUpTo ModuleName
531    | LoadDependenciesOf ModuleName
532
533 -- | Try to load the program.  If a Module is supplied, then just
534 -- attempt to load up to this target.  If no Module is supplied,
535 -- then try to load all targets.
536 load :: Session -> LoadHowMuch -> IO SuccessFlag
537 load s@(Session ref) how_much
538    = do 
539         -- Dependency analysis first.  Note that this fixes the module graph:
540         -- even if we don't get a fully successful upsweep, the full module
541         -- graph is still retained in the Session.  We can tell which modules
542         -- were successfully loaded by inspecting the Session's HPT.
543         mb_graph <- depanal s [] False
544         case mb_graph of           
545            Just mod_graph -> load2 s how_much mod_graph 
546            Nothing        -> return Failed
547
548 load2 s@(Session ref) how_much mod_graph = do
549         guessOutputFile s
550         hsc_env <- readIORef ref
551
552         let hpt1      = hsc_HPT hsc_env
553         let dflags    = hsc_dflags hsc_env
554         let ghci_mode = ghcMode dflags -- this never changes
555
556         -- The "bad" boot modules are the ones for which we have
557         -- B.hs-boot in the module graph, but no B.hs
558         -- The downsweep should have ensured this does not happen
559         -- (see msDeps)
560         let all_home_mods = [ms_mod_name s 
561                             | s <- mod_graph, not (isBootSummary s)]
562 #ifdef DEBUG
563             bad_boot_mods = [s        | s <- mod_graph, isBootSummary s,
564                                         not (ms_mod_name s `elem` all_home_mods)]
565 #endif
566         ASSERT( null bad_boot_mods ) return ()
567
568         -- mg2_with_srcimps drops the hi-boot nodes, returning a 
569         -- graph with cycles.  Among other things, it is used for
570         -- backing out partially complete cycles following a failed
571         -- upsweep, and for removing from hpt all the modules
572         -- not in strict downwards closure, during calls to compile.
573         let mg2_with_srcimps :: [SCC ModSummary]
574             mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
575
576         -- If we can determine that any of the {-# SOURCE #-} imports
577         -- are definitely unnecessary, then emit a warning.
578         warnUnnecessarySourceImports dflags mg2_with_srcimps
579
580         let
581             -- check the stability property for each module.
582             stable_mods@(stable_obj,stable_bco)
583                 = checkStability hpt1 mg2_with_srcimps all_home_mods
584
585             -- prune bits of the HPT which are definitely redundant now,
586             -- to save space.
587             pruned_hpt = pruneHomePackageTable hpt1 
588                                 (flattenSCCs mg2_with_srcimps)
589                                 stable_mods
590
591         evaluate pruned_hpt
592
593         debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
594                                 text "Stable BCO:" <+> ppr stable_bco)
595
596         -- Unload any modules which are going to be re-linked this time around.
597         let stable_linkables = [ linkable
598                                | m <- stable_obj++stable_bco,
599                                  Just hmi <- [lookupUFM pruned_hpt m],
600                                  Just linkable <- [hm_linkable hmi] ]
601         unload hsc_env stable_linkables
602
603         -- We could at this point detect cycles which aren't broken by
604         -- a source-import, and complain immediately, but it seems better
605         -- to let upsweep_mods do this, so at least some useful work gets
606         -- done before the upsweep is abandoned.
607         --hPutStrLn stderr "after tsort:\n"
608         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
609
610         -- Now do the upsweep, calling compile for each module in
611         -- turn.  Final result is version 3 of everything.
612
613         -- Topologically sort the module graph, this time including hi-boot
614         -- nodes, and possibly just including the portion of the graph
615         -- reachable from the module specified in the 2nd argument to load.
616         -- This graph should be cycle-free.
617         -- If we're restricting the upsweep to a portion of the graph, we
618         -- also want to retain everything that is still stable.
619         let full_mg :: [SCC ModSummary]
620             full_mg    = topSortModuleGraph False mod_graph Nothing
621
622             maybe_top_mod = case how_much of
623                                 LoadUpTo m           -> Just m
624                                 LoadDependenciesOf m -> Just m
625                                 _                    -> Nothing
626
627             partial_mg0 :: [SCC ModSummary]
628             partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
629
630             -- LoadDependenciesOf m: we want the upsweep to stop just
631             -- short of the specified module (unless the specified module
632             -- is stable).
633             partial_mg
634                 | LoadDependenciesOf mod <- how_much
635                 = ASSERT( case last partial_mg0 of 
636                             AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
637                   List.init partial_mg0
638                 | otherwise
639                 = partial_mg0
640   
641             stable_mg = 
642                 [ AcyclicSCC ms
643                 | AcyclicSCC ms <- full_mg,
644                   ms_mod_name ms `elem` stable_obj++stable_bco,
645                   ms_mod_name ms `notElem` [ ms_mod_name ms' | 
646                                                 AcyclicSCC ms' <- partial_mg ] ]
647
648             mg = stable_mg ++ partial_mg
649
650         -- clean up between compilations
651         let cleanup = cleanTempFilesExcept dflags
652                           (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
653
654         debugTraceMsg dflags 2 (hang (text "Ready for upsweep") 
655                                    2 (ppr mg))
656         (upsweep_ok, hsc_env1, modsUpswept)
657            <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
658                            pruned_hpt stable_mods cleanup mg
659
660         -- Make modsDone be the summaries for each home module now
661         -- available; this should equal the domain of hpt3.
662         -- Get in in a roughly top .. bottom order (hence reverse).
663
664         let modsDone = reverse modsUpswept
665
666         -- Try and do linking in some form, depending on whether the
667         -- upsweep was completely or only partially successful.
668
669         if succeeded upsweep_ok
670
671          then 
672            -- Easy; just relink it all.
673            do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
674
675               -- Clean up after ourselves
676               cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
677
678               -- Issue a warning for the confusing case where the user
679               -- said '-o foo' but we're not going to do any linking.
680               -- We attempt linking if either (a) one of the modules is
681               -- called Main, or (b) the user said -no-hs-main, indicating
682               -- that main() is going to come from somewhere else.
683               --
684               let ofile = outputFile dflags
685               let no_hs_main = dopt Opt_NoHsMain dflags
686               let 
687                 main_mod = mainModIs dflags
688                 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
689                 do_linking = a_root_is_Main || no_hs_main
690
691               when (ghcLink dflags == LinkBinary 
692                     && isJust ofile && not do_linking) $
693                 debugTraceMsg dflags 1 $
694                     text ("Warning: output was redirected with -o, " ++
695                           "but no output will be generated\n" ++
696                           "because there is no " ++ 
697                           moduleNameString (moduleName main_mod) ++ " module.")
698
699               -- link everything together
700               linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
701
702               loadFinish Succeeded linkresult ref hsc_env1
703
704          else 
705            -- Tricky.  We need to back out the effects of compiling any
706            -- half-done cycles, both so as to clean up the top level envs
707            -- and to avoid telling the interactive linker to link them.
708            do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
709
710               let modsDone_names
711                      = map ms_mod modsDone
712               let mods_to_zap_names 
713                      = findPartiallyCompletedCycles modsDone_names 
714                           mg2_with_srcimps
715               let mods_to_keep
716                      = filter ((`notElem` mods_to_zap_names).ms_mod) 
717                           modsDone
718
719               let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep) 
720                                               (hsc_HPT hsc_env1)
721
722               -- Clean up after ourselves
723               cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
724
725               -- there should be no Nothings where linkables should be, now
726               ASSERT(all (isJust.hm_linkable) 
727                         (eltsUFM (hsc_HPT hsc_env))) do
728         
729               -- Link everything together
730               linkresult <- link (ghcLink dflags) dflags False hpt4
731
732               let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
733               loadFinish Failed linkresult ref hsc_env4
734
735 -- Finish up after a load.
736
737 -- If the link failed, unload everything and return.
738 loadFinish all_ok Failed ref hsc_env
739   = do unload hsc_env []
740        writeIORef ref $! discardProg hsc_env
741        return Failed
742
743 -- Empty the interactive context and set the module context to the topmost
744 -- newly loaded module, or the Prelude if none were loaded.
745 loadFinish all_ok Succeeded ref hsc_env
746   = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
747        return all_ok
748
749
750 -- Forget the current program, but retain the persistent info in HscEnv
751 discardProg :: HscEnv -> HscEnv
752 discardProg hsc_env
753   = hsc_env { hsc_mod_graph = emptyMG, 
754               hsc_IC = emptyInteractiveContext,
755               hsc_HPT = emptyHomePackageTable }
756
757 -- used to fish out the preprocess output files for the purposes of
758 -- cleaning up.  The preprocessed file *might* be the same as the
759 -- source file, but that doesn't do any harm.
760 ppFilesFromSummaries summaries = map ms_hspp_file summaries
761
762 -- -----------------------------------------------------------------------------
763 -- Check module
764
765 data CheckedModule = 
766   CheckedModule { parsedSource      :: ParsedSource,
767                   renamedSource     :: Maybe RenamedSource,
768                   typecheckedSource :: Maybe TypecheckedSource,
769                   checkedModuleInfo :: Maybe ModuleInfo
770                 }
771         -- ToDo: improvements that could be made here:
772         --  if the module succeeded renaming but not typechecking,
773         --  we can still get back the GlobalRdrEnv and exports, so
774         --  perhaps the ModuleInfo should be split up into separate
775         --  fields within CheckedModule.
776
777 type ParsedSource      = Located (HsModule RdrName)
778 type RenamedSource     = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
779                           Maybe (HsDoc Name), HaddockModInfo Name)
780 type TypecheckedSource = LHsBinds Id
781
782 -- NOTE:
783 --   - things that aren't in the output of the typechecker right now:
784 --     - the export list
785 --     - the imports
786 --     - type signatures
787 --     - type/data/newtype declarations
788 --     - class declarations
789 --     - instances
790 --   - extra things in the typechecker's output:
791 --     - default methods are turned into top-level decls.
792 --     - dictionary bindings
793
794
795 -- | This is the way to get access to parsed and typechecked source code
796 -- for a module.  'checkModule' loads all the dependencies of the specified
797 -- module in the Session, and then attempts to typecheck the module.  If
798 -- successful, it returns the abstract syntax for the module.
799 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
800 checkModule session@(Session ref) mod = do
801         -- load up the dependencies first
802    r <- load session (LoadDependenciesOf mod)
803    if (failed r) then return Nothing else do
804
805         -- now parse & typecheck the module
806    hsc_env <- readIORef ref   
807    let mg  = hsc_mod_graph hsc_env
808    case [ ms | ms <- mg, ms_mod_name ms == mod ] of
809         [] -> return Nothing
810         (ms:_) -> do 
811            mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
812            case mbChecked of
813              Nothing -> return Nothing
814              Just (HscChecked parsed renamed Nothing) ->
815                    return (Just (CheckedModule {
816                                         parsedSource = parsed,
817                                         renamedSource = renamed,
818                                         typecheckedSource = Nothing,
819                                         checkedModuleInfo = Nothing }))
820              Just (HscChecked parsed renamed
821                            (Just (tc_binds, rdr_env, details))) -> do
822                    let minf = ModuleInfo {
823                                 minf_type_env  = md_types details,
824                                 minf_exports   = availsToNameSet $
825                                                      md_exports details,
826                                 minf_rdr_env   = Just rdr_env,
827                                 minf_instances = md_insts details
828 #ifdef GHCI
829                                ,minf_modBreaks = emptyModBreaks 
830 #endif
831                               }
832                    return (Just (CheckedModule {
833                                         parsedSource = parsed,
834                                         renamedSource = renamed,
835                                         typecheckedSource = Just tc_binds,
836                                         checkedModuleInfo = Just minf }))
837
838 -- ---------------------------------------------------------------------------
839 -- Unloading
840
841 unload :: HscEnv -> [Linkable] -> IO ()
842 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
843   = case ghcLink (hsc_dflags hsc_env) of
844 #ifdef GHCI
845         LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
846 #else
847         LinkInMemory -> panic "unload: no interpreter"
848 #endif
849         other -> return ()
850
851 -- -----------------------------------------------------------------------------
852 -- checkStability
853
854 {-
855   Stability tells us which modules definitely do not need to be recompiled.
856   There are two main reasons for having stability:
857   
858    - avoid doing a complete upsweep of the module graph in GHCi when
859      modules near the bottom of the tree have not changed.
860
861    - to tell GHCi when it can load object code: we can only load object code
862      for a module when we also load object code fo  all of the imports of the
863      module.  So we need to know that we will definitely not be recompiling
864      any of these modules, and we can use the object code.
865
866   The stability check is as follows.  Both stableObject and
867   stableBCO are used during the upsweep phase later.
868
869   -------------------
870   stable m = stableObject m || stableBCO m
871
872   stableObject m = 
873         all stableObject (imports m)
874         && old linkable does not exist, or is == on-disk .o
875         && date(on-disk .o) > date(.hs)
876
877   stableBCO m =
878         all stable (imports m)
879         && date(BCO) > date(.hs)
880   -------------------    
881
882   These properties embody the following ideas:
883
884     - if a module is stable, then:
885         - if it has been compiled in a previous pass (present in HPT)
886           then it does not need to be compiled or re-linked.
887         - if it has not been compiled in a previous pass,
888           then we only need to read its .hi file from disk and
889           link it to produce a ModDetails.
890
891     - if a modules is not stable, we will definitely be at least
892       re-linking, and possibly re-compiling it during the upsweep.
893       All non-stable modules can (and should) therefore be unlinked
894       before the upsweep.
895
896     - Note that objects are only considered stable if they only depend
897       on other objects.  We can't link object code against byte code.
898 -}
899
900 checkStability
901         :: HomePackageTable             -- HPT from last compilation
902         -> [SCC ModSummary]             -- current module graph (cyclic)
903         -> [ModuleName]                 -- all home modules
904         -> ([ModuleName],               -- stableObject
905             [ModuleName])               -- stableBCO
906
907 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
908   where
909    checkSCC (stable_obj, stable_bco) scc0
910      | stableObjects = (scc_mods ++ stable_obj, stable_bco)
911      | stableBCOs    = (stable_obj, scc_mods ++ stable_bco)
912      | otherwise     = (stable_obj, stable_bco)
913      where
914         scc = flattenSCC scc0
915         scc_mods = map ms_mod_name scc
916         home_module m   = m `elem` all_home_mods && m `notElem` scc_mods
917
918         scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
919             -- all imports outside the current SCC, but in the home pkg
920         
921         stable_obj_imps = map (`elem` stable_obj) scc_allimps
922         stable_bco_imps = map (`elem` stable_bco) scc_allimps
923
924         stableObjects = 
925            and stable_obj_imps
926            && all object_ok scc
927
928         stableBCOs = 
929            and (zipWith (||) stable_obj_imps stable_bco_imps)
930            && all bco_ok scc
931
932         object_ok ms
933           | Just t <- ms_obj_date ms  =  t >= ms_hs_date ms 
934                                          && same_as_prev t
935           | otherwise = False
936           where
937              same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
938                                 Just hmi  | Just l <- hm_linkable hmi
939                                  -> isObjectLinkable l && t == linkableTime l
940                                 _other  -> True
941                 -- why '>=' rather than '>' above?  If the filesystem stores
942                 -- times to the nearset second, we may occasionally find that
943                 -- the object & source have the same modification time, 
944                 -- especially if the source was automatically generated
945                 -- and compiled.  Using >= is slightly unsafe, but it matches
946                 -- make's behaviour.
947
948         bco_ok ms
949           = case lookupUFM hpt (ms_mod_name ms) of
950                 Just hmi  | Just l <- hm_linkable hmi ->
951                         not (isObjectLinkable l) && 
952                         linkableTime l >= ms_hs_date ms
953                 _other  -> False
954
955 ms_allimps :: ModSummary -> [ModuleName]
956 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
957
958 -- -----------------------------------------------------------------------------
959 -- Prune the HomePackageTable
960
961 -- Before doing an upsweep, we can throw away:
962 --
963 --   - For non-stable modules:
964 --      - all ModDetails, all linked code
965 --   - all unlinked code that is out of date with respect to
966 --     the source file
967 --
968 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
969 -- space at the end of the upsweep, because the topmost ModDetails of the
970 -- old HPT holds on to the entire type environment from the previous
971 -- compilation.
972
973 pruneHomePackageTable
974    :: HomePackageTable
975    -> [ModSummary]
976    -> ([ModuleName],[ModuleName])
977    -> HomePackageTable
978
979 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
980   = mapUFM prune hpt
981   where prune hmi
982           | is_stable modl = hmi'
983           | otherwise      = hmi'{ hm_details = emptyModDetails }
984           where
985            modl = moduleName (mi_module (hm_iface hmi))
986            hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
987                 = hmi{ hm_linkable = Nothing }
988                 | otherwise
989                 = hmi
990                 where ms = expectJust "prune" (lookupUFM ms_map modl)
991
992         ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
993
994         is_stable m = m `elem` stable_obj || m `elem` stable_bco
995
996 -- -----------------------------------------------------------------------------
997
998 -- Return (names of) all those in modsDone who are part of a cycle
999 -- as defined by theGraph.
1000 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1001 findPartiallyCompletedCycles modsDone theGraph
1002    = chew theGraph
1003      where
1004         chew [] = []
1005         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
1006         chew ((CyclicSCC vs):rest)
1007            = let names_in_this_cycle = nub (map ms_mod vs)
1008                  mods_in_this_cycle  
1009                     = nub ([done | done <- modsDone, 
1010                                    done `elem` names_in_this_cycle])
1011                  chewed_rest = chew rest
1012              in 
1013              if   notNull mods_in_this_cycle
1014                   && length mods_in_this_cycle < length names_in_this_cycle
1015              then mods_in_this_cycle ++ chewed_rest
1016              else chewed_rest
1017
1018 -- -----------------------------------------------------------------------------
1019 -- The upsweep
1020
1021 -- This is where we compile each module in the module graph, in a pass
1022 -- from the bottom to the top of the graph.
1023
1024 -- There better had not be any cyclic groups here -- we check for them.
1025
1026 upsweep
1027     :: HscEnv                   -- Includes initially-empty HPT
1028     -> HomePackageTable         -- HPT from last time round (pruned)
1029     -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1030     -> IO ()                    -- How to clean up unwanted tmp files
1031     -> [SCC ModSummary]         -- Mods to do (the worklist)
1032     -> IO (SuccessFlag,
1033            HscEnv,              -- With an updated HPT
1034            [ModSummary])        -- Mods which succeeded
1035
1036 upsweep hsc_env old_hpt stable_mods cleanup mods
1037    = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1038
1039 upsweep' hsc_env old_hpt stable_mods cleanup
1040      [] _ _
1041    = return (Succeeded, hsc_env, [])
1042
1043 upsweep' hsc_env old_hpt stable_mods cleanup
1044      (CyclicSCC ms:_) _ _
1045    = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1046         return (Failed, hsc_env, [])
1047
1048 upsweep' hsc_env old_hpt stable_mods cleanup
1049      (AcyclicSCC mod:mods) mod_index nmods
1050    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
1051         --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
1052         --                     (moduleEnvElts (hsc_HPT hsc_env)))
1053
1054         mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
1055                        mod_index nmods
1056
1057         cleanup         -- Remove unwanted tmp files between compilations
1058
1059         case mb_mod_info of
1060             Nothing -> return (Failed, hsc_env, [])
1061             Just mod_info -> do 
1062                 { let this_mod = ms_mod_name mod
1063
1064                         -- Add new info to hsc_env
1065                       hpt1     = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1066                       hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1067
1068                         -- Space-saving: delete the old HPT entry
1069                         -- for mod BUT if mod is a hs-boot
1070                         -- node, don't delete it.  For the
1071                         -- interface, the HPT entry is probaby for the
1072                         -- main Haskell source file.  Deleting it
1073                         -- would force .. (what?? --SDM)
1074                       old_hpt1 | isBootSummary mod = old_hpt
1075                                | otherwise = delFromUFM old_hpt this_mod
1076
1077                 ; (restOK, hsc_env2, modOKs) 
1078                         <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup 
1079                                 mods (mod_index+1) nmods
1080                 ; return (restOK, hsc_env2, mod:modOKs)
1081                 }
1082
1083
1084 -- Compile a single module.  Always produce a Linkable for it if 
1085 -- successful.  If no compilation happened, return the old Linkable.
1086 upsweep_mod :: HscEnv
1087             -> HomePackageTable
1088             -> ([ModuleName],[ModuleName])
1089             -> ModSummary
1090             -> Int  -- index of module
1091             -> Int  -- total number of modules
1092             -> IO (Maybe HomeModInfo)   -- Nothing => Failed
1093
1094 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1095    =    let 
1096             this_mod_name = ms_mod_name summary
1097             this_mod    = ms_mod summary
1098             mb_obj_date = ms_obj_date summary
1099             obj_fn      = ml_obj_file (ms_location summary)
1100             hs_date     = ms_hs_date summary
1101
1102             is_stable_obj = this_mod_name `elem` stable_obj
1103             is_stable_bco = this_mod_name `elem` stable_bco
1104
1105             old_hmi = lookupUFM old_hpt this_mod_name
1106
1107             -- We're using the dflags for this module now, obtained by
1108             -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1109             dflags = ms_hspp_opts summary
1110             prevailing_target = hscTarget (hsc_dflags hsc_env)
1111             local_target      = hscTarget dflags
1112
1113             -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1114             -- we don't do anything dodgy: these should only work to change
1115             -- from -fvia-C to -fasm and vice-versa, otherwise we could 
1116             -- end up trying to link object code to byte code.
1117             target = if prevailing_target /= local_target
1118                         && (not (isObjectTarget prevailing_target)
1119                             || not (isObjectTarget local_target))
1120                         then prevailing_target
1121                         else local_target 
1122
1123             -- store the corrected hscTarget into the summary
1124             summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1125
1126             -- The old interface is ok if
1127             --  a) we're compiling a source file, and the old HPT
1128             --     entry is for a source file
1129             --  b) we're compiling a hs-boot file
1130             -- Case (b) allows an hs-boot file to get the interface of its
1131             -- real source file on the second iteration of the compilation
1132             -- manager, but that does no harm.  Otherwise the hs-boot file
1133             -- will always be recompiled
1134             
1135             mb_old_iface 
1136                 = case old_hmi of
1137                      Nothing                              -> Nothing
1138                      Just hm_info | isBootSummary summary -> Just iface
1139                                   | not (mi_boot iface)   -> Just iface
1140                                   | otherwise             -> Nothing
1141                                    where 
1142                                      iface = hm_iface hm_info
1143
1144             compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1145             compile_it  = upsweep_compile hsc_env old_hpt this_mod_name 
1146                                 summary' mod_index nmods mb_old_iface
1147
1148             compile_it_discard_iface 
1149                         = upsweep_compile hsc_env old_hpt this_mod_name 
1150                                 summary' mod_index nmods Nothing
1151
1152         in
1153         case target of
1154
1155             _any
1156                 -- Regardless of whether we're generating object code or
1157                 -- byte code, we can always use an existing object file
1158                 -- if it is *stable* (see checkStability).
1159                 | is_stable_obj, isJust old_hmi ->
1160                         return old_hmi
1161                         -- object is stable, and we have an entry in the
1162                         -- old HPT: nothing to do
1163
1164                 | is_stable_obj, isNothing old_hmi -> do
1165                         linkable <- findObjectLinkable this_mod obj_fn 
1166                                         (expectJust "upseep1" mb_obj_date)
1167                         compile_it (Just linkable)
1168                         -- object is stable, but we need to load the interface
1169                         -- off disk to make a HMI.
1170
1171             HscInterpreted
1172                 | is_stable_bco -> 
1173                         ASSERT(isJust old_hmi) -- must be in the old_hpt
1174                         return old_hmi
1175                         -- BCO is stable: nothing to do
1176
1177                 | Just hmi <- old_hmi,
1178                   Just l <- hm_linkable hmi, not (isObjectLinkable l),
1179                   linkableTime l >= ms_hs_date summary ->
1180                         compile_it (Just l)
1181                         -- we have an old BCO that is up to date with respect
1182                         -- to the source: do a recompilation check as normal.
1183
1184                 | otherwise -> 
1185                         compile_it Nothing
1186                         -- no existing code at all: we must recompile.
1187
1188               -- When generating object code, if there's an up-to-date
1189               -- object file on the disk, then we can use it.
1190               -- However, if the object file is new (compared to any
1191               -- linkable we had from a previous compilation), then we
1192               -- must discard any in-memory interface, because this
1193               -- means the user has compiled the source file
1194               -- separately and generated a new interface, that we must
1195               -- read from the disk.
1196               --
1197             obj | isObjectTarget obj,
1198                   Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1199                      case old_hmi of
1200                         Just hmi 
1201                           | Just l <- hm_linkable hmi,
1202                             isObjectLinkable l && linkableTime l == obj_date
1203                             -> compile_it (Just l)
1204                         _otherwise -> do
1205                           linkable <- findObjectLinkable this_mod obj_fn obj_date
1206                           compile_it_discard_iface (Just linkable)
1207
1208             _otherwise ->
1209                   compile_it Nothing
1210
1211
1212 -- Run hsc to compile a module
1213 upsweep_compile hsc_env old_hpt this_mod summary
1214                 mod_index nmods
1215                 mb_old_iface
1216                 mb_old_linkable
1217  = do
1218    compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1219                         mod_index nmods
1220
1221    case compresult of
1222         -- Compilation failed.  Compile may still have updated the PCS, tho.
1223         CompErrs -> return Nothing
1224
1225         -- Compilation "succeeded", and may or may not have returned a new
1226         -- linkable (depending on whether compilation was actually performed
1227         -- or not).
1228         CompOK new_details new_iface new_linkable
1229               -> do let new_info = HomeModInfo { hm_iface = new_iface,
1230                                                  hm_details = new_details,
1231                                                  hm_linkable = new_linkable }
1232                     return (Just new_info)
1233
1234
1235 -- Filter modules in the HPT
1236 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1237 retainInTopLevelEnvs keep_these hpt
1238    = listToUFM   [ (mod, expectJust "retain" mb_mod_info)
1239                  | mod <- keep_these
1240                  , let mb_mod_info = lookupUFM hpt mod
1241                  , isJust mb_mod_info ]
1242
1243 -- ---------------------------------------------------------------------------
1244 -- Topological sort of the module graph
1245
1246 topSortModuleGraph
1247           :: Bool               -- Drop hi-boot nodes? (see below)
1248           -> [ModSummary]
1249           -> Maybe ModuleName
1250           -> [SCC ModSummary]
1251 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1252 -- The resulting list of strongly-connected-components is in topologically
1253 -- sorted order, starting with the module(s) at the bottom of the
1254 -- dependency graph (ie compile them first) and ending with the ones at
1255 -- the top.
1256 --
1257 -- Drop hi-boot nodes (first boolean arg)? 
1258 --
1259 --   False:     treat the hi-boot summaries as nodes of the graph,
1260 --              so the graph must be acyclic
1261 --
1262 --   True:      eliminate the hi-boot nodes, and instead pretend
1263 --              the a source-import of Foo is an import of Foo
1264 --              The resulting graph has no hi-boot nodes, but can by cyclic
1265
1266 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1267   = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1268 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1269   = stronglyConnComp (map vertex_fn (reachable graph root))
1270   where 
1271         -- restrict the graph to just those modules reachable from
1272         -- the specified module.  We do this by building a graph with
1273         -- the full set of nodes, and determining the reachable set from
1274         -- the specified node.
1275         (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1276         (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1277         root 
1278           | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1279           | otherwise  = throwDyn (ProgramError "module does not exist")
1280
1281 moduleGraphNodes :: Bool -> [ModSummary]
1282   -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1283 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1284    where
1285         -- Drop hs-boot nodes by using HsSrcFile as the key
1286         hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1287                     | otherwise          = HsBootFile   
1288
1289         -- We use integers as the keys for the SCC algorithm
1290         nodes :: [(ModSummary, Int, [Int])]     
1291         nodes = [(s, expectJust "topSort" $ 
1292                         lookup_key (ms_hsc_src s) (ms_mod_name s),
1293                      out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1294                      out_edge_keys HsSrcFile   (map unLoc (ms_imps s)) ++
1295                      (-- see [boot-edges] below
1296                       if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile 
1297                         then [] 
1298                         else case lookup_key HsBootFile (ms_mod_name s) of
1299                                 Nothing -> []
1300                                 Just k  -> [k])
1301                  )
1302                 | s <- summaries
1303                 , not (isBootSummary s && drop_hs_boot_nodes) ]
1304                 -- Drop the hi-boot ones if told to do so
1305
1306         -- [boot-edges] if this is a .hs and there is an equivalent
1307         -- .hs-boot, add a link from the former to the latter.  This
1308         -- has the effect of detecting bogus cases where the .hs-boot
1309         -- depends on the .hs, by introducing a cycle.  Additionally,
1310         -- it ensures that we will always process the .hs-boot before
1311         -- the .hs, and so the HomePackageTable will always have the
1312         -- most up to date information.
1313
1314         key_map :: NodeMap Int
1315         key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1316                             | s <- summaries]
1317                            `zip` [1..])
1318
1319         lookup_key :: HscSource -> ModuleName -> Maybe Int
1320         lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1321
1322         out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1323         out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1324                 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1325                 -- the IsBootInterface parameter True; else False
1326
1327
1328 type NodeKey   = (ModuleName, HscSource)  -- The nodes of the graph are 
1329 type NodeMap a = FiniteMap NodeKey a      -- keyed by (mod, src_file_type) pairs
1330
1331 msKey :: ModSummary -> NodeKey
1332 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1333
1334 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1335 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1336         
1337 nodeMapElts :: NodeMap a -> [a]
1338 nodeMapElts = eltsFM
1339
1340 ms_mod_name :: ModSummary -> ModuleName
1341 ms_mod_name = moduleName . ms_mod
1342
1343 -- If there are {-# SOURCE #-} imports between strongly connected
1344 -- components in the topological sort, then those imports can
1345 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1346 -- were necessary, then the edge would be part of a cycle.
1347 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1348 warnUnnecessarySourceImports dflags sccs = 
1349   printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1350   where check ms =
1351            let mods_in_this_cycle = map ms_mod_name ms in
1352            [ warn m i | m <- ms, i <- ms_srcimps m,
1353                         unLoc i `notElem`  mods_in_this_cycle ]
1354
1355         warn :: ModSummary -> Located ModuleName -> WarnMsg
1356         warn ms (L loc mod) = 
1357            mkPlainErrMsg loc
1358                 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1359                  <+> quotes (ppr mod))
1360
1361 -----------------------------------------------------------------------------
1362 -- Downsweep (dependency analysis)
1363
1364 -- Chase downwards from the specified root set, returning summaries
1365 -- for all home modules encountered.  Only follow source-import
1366 -- links.
1367
1368 -- We pass in the previous collection of summaries, which is used as a
1369 -- cache to avoid recalculating a module summary if the source is
1370 -- unchanged.
1371 --
1372 -- The returned list of [ModSummary] nodes has one node for each home-package
1373 -- module, plus one for any hs-boot files.  The imports of these nodes 
1374 -- are all there, including the imports of non-home-package modules.
1375
1376 downsweep :: HscEnv
1377           -> [ModSummary]       -- Old summaries
1378           -> [ModuleName]       -- Ignore dependencies on these; treat
1379                                 -- them as if they were package modules
1380           -> Bool               -- True <=> allow multiple targets to have 
1381                                 --          the same module name; this is 
1382                                 --          very useful for ghc -M
1383           -> IO (Maybe [ModSummary])
1384                 -- The elts of [ModSummary] all have distinct
1385                 -- (Modules, IsBoot) identifiers, unless the Bool is true
1386                 -- in which case there can be repeats
1387 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1388    = -- catch error messages and return them
1389      handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1390        rootSummaries <- mapM getRootSummary roots
1391        let root_map = mkRootMap rootSummaries
1392        checkDuplicates root_map
1393        summs <- loop (concatMap msDeps rootSummaries) root_map
1394        return (Just summs)
1395      where
1396         roots = hsc_targets hsc_env
1397
1398         old_summary_map :: NodeMap ModSummary
1399         old_summary_map = mkNodeMap old_summaries
1400
1401         getRootSummary :: Target -> IO ModSummary
1402         getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1403            = do exists <- doesFileExist file
1404                 if exists 
1405                     then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1406                     else throwDyn $ mkPlainErrMsg noSrcSpan $
1407                            text "can't find file:" <+> text file
1408         getRootSummary (Target (TargetModule modl) maybe_buf)
1409            = do maybe_summary <- summariseModule hsc_env old_summary_map False 
1410                                            (L rootLoc modl) maybe_buf excl_mods
1411                 case maybe_summary of
1412                    Nothing -> packageModErr modl
1413                    Just s  -> return s
1414
1415         rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1416
1417         -- In a root module, the filename is allowed to diverge from the module
1418         -- name, so we have to check that there aren't multiple root files
1419         -- defining the same module (otherwise the duplicates will be silently
1420         -- ignored, leading to confusing behaviour).
1421         checkDuplicates :: NodeMap [ModSummary] -> IO ()
1422         checkDuplicates root_map 
1423            | allow_dup_roots = return ()
1424            | null dup_roots  = return ()
1425            | otherwise       = multiRootsErr (head dup_roots)
1426            where
1427              dup_roots :: [[ModSummary]]        -- Each at least of length 2
1428              dup_roots = filterOut isSingleton (nodeMapElts root_map)
1429
1430         loop :: [(Located ModuleName,IsBootInterface)]
1431                         -- Work list: process these modules
1432              -> NodeMap [ModSummary]
1433                         -- Visited set; the range is a list because
1434                         -- the roots can have the same module names
1435                         -- if allow_dup_roots is True
1436              -> IO [ModSummary]
1437                         -- The result includes the worklist, except
1438                         -- for those mentioned in the visited set
1439         loop [] done      = return (concat (nodeMapElts done))
1440         loop ((wanted_mod, is_boot) : ss) done 
1441           | Just summs <- lookupFM done key
1442           = if isSingleton summs then
1443                 loop ss done
1444             else
1445                 do { multiRootsErr summs; return [] }
1446           | otherwise         = do { mb_s <- summariseModule hsc_env old_summary_map 
1447                                                  is_boot wanted_mod Nothing excl_mods
1448                                    ; case mb_s of
1449                                         Nothing -> loop ss done
1450                                         Just s  -> loop (msDeps s ++ ss) 
1451                                                         (addToFM done key [s]) }
1452           where
1453             key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1454
1455 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1456 mkRootMap summaries = addListToFM_C (++) emptyFM 
1457                         [ (msKey s, [s]) | s <- summaries ]
1458
1459 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1460 -- (msDeps s) returns the dependencies of the ModSummary s.
1461 -- A wrinkle is that for a {-# SOURCE #-} import we return
1462 --      *both* the hs-boot file
1463 --      *and* the source file
1464 -- as "dependencies".  That ensures that the list of all relevant
1465 -- modules always contains B.hs if it contains B.hs-boot.
1466 -- Remember, this pass isn't doing the topological sort.  It's
1467 -- just gathering the list of all relevant ModSummaries
1468 msDeps s = 
1469     concat [ [(m,True), (m,False)] | m <- ms_srcimps s ] 
1470          ++ [ (m,False) | m <- ms_imps s ] 
1471
1472 -----------------------------------------------------------------------------
1473 -- Summarising modules
1474
1475 -- We have two types of summarisation:
1476 --
1477 --    * Summarise a file.  This is used for the root module(s) passed to
1478 --      cmLoadModules.  The file is read, and used to determine the root
1479 --      module name.  The module name may differ from the filename.
1480 --
1481 --    * Summarise a module.  We are given a module name, and must provide
1482 --      a summary.  The finder is used to locate the file in which the module
1483 --      resides.
1484
1485 summariseFile
1486         :: HscEnv
1487         -> [ModSummary]                 -- old summaries
1488         -> FilePath                     -- source file name
1489         -> Maybe Phase                  -- start phase
1490         -> Maybe (StringBuffer,ClockTime)
1491         -> IO ModSummary
1492
1493 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1494         -- we can use a cached summary if one is available and the
1495         -- source file hasn't changed,  But we have to look up the summary
1496         -- by source file, rather than module name as we do in summarise.
1497    | Just old_summary <- findSummaryBySourceFile old_summaries file
1498    = do
1499         let location = ms_location old_summary
1500
1501                 -- return the cached summary if the source didn't change
1502         src_timestamp <- case maybe_buf of
1503                            Just (_,t) -> return t
1504                            Nothing    -> getModificationTime file
1505                 -- The file exists; we checked in getRootSummary above.
1506                 -- If it gets removed subsequently, then this 
1507                 -- getModificationTime may fail, but that's the right
1508                 -- behaviour.
1509
1510         if ms_hs_date old_summary == src_timestamp 
1511            then do -- update the object-file timestamp
1512                   obj_timestamp <- getObjTimestamp location False
1513                   return old_summary{ ms_obj_date = obj_timestamp }
1514            else
1515                 new_summary
1516
1517    | otherwise
1518    = new_summary
1519   where
1520     new_summary = do
1521         let dflags = hsc_dflags hsc_env
1522
1523         (dflags', hspp_fn, buf)
1524             <- preprocessFile dflags file mb_phase maybe_buf
1525
1526         (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1527
1528         -- Make a ModLocation for this file
1529         location <- mkHomeModLocation dflags mod_name file
1530
1531         -- Tell the Finder cache where it is, so that subsequent calls
1532         -- to findModule will find it, even if it's not on any search path
1533         mod <- addHomeModuleToFinder hsc_env mod_name location
1534
1535         src_timestamp <- case maybe_buf of
1536                            Just (_,t) -> return t
1537                            Nothing    -> getModificationTime file
1538                         -- getMofificationTime may fail
1539
1540         obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1541
1542         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1543                              ms_location = location,
1544                              ms_hspp_file = hspp_fn,
1545                              ms_hspp_opts = dflags',
1546                              ms_hspp_buf  = Just buf,
1547                              ms_srcimps = srcimps, ms_imps = the_imps,
1548                              ms_hs_date = src_timestamp,
1549                              ms_obj_date = obj_timestamp })
1550
1551 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1552 findSummaryBySourceFile summaries file
1553   = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1554                                  expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1555         [] -> Nothing
1556         (x:xs) -> Just x
1557
1558 -- Summarise a module, and pick up source and timestamp.
1559 summariseModule
1560           :: HscEnv
1561           -> NodeMap ModSummary -- Map of old summaries
1562           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1563           -> Located ModuleName -- Imported module to be summarised
1564           -> Maybe (StringBuffer, ClockTime)
1565           -> [ModuleName]               -- Modules to exclude
1566           -> IO (Maybe ModSummary)      -- Its new summary
1567
1568 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1569   | wanted_mod `elem` excl_mods
1570   = return Nothing
1571
1572   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1573   = do          -- Find its new timestamp; all the 
1574                 -- ModSummaries in the old map have valid ml_hs_files
1575         let location = ms_location old_summary
1576             src_fn = expectJust "summariseModule" (ml_hs_file location)
1577
1578                 -- check the modification time on the source file, and
1579                 -- return the cached summary if it hasn't changed.  If the
1580                 -- file has disappeared, we need to call the Finder again.
1581         case maybe_buf of
1582            Just (_,t) -> check_timestamp old_summary location src_fn t
1583            Nothing    -> do
1584                 m <- System.IO.Error.try (getModificationTime src_fn)
1585                 case m of
1586                    Right t -> check_timestamp old_summary location src_fn t
1587                    Left e | isDoesNotExistError e -> find_it
1588                           | otherwise             -> ioError e
1589
1590   | otherwise  = find_it
1591   where
1592     dflags = hsc_dflags hsc_env
1593
1594     hsc_src = if is_boot then HsBootFile else HsSrcFile
1595
1596     check_timestamp old_summary location src_fn src_timestamp
1597         | ms_hs_date old_summary == src_timestamp = do
1598                 -- update the object-file timestamp
1599                 obj_timestamp <- getObjTimestamp location is_boot
1600                 return (Just old_summary{ ms_obj_date = obj_timestamp })
1601         | otherwise = 
1602                 -- source changed: re-summarise.
1603                 new_summary location (ms_mod old_summary) src_fn src_timestamp
1604
1605     find_it = do
1606         -- Don't use the Finder's cache this time.  If the module was
1607         -- previously a package module, it may have now appeared on the
1608         -- search path, so we want to consider it to be a home module.  If
1609         -- the module was previously a home module, it may have moved.
1610         uncacheModule hsc_env wanted_mod
1611         found <- findImportedModule hsc_env wanted_mod Nothing
1612         case found of
1613              Found location mod 
1614                 | isJust (ml_hs_file location) ->
1615                         -- Home package
1616                          just_found location mod
1617                 | otherwise -> 
1618                         -- Drop external-pkg
1619                         ASSERT(modulePackageId mod /= thisPackage dflags)
1620                         return Nothing
1621                 where
1622                         
1623              err -> noModError dflags loc wanted_mod err
1624                         -- Not found
1625
1626     just_found location mod = do
1627                 -- Adjust location to point to the hs-boot source file, 
1628                 -- hi file, object file, when is_boot says so
1629         let location' | is_boot   = addBootSuffixLocn location
1630                       | otherwise = location
1631             src_fn = expectJust "summarise2" (ml_hs_file location')
1632
1633                 -- Check that it exists
1634                 -- It might have been deleted since the Finder last found it
1635         maybe_t <- modificationTimeIfExists src_fn
1636         case maybe_t of
1637           Nothing -> noHsFileErr loc src_fn
1638           Just t  -> new_summary location' mod src_fn t
1639
1640
1641     new_summary location mod src_fn src_timestamp
1642       = do
1643         -- Preprocess the source file and get its imports
1644         -- The dflags' contains the OPTIONS pragmas
1645         (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1646         (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1647
1648         when (mod_name /= wanted_mod) $
1649                 throwDyn $ mkPlainErrMsg mod_loc $ 
1650                               text "file name does not match module name"
1651                               <+> quotes (ppr mod_name)
1652
1653                 -- Find the object timestamp, and return the summary
1654         obj_timestamp <- getObjTimestamp location is_boot
1655
1656         return (Just ( ModSummary { ms_mod       = mod, 
1657                                     ms_hsc_src   = hsc_src,
1658                                     ms_location  = location,
1659                                     ms_hspp_file = hspp_fn,
1660                                     ms_hspp_opts = dflags',
1661                                     ms_hspp_buf  = Just buf,
1662                                     ms_srcimps   = srcimps,
1663                                     ms_imps      = the_imps,
1664                                     ms_hs_date   = src_timestamp,
1665                                     ms_obj_date  = obj_timestamp }))
1666
1667
1668 getObjTimestamp location is_boot
1669   = if is_boot then return Nothing
1670                else modificationTimeIfExists (ml_obj_file location)
1671
1672
1673 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1674   -> IO (DynFlags, FilePath, StringBuffer)
1675 preprocessFile dflags src_fn mb_phase Nothing
1676   = do
1677         (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1678         buf <- hGetStringBuffer hspp_fn
1679         return (dflags', hspp_fn, buf)
1680
1681 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1682   = do
1683         -- case we bypass the preprocessing stage?
1684         let 
1685             local_opts = getOptions buf src_fn
1686         --
1687         (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1688
1689         let
1690             needs_preprocessing
1691                 | Just (Unlit _) <- mb_phase    = True
1692                 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn  = True
1693                   -- note: local_opts is only required if there's no Unlit phase
1694                 | dopt Opt_Cpp dflags'          = True
1695                 | dopt Opt_Pp  dflags'          = True
1696                 | otherwise                     = False
1697
1698         when needs_preprocessing $
1699            ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1700
1701         return (dflags', src_fn, buf)
1702
1703
1704 -----------------------------------------------------------------------------
1705 --                      Error messages
1706 -----------------------------------------------------------------------------
1707
1708 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1709 -- ToDo: we don't have a proper line number for this error
1710 noModError dflags loc wanted_mod err
1711   = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1712                                 
1713 noHsFileErr loc path
1714   = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1715  
1716 packageModErr mod
1717   = throwDyn $ mkPlainErrMsg noSrcSpan $
1718         text "module" <+> quotes (ppr mod) <+> text "is a package module"
1719
1720 multiRootsErr :: [ModSummary] -> IO ()
1721 multiRootsErr summs@(summ1:_)
1722   = throwDyn $ mkPlainErrMsg noSrcSpan $
1723         text "module" <+> quotes (ppr mod) <+> 
1724         text "is defined in multiple files:" <+>
1725         sep (map text files)
1726   where
1727     mod = ms_mod summ1
1728     files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1729
1730 cyclicModuleErr :: [ModSummary] -> SDoc
1731 cyclicModuleErr ms
1732   = hang (ptext SLIT("Module imports form a cycle for modules:"))
1733        2 (vcat (map show_one ms))
1734   where
1735     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1736                         nest 2 $ ptext SLIT("imports:") <+> 
1737                                    (pp_imps HsBootFile (ms_srcimps ms)
1738                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
1739     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1740     pp_imps src mods = fsep (map (show_mod src) mods)
1741
1742
1743 -- | Inform GHC that the working directory has changed.  GHC will flush
1744 -- its cache of module locations, since it may no longer be valid.
1745 -- Note: if you change the working directory, you should also unload
1746 -- the current program (set targets to empty, followed by load).
1747 workingDirectoryChanged :: Session -> IO ()
1748 workingDirectoryChanged s = withSession s $ flushFinderCaches
1749
1750 -- -----------------------------------------------------------------------------
1751 -- inspecting the session
1752
1753 -- | Get the module dependency graph.
1754 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1755 getModuleGraph s = withSession s (return . hsc_mod_graph)
1756
1757 isLoaded :: Session -> ModuleName -> IO Bool
1758 isLoaded s m = withSession s $ \hsc_env ->
1759   return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1760
1761 getBindings :: Session -> IO [TyThing]
1762 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1763
1764 getPrintUnqual :: Session -> IO PrintUnqualified
1765 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1766
1767 -- | Container for information about a 'Module'.
1768 data ModuleInfo = ModuleInfo {
1769         minf_type_env  :: TypeEnv,
1770         minf_exports   :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1771         minf_rdr_env   :: Maybe GlobalRdrEnv,   -- Nothing for a compiled/package mod
1772         minf_instances :: [Instance]
1773 #ifdef GHCI
1774         ,minf_modBreaks :: ModBreaks 
1775 #endif
1776         -- ToDo: this should really contain the ModIface too
1777   }
1778         -- We don't want HomeModInfo here, because a ModuleInfo applies
1779         -- to package modules too.
1780
1781 -- | Request information about a loaded 'Module'
1782 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1783 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1784   let mg = hsc_mod_graph hsc_env
1785   if mdl `elem` map ms_mod mg
1786         then getHomeModuleInfo hsc_env (moduleName mdl)
1787         else do
1788   {- if isHomeModule (hsc_dflags hsc_env) mdl
1789         then return Nothing
1790         else -} getPackageModuleInfo hsc_env mdl
1791    -- getPackageModuleInfo will attempt to find the interface, so
1792    -- we don't want to call it for a home module, just in case there
1793    -- was a problem loading the module and the interface doesn't
1794    -- exist... hence the isHomeModule test here.  (ToDo: reinstate)
1795
1796 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1797 getPackageModuleInfo hsc_env mdl = do
1798 #ifdef GHCI
1799   (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1800   case mb_avails of
1801     Nothing -> return Nothing
1802     Just avails -> do
1803         eps <- readIORef (hsc_EPS hsc_env)
1804         let 
1805             names  = availsToNameSet avails
1806             pte    = eps_PTE eps
1807             tys    = [ ty | name <- concatMap availNames avails,
1808                             Just ty <- [lookupTypeEnv pte name] ]
1809         --
1810         return (Just (ModuleInfo {
1811                         minf_type_env  = mkTypeEnv tys,
1812                         minf_exports   = names,
1813                         minf_rdr_env   = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1814                         minf_instances = error "getModuleInfo: instances for package module unimplemented",
1815                         minf_modBreaks = emptyModBreaks  
1816                 }))
1817 #else
1818   -- bogusly different for non-GHCI (ToDo)
1819   return Nothing
1820 #endif
1821
1822 getHomeModuleInfo hsc_env mdl = 
1823   case lookupUFM (hsc_HPT hsc_env) mdl of
1824     Nothing  -> return Nothing
1825     Just hmi -> do
1826       let details = hm_details hmi
1827       return (Just (ModuleInfo {
1828                         minf_type_env  = md_types details,
1829                         minf_exports   = availsToNameSet (md_exports details),
1830                         minf_rdr_env   = mi_globals $! hm_iface hmi,
1831                         minf_instances = md_insts details
1832 #ifdef GHCI
1833                        ,minf_modBreaks = md_modBreaks details  
1834 #endif
1835                         }))
1836
1837 -- | The list of top-level entities defined in a module
1838 modInfoTyThings :: ModuleInfo -> [TyThing]
1839 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1840
1841 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1842 modInfoTopLevelScope minf
1843   = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1844
1845 modInfoExports :: ModuleInfo -> [Name]
1846 modInfoExports minf = nameSetToList $! minf_exports minf
1847
1848 -- | Returns the instances defined by the specified module.
1849 -- Warning: currently unimplemented for package modules.
1850 modInfoInstances :: ModuleInfo -> [Instance]
1851 modInfoInstances = minf_instances
1852
1853 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1854 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1855
1856 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1857 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1858
1859 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1860 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1861    case lookupTypeEnv (minf_type_env minf) name of
1862      Just tyThing -> return (Just tyThing)
1863      Nothing      -> do
1864        eps <- readIORef (hsc_EPS hsc_env)
1865        return $! lookupType (hsc_dflags hsc_env) 
1866                             (hsc_HPT hsc_env) (eps_PTE eps) name
1867
1868 #ifdef GHCI
1869 modInfoModBreaks = minf_modBreaks  
1870 #endif
1871
1872 isDictonaryId :: Id -> Bool
1873 isDictonaryId id
1874   = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1875
1876 -- | Looks up a global name: that is, any top-level name in any
1877 -- visible module.  Unlike 'lookupName', lookupGlobalName does not use
1878 -- the interactive context, and therefore does not require a preceding
1879 -- 'setContext'.
1880 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1881 lookupGlobalName s name = withSession s $ \hsc_env -> do
1882    eps <- readIORef (hsc_EPS hsc_env)
1883    return $! lookupType (hsc_dflags hsc_env) 
1884                         (hsc_HPT hsc_env) (eps_PTE eps) name
1885
1886 -- -----------------------------------------------------------------------------
1887 -- Misc exported utils
1888
1889 dataConType :: DataCon -> Type
1890 dataConType dc = idType (dataConWrapId dc)
1891
1892 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1893 pprParenSymName :: NamedThing a => a -> SDoc
1894 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1895
1896 -- ----------------------------------------------------------------------------
1897
1898 #if 0
1899
1900 -- ToDo:
1901 --   - Data and Typeable instances for HsSyn.
1902
1903 -- ToDo: check for small transformations that happen to the syntax in
1904 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1905
1906 -- ToDo: maybe use TH syntax instead of IfaceSyn?  There's already a way
1907 -- to get from TyCons, Ids etc. to TH syntax (reify).
1908
1909 -- :browse will use either lm_toplev or inspect lm_interface, depending
1910 -- on whether the module is interpreted or not.
1911
1912 -- This is for reconstructing refactored source code
1913 -- Calls the lexer repeatedly.
1914 -- ToDo: add comment tokens to token stream
1915 getTokenStream :: Session -> Module -> IO [Located Token]
1916 #endif
1917
1918 -- -----------------------------------------------------------------------------
1919 -- Interactive evaluation
1920
1921 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1922 -- filesystem and package database to find the corresponding 'Module', 
1923 -- using the algorithm that is used for an @import@ declaration.
1924 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1925 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1926   findModule' hsc_env mod_name maybe_pkg
1927
1928 findModule' hsc_env mod_name maybe_pkg =
1929   let
1930         dflags = hsc_dflags hsc_env
1931         hpt    = hsc_HPT hsc_env
1932         this_pkg = thisPackage dflags
1933   in
1934   case lookupUFM hpt mod_name of
1935     Just mod_info -> return (mi_module (hm_iface mod_info))
1936     _not_a_home_module -> do
1937           res <- findImportedModule hsc_env mod_name maybe_pkg
1938           case res of
1939             Found _ m | modulePackageId m /= this_pkg -> return m
1940                       | otherwise -> throwDyn (CmdLineError (showSDoc $
1941                                         text "module" <+> pprModule m <+>
1942                                         text "is not loaded"))
1943             err -> let msg = cannotFindModule dflags mod_name err in
1944                    throwDyn (CmdLineError (showSDoc msg))
1945
1946 #ifdef GHCI
1947
1948 -- | Set the interactive evaluation context.
1949 --
1950 -- Setting the context doesn't throw away any bindings; the bindings
1951 -- we've built up in the InteractiveContext simply move to the new
1952 -- module.  They always shadow anything in scope in the current context.
1953 setContext :: Session
1954            -> [Module]  -- entire top level scope of these modules
1955            -> [Module]  -- exports only of these modules
1956            -> IO ()
1957 setContext sess@(Session ref) toplev_mods export_mods = do 
1958   hsc_env <- readIORef ref
1959   let old_ic  = hsc_IC     hsc_env
1960       hpt     = hsc_HPT    hsc_env
1961   --
1962   export_env  <- mkExportEnv hsc_env export_mods
1963   toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1964   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1965   writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1966                                             ic_exports      = export_mods,
1967                                             ic_rn_gbl_env   = all_env }}
1968
1969 -- Make a GlobalRdrEnv based on the exports of the modules only.
1970 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1971 mkExportEnv hsc_env mods = do
1972   stuff <- mapM (getModuleExports hsc_env) mods
1973   let 
1974         (_msgs, mb_name_sets) = unzip stuff
1975         gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
1976                | (Just avails, mod) <- zip mb_name_sets mods ]
1977   --
1978   return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1979
1980 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1981 nameSetToGlobalRdrEnv names mod =
1982   mkGlobalRdrEnv [ GRE  { gre_name = name, gre_prov = vanillaProv mod }
1983                  | name <- nameSetToList names ]
1984
1985 vanillaProv :: ModuleName -> Provenance
1986 -- We're building a GlobalRdrEnv as if the user imported
1987 -- all the specified modules into the global interactive module
1988 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1989   where
1990     decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name, 
1991                          is_qual = False, 
1992                          is_dloc = srcLocSpan interactiveSrcLoc }
1993
1994 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1995 mkTopLevEnv hpt modl
1996   = case lookupUFM hpt (moduleName modl) of
1997       Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ 
1998                                                 showSDoc (ppr modl)))
1999       Just details ->
2000          case mi_globals (hm_iface details) of
2001                 Nothing  -> 
2002                    throwDyn (ProgramError ("mkTopLevEnv: not interpreted " 
2003                                                 ++ showSDoc (ppr modl)))
2004                 Just env -> return env
2005
2006 -- | Get the interactive evaluation context, consisting of a pair of the
2007 -- set of modules from which we take the full top-level scope, and the set
2008 -- of modules from which we take just the exports respectively.
2009 getContext :: Session -> IO ([Module],[Module])
2010 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
2011                                 return (ic_toplev_scope ic, ic_exports ic))
2012
2013 -- | Returns 'True' if the specified module is interpreted, and hence has
2014 -- its full top-level scope available.
2015 moduleIsInterpreted :: Session -> Module -> IO Bool
2016 moduleIsInterpreted s modl = withSession s $ \h ->
2017  if modulePackageId modl /= thisPackage (hsc_dflags h)
2018         then return False
2019         else case lookupUFM (hsc_HPT h) (moduleName modl) of
2020                 Just details       -> return (isJust (mi_globals (hm_iface details)))
2021                 _not_a_home_module -> return False
2022
2023 -- | Looks up an identifier in the current interactive context (for :info)
2024 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
2025 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
2026
2027 -- | Returns all names in scope in the current interactive context
2028 getNamesInScope :: Session -> IO [Name]
2029 getNamesInScope s = withSession s $ \hsc_env -> do
2030   return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
2031
2032 getRdrNamesInScope :: Session -> IO [RdrName]
2033 getRdrNamesInScope  s = withSession s $ \hsc_env -> do
2034   let env = ic_rn_gbl_env (hsc_IC hsc_env)
2035   return (concat (map greToRdrNames (globalRdrEnvElts env)))
2036
2037 -- ToDo: move to RdrName
2038 greToRdrNames :: GlobalRdrElt -> [RdrName]
2039 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
2040   = case prov of
2041      LocalDef -> [unqual]
2042      Imported specs -> concat (map do_spec (map is_decl specs))
2043   where
2044     occ = nameOccName name
2045     unqual = Unqual occ
2046     do_spec decl_spec
2047         | is_qual decl_spec = [qual]
2048         | otherwise         = [unqual,qual]
2049         where qual = Qual (is_as decl_spec) occ
2050
2051 -- | Parses a string as an identifier, and returns the list of 'Name's that
2052 -- the identifier can refer to in the current interactive context.
2053 parseName :: Session -> String -> IO [Name]
2054 parseName s str = withSession s $ \hsc_env -> do
2055    maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2056    case maybe_rdr_name of
2057         Nothing -> return []
2058         Just (L _ rdr_name) -> do
2059             mb_names <- tcRnLookupRdrName hsc_env rdr_name
2060             case mb_names of
2061                 Nothing -> return []
2062                 Just ns -> return ns
2063                 -- ToDo: should return error messages
2064
2065 -- | Returns the 'TyThing' for a 'Name'.  The 'Name' may refer to any
2066 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2067 lookupName :: Session -> Name -> IO (Maybe TyThing)
2068 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2069
2070 -- -----------------------------------------------------------------------------
2071 -- Getting the type of an expression
2072
2073 -- | Get the type of an expression
2074 exprType :: Session -> String -> IO (Maybe Type)
2075 exprType s expr = withSession s $ \hsc_env -> do
2076    maybe_stuff <- hscTcExpr hsc_env expr
2077    case maybe_stuff of
2078         Nothing -> return Nothing
2079         Just ty -> return (Just tidy_ty)
2080              where 
2081                 tidy_ty = tidyType emptyTidyEnv ty
2082
2083 -- -----------------------------------------------------------------------------
2084 -- Getting the kind of a type
2085
2086 -- | Get the kind of a  type
2087 typeKind  :: Session -> String -> IO (Maybe Kind)
2088 typeKind s str = withSession s $ \hsc_env -> do
2089    maybe_stuff <- hscKcType hsc_env str
2090    case maybe_stuff of
2091         Nothing -> return Nothing
2092         Just kind -> return (Just kind)
2093
2094 -----------------------------------------------------------------------------
2095 -- cmCompileExpr: compile an expression and deliver an HValue
2096
2097 compileExpr :: Session -> String -> IO (Maybe HValue)
2098 compileExpr s expr = withSession s $ \hsc_env -> do
2099   maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2100   case maybe_stuff of
2101         Nothing -> return Nothing
2102         Just (new_ic, names, hval) -> do
2103                         -- Run it!
2104                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2105
2106                 case (names,hvals) of
2107                   ([n],[hv]) -> return (Just hv)
2108                   _          -> panic "compileExpr"
2109
2110 -- -----------------------------------------------------------------------------
2111 -- Compile an expression into a dynamic
2112
2113 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2114 dynCompileExpr ses expr = do
2115     (full,exports) <- getContext ses
2116     setContext ses full $
2117         (mkModule
2118             (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2119         ):exports
2120     let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2121     res <- withSession ses (flip hscStmt stmt)
2122     setContext ses full exports
2123     case res of
2124         Nothing -> return Nothing
2125         Just (_, names, hvals) -> do
2126             vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2127             case (names,vals) of
2128                 (_:[], v:[])    -> return (Just v)
2129                 _               -> panic "dynCompileExpr"
2130
2131 -- -----------------------------------------------------------------------------
2132 -- running a statement interactively
2133
2134 data RunResult
2135   = RunOk [Name]                -- ^ names bound by this evaluation
2136   | RunFailed                   -- ^ statement failed compilation
2137   | RunException Exception      -- ^ statement raised an exception
2138   | RunBreak ThreadId [Name] BreakInfo ResumeHandle
2139
2140 data Status
2141    = Break HValue BreakInfo ThreadId ResumeHandle -- ^ the computation hit a breakpoint
2142    | Complete (Either Exception [HValue]) -- ^ the computation completed with either an exception or a value
2143
2144 data ResumeHandle = ResumeHandle (MVar ()) (MVar Status) [Name]
2145
2146 -- | Run a statement in the current interactive context.  Statement
2147 -- may bind multple values.
2148 runStmt :: Session -> String -> IO RunResult
2149 runStmt (Session ref) expr
2150    = do 
2151         hsc_env <- readIORef ref
2152
2153         breakMVar  <- newEmptyMVar  -- wait on this when we hit a breakpoint
2154         statusMVar <- newEmptyMVar  -- wait on this when a computation is running 
2155
2156         -- Turn off -fwarn-unused-bindings when running a statement, to hide
2157         -- warnings about the implicit bindings we introduce.
2158         let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2159             hsc_env' = hsc_env{ hsc_dflags = dflags' }
2160
2161         maybe_stuff <- hscStmt hsc_env' expr
2162
2163         case maybe_stuff of
2164            Nothing -> return RunFailed
2165            Just (new_hsc_env, names, hval) -> do
2166               writeIORef ref new_hsc_env
2167
2168               let resume_handle = ResumeHandle breakMVar statusMVar names
2169               -- set the onBreakAction to be performed when we hit a
2170               -- breakpoint this is visible in the Byte Code
2171               -- Interpreter, thus it is a global variable,
2172               -- implemented with stable pointers
2173               stablePtr <- setBreakAction resume_handle
2174
2175               let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2176               status <- sandboxIO statusMVar thing_to_run
2177               freeStablePtr stablePtr -- be careful not to leak stable pointers!
2178               handleRunStatus ref names status
2179
2180 handleRunStatus ref names status =
2181    case status of  
2182       -- did we hit a breakpoint or did we complete?
2183       (Break apStack info tid res) -> do
2184                 hsc_env <- readIORef ref
2185                 (new_hsc_env, names) <- extendEnvironment hsc_env apStack 
2186                                                 (breakInfo_vars info)
2187                 writeIORef ref new_hsc_env 
2188                 return (RunBreak tid names info res)
2189       (Complete either_hvals) ->
2190                 case either_hvals of
2191                     Left e -> return (RunException e)
2192                     Right hvals -> do
2193                         extendLinkEnv (zip names hvals)
2194                         return (RunOk names)
2195            
2196 -- this points to the IO action that is executed when a breakpoint is hit
2197 foreign import ccall "&breakPointIOAction" 
2198         breakPointIOAction :: Ptr (StablePtr (BreakInfo -> HValue -> IO ())) 
2199
2200 -- When running a computation, we redirect ^C exceptions to the running
2201 -- thread.  ToDo: we might want a way to continue even if the target
2202 -- thread doesn't die when it receives the exception... "this thread
2203 -- is not responding".
2204 sandboxIO :: MVar Status -> IO [HValue] -> IO Status
2205 sandboxIO statusMVar thing = do
2206   ts <- takeMVar interruptTargetThread
2207   child <- forkIO (do res <- Exception.try thing; putMVar statusMVar (Complete res))
2208   putMVar interruptTargetThread (child:ts)
2209   takeMVar statusMVar `finally` modifyMVar_ interruptTargetThread (return.tail)
2210
2211 setBreakAction res@(ResumeHandle breakMVar statusMVar names) = do 
2212   stablePtr <- newStablePtr onBreak
2213   poke breakPointIOAction stablePtr
2214   return stablePtr
2215   where onBreak ids apStack = do
2216                 tid <- myThreadId
2217                 putMVar statusMVar (Break apStack ids tid res)
2218                 takeMVar breakMVar
2219
2220 resume :: Session -> ResumeHandle -> IO RunResult
2221 resume (Session ref) res@(ResumeHandle breakMVar statusMVar names) = do
2222    stablePtr <- setBreakAction res
2223    putMVar breakMVar ()
2224    status <- takeMVar statusMVar
2225    handleRunStatus ref names status
2226
2227 {-
2228 -- This version of sandboxIO runs the expression in a completely new
2229 -- RTS main thread.  It is disabled for now because ^C exceptions
2230 -- won't be delivered to the new thread, instead they'll be delivered
2231 -- to the (blocked) GHCi main thread.
2232
2233 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2234
2235 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2236 sandboxIO thing = do
2237   st_thing <- newStablePtr (Exception.try thing)
2238   alloca $ \ p_st_result -> do
2239     stat <- rts_evalStableIO st_thing p_st_result
2240     freeStablePtr st_thing
2241     if stat == 1
2242         then do st_result <- peek p_st_result
2243                 result <- deRefStablePtr st_result
2244                 freeStablePtr st_result
2245                 return (Right result)
2246         else do
2247                 return (Left (fromIntegral stat))
2248
2249 foreign import "rts_evalStableIO"  {- safe -}
2250   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2251   -- more informative than the C type!
2252
2253 XXX the type of rts_evalStableIO no longer matches the above
2254
2255 -}
2256
2257 -- -----------------------------------------------------------------------------
2258 -- After stopping at a breakpoint, add free variables to the environment
2259
2260 -- Todo: turn this into a primop, and provide special version(s) for unboxed things
2261 foreign import ccall "rts_getApStackVal" getApStackVal :: StablePtr a -> Int -> IO (StablePtr b)
2262
2263 getIdValFromApStack :: a -> (Id, Int) -> IO (Id, HValue)
2264 getIdValFromApStack apStack (identifier, stackDepth) = do
2265    -- ToDo: check the type of the identifer and decide whether it is unboxed or not
2266    apSptr <- newStablePtr apStack
2267    resultSptr <- getApStackVal apSptr (stackDepth - 1)
2268    result <- deRefStablePtr resultSptr
2269    freeStablePtr apSptr
2270    freeStablePtr resultSptr 
2271    return (identifier, unsafeCoerce# result)
2272
2273 extendEnvironment :: HscEnv -> a -> [(Id, Int)] -> IO (HscEnv, [Name])
2274 extendEnvironment hsc_env apStack idsOffsets = do
2275    idsVals <- mapM (getIdValFromApStack apStack) idsOffsets 
2276    let (ids, hValues) = unzip idsVals 
2277    let names = map idName ids
2278    let global_ids = map globaliseAndTidy ids
2279    typed_ids  <- mapM instantiateIdType global_ids
2280    let ictxt = hsc_IC hsc_env
2281        rn_env   = ic_rn_local_env ictxt
2282        type_env = ic_type_env ictxt
2283        bound_names = map idName typed_ids
2284        new_rn_env  = extendLocalRdrEnv rn_env bound_names
2285        -- Remove any shadowed bindings from the type_env;
2286        -- they are inaccessible but might, I suppose, cause 
2287        -- a space leak if we leave them there
2288        shadowed = [ n | name <- bound_names,
2289                     let rdr_name = mkRdrUnqual (nameOccName name),
2290                     Just n <- [lookupLocalRdrEnv rn_env rdr_name] ]
2291        filtered_type_env = delListFromNameEnv type_env shadowed
2292        new_type_env = extendTypeEnvWithIds filtered_type_env (typed_ids)
2293        new_ic = ictxt { ic_rn_local_env = new_rn_env, 
2294                         ic_type_env     = new_type_env }
2295    extendLinkEnv (zip names hValues) -- ToDo: we must remember to restore the old env after we finish a breakpoint
2296    return (hsc_env{hsc_IC = new_ic}, names)
2297   where
2298    globaliseAndTidy :: Id -> Id
2299    globaliseAndTidy id
2300       = let tidied_type = tidyTopType$ idType id
2301         in setIdType (globaliseId VanillaGlobal id) tidied_type
2302
2303    -- | Instantiate the tyVars with GHC.Base.Unknown
2304    instantiateIdType :: Id -> IO Id
2305    instantiateIdType id = do
2306       instantiatedType <- instantiateTyVarsToUnknown hsc_env (idType id)
2307       return$ setIdType id instantiatedType
2308
2309 -----------------------------------------------------------------------------
2310 -- show a module and it's source/object filenames
2311
2312 showModule :: Session -> ModSummary -> IO String
2313 showModule s mod_summary = withSession s $                        \hsc_env -> 
2314                            isModuleInterpreted s mod_summary >>=  \interpreted -> 
2315                            return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
2316
2317 isModuleInterpreted :: Session -> ModSummary -> IO Bool
2318 isModuleInterpreted s mod_summary = withSession s $ \hsc_env -> 
2319   case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2320         Nothing       -> panic "missing linkable"
2321         Just mod_info -> return (not obj_linkable)
2322                       where
2323                          obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
2324
2325 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2326 obtainTerm1 sess force mb_ty x = withSession sess $ \hsc_env -> cvObtainTerm hsc_env force mb_ty (unsafeCoerce# x)
2327
2328 obtainTerm :: Session -> Bool -> Id -> IO (Maybe Term)
2329 obtainTerm sess force id = withSession sess $ \hsc_env -> do
2330               mb_v <- getHValue (varName id) 
2331               case mb_v of
2332                 Just v  -> fmap Just$ cvObtainTerm hsc_env force (Just$ idType id) v
2333                 Nothing -> return Nothing
2334
2335 #endif /* GHCI */