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