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