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