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