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