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