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