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