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