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