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