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