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