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