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