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