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