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