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