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