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