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