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