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