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