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