[project @ 2005-05-05 09:40:37 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,
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 )
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 then summariseFile hsc_env file maybe_buf else do
1216                 throwDyn (CmdLineError ("can't find file: " ++ file))   
1217         getRootSummary (Target (TargetModule modl) maybe_buf)
1218            = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False 
1219                                            modl maybe_buf excl_mods
1220                 case maybe_summary of
1221                    Nothing -> packageModErr modl
1222                    Just s  -> return s
1223
1224         -- In a root module, the filename is allowed to diverge from the module
1225         -- name, so we have to check that there aren't multiple root files
1226         -- defining the same module (otherwise the duplicates will be silently
1227         -- ignored, leading to confusing behaviour).
1228         checkDuplicates :: [ModSummary] -> IO ()
1229         checkDuplicates summaries = mapM_ check summaries
1230           where check summ = 
1231                   case dups of
1232                         []     -> return ()
1233                         [_one] -> return ()
1234                         many   -> multiRootsErr modl many
1235                    where modl = ms_mod summ
1236                          dups = 
1237                            [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1238                            | summ' <- summaries, ms_mod summ' == modl ]
1239
1240         loop :: [(FilePath,Module,IsBootInterface)]
1241                         -- Work list: process these modules
1242              -> NodeMap ModSummary
1243                         -- Visited set
1244              -> IO [ModSummary]
1245                         -- The result includes the worklist, except
1246                         -- for those mentioned in the visited set
1247         loop [] done      = return (nodeMapElts done)
1248         loop ((cur_path, wanted_mod, is_boot) : ss) done 
1249           | key `elemFM` done = loop ss done
1250           | otherwise         = do { mb_s <- summarise hsc_env old_summary_map 
1251                                                  (Just cur_path) is_boot 
1252                                                  wanted_mod Nothing excl_mods
1253                                    ; case mb_s of
1254                                         Nothing -> loop ss done
1255                                         Just s  -> loop (msDeps s ++ ss) 
1256                                                         (addToFM done key s) }
1257           where
1258             key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1259
1260 msDeps :: ModSummary -> [(FilePath,             -- Importing module
1261                           Module,               -- Imported module
1262                           IsBootInterface)]      -- {-# SOURCE #-} import or not
1263 -- (msDeps s) returns the dependencies of the ModSummary s.
1264 -- A wrinkle is that for a {-# SOURCE #-} import we return
1265 --      *both* the hs-boot file
1266 --      *and* the source file
1267 -- as "dependencies".  That ensures that the list of all relevant
1268 -- modules always contains B.hs if it contains B.hs-boot.
1269 -- Remember, this pass isn't doing the topological sort.  It's
1270 -- just gathering the list of all relevant ModSummaries
1271 msDeps s =  concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s] 
1272          ++ [(f,m,False) | m <- ms_imps    s] 
1273         where
1274           f = msHsFilePath s    -- Keep the importing module for error reporting
1275
1276
1277 -----------------------------------------------------------------------------
1278 -- Summarising modules
1279
1280 -- We have two types of summarisation:
1281 --
1282 --    * Summarise a file.  This is used for the root module(s) passed to
1283 --      cmLoadModules.  The file is read, and used to determine the root
1284 --      module name.  The module name may differ from the filename.
1285 --
1286 --    * Summarise a module.  We are given a module name, and must provide
1287 --      a summary.  The finder is used to locate the file in which the module
1288 --      resides.
1289
1290 summariseFile :: HscEnv -> FilePath
1291    -> Maybe (StringBuffer,ClockTime)
1292    -> IO ModSummary
1293 -- Used for Haskell source only, I think
1294 -- We know the file name, and we know it exists,
1295 -- but we don't necessarily know the module name (might differ)
1296 summariseFile hsc_env file maybe_buf
1297    = do let dflags = hsc_dflags hsc_env
1298
1299         (dflags', hspp_fn, buf)
1300             <- preprocessFile dflags file maybe_buf
1301
1302         (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1303
1304         -- Make a ModLocation for this file
1305         location <- mkHomeModLocation dflags mod file
1306
1307         -- Tell the Finder cache where it is, so that subsequent calls
1308         -- to findModule will find it, even if it's not on any search path
1309         addHomeModuleToFinder hsc_env mod location
1310
1311         src_timestamp <- case maybe_buf of
1312                            Just (_,t) -> return t
1313                            Nothing    -> getModificationTime file
1314
1315         obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1316
1317         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1318                              ms_location = location,
1319                              ms_hspp_file = Just hspp_fn,
1320                              ms_hspp_buf  = Just buf,
1321                              ms_srcimps = srcimps, ms_imps = the_imps,
1322                              ms_hs_date = src_timestamp,
1323                              ms_obj_date = obj_timestamp })
1324
1325 -- Summarise a module, and pick up source and timestamp.
1326 summarise :: HscEnv
1327           -> NodeMap ModSummary -- Map of old summaries
1328           -> Maybe FilePath     -- Importing module (for error messages)
1329           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1330           -> Module             -- Imported module to be summarised
1331           -> Maybe (StringBuffer, ClockTime)
1332           -> [Module]           -- Modules to exclude
1333           -> IO (Maybe ModSummary)      -- Its new summary
1334
1335 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1336   | wanted_mod `elem` excl_mods
1337   = return Nothing
1338
1339   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1340   = do          -- Find its new timestamp; all the 
1341                 -- ModSummaries in the old map have valid ml_hs_files
1342         let location = ms_location old_summary
1343             src_fn = expectJust "summarise" (ml_hs_file location)
1344
1345                 -- return the cached summary if the source didn't change
1346         src_timestamp <- case maybe_buf of
1347                            Just (_,t) -> return t
1348                            Nothing    -> getModificationTime src_fn
1349
1350         if ms_hs_date old_summary == src_timestamp 
1351            then do -- update the object-file timestamp
1352                   obj_timestamp <- getObjTimestamp location is_boot
1353                   return (Just old_summary{ ms_obj_date = obj_timestamp })
1354            else
1355                 -- source changed: re-summarise
1356                 new_summary location src_fn maybe_buf src_timestamp
1357
1358   | otherwise
1359   = do  found <- findModule hsc_env wanted_mod True {-explicit-}
1360         case found of
1361              Found location pkg 
1362                 | not (isHomePackage pkg) -> return Nothing
1363                         -- Drop external-pkg
1364                 | isJust (ml_hs_file location) -> just_found location
1365                         -- Home package
1366              err -> noModError dflags cur_mod wanted_mod err
1367                         -- Not found
1368   where
1369     dflags = hsc_dflags hsc_env
1370
1371     hsc_src = if is_boot then HsBootFile else HsSrcFile
1372
1373     just_found location = do
1374                 -- Adjust location to point to the hs-boot source file, 
1375                 -- hi file, object file, when is_boot says so
1376         let location' | is_boot   = addBootSuffixLocn location
1377                       | otherwise = location
1378             src_fn = expectJust "summarise2" (ml_hs_file location')
1379
1380                 -- Check that it exists
1381                 -- It might have been deleted since the Finder last found it
1382         maybe_t <- modificationTimeIfExists src_fn
1383         case maybe_t of
1384           Nothing -> noHsFileErr cur_mod src_fn
1385           Just t  -> new_summary location' src_fn Nothing t
1386
1387
1388     new_summary location src_fn maybe_bug src_timestamp
1389       = do
1390         -- Preprocess the source file and get its imports
1391         -- The dflags' contains the OPTIONS pragmas
1392         (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1393         (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1394
1395         when (mod_name /= wanted_mod) $
1396                 throwDyn (ProgramError 
1397                    (showSDoc (text src_fn
1398                               <>  text ": file name does not match module name"
1399                               <+> quotes (ppr mod_name))))
1400
1401                 -- Find the object timestamp, and return the summary
1402         obj_timestamp <- getObjTimestamp location is_boot
1403
1404         return (Just ( ModSummary { ms_mod       = wanted_mod, 
1405                                     ms_hsc_src   = hsc_src,
1406                                     ms_location  = location,
1407                                     ms_hspp_file = Just hspp_fn,
1408                                     ms_hspp_buf  = Just buf,
1409                                     ms_srcimps   = srcimps,
1410                                     ms_imps      = the_imps,
1411                                     ms_hs_date   = src_timestamp,
1412                                     ms_obj_date  = obj_timestamp }))
1413
1414
1415 getObjTimestamp location is_boot
1416   = if is_boot then return Nothing
1417                else modificationTimeIfExists (ml_obj_file location)
1418
1419
1420 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1421   -> IO (DynFlags, FilePath, StringBuffer)
1422 preprocessFile dflags src_fn Nothing
1423   = do
1424         (dflags', hspp_fn) <- preprocess dflags src_fn
1425         buf <- hGetStringBuffer hspp_fn
1426         return (dflags', hspp_fn, buf)
1427
1428 preprocessFile dflags src_fn (Just (buf, time))
1429   = do
1430         -- case we bypass the preprocessing stage?
1431         let 
1432             local_opts = getOptionsFromStringBuffer buf
1433         --
1434         (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1435
1436         let
1437             needs_preprocessing
1438                 | Unlit _ <- startPhase src_fn  = True
1439                   -- note: local_opts is only required if there's no Unlit phase
1440                 | dopt Opt_Cpp dflags'          = True
1441                 | dopt Opt_Pp  dflags'          = True
1442                 | otherwise                     = False
1443
1444         when needs_preprocessing $
1445            ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1446
1447         return (dflags', src_fn, buf)
1448
1449
1450 -----------------------------------------------------------------------------
1451 --                      Error messages
1452 -----------------------------------------------------------------------------
1453
1454 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1455 -- ToDo: we don't have a proper line number for this error
1456 noModError dflags cur_mod wanted_mod err
1457   = throwDyn $ ProgramError $ showSDoc $
1458     vcat [cantFindError dflags wanted_mod err,
1459           nest 2 (parens (pp_where cur_mod))]
1460                                 
1461 noHsFileErr cur_mod path
1462   = throwDyn $ CmdLineError $ showSDoc $
1463     vcat [text "Can't find" <+> text path,
1464           nest 2 (parens (pp_where cur_mod))]
1465  
1466 pp_where Nothing  = text "one of the roots of the dependency analysis"
1467 pp_where (Just p) = text "imported from" <+> text p
1468
1469 packageModErr mod
1470   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1471                                    quotes (ppr mod) <+>
1472                                    text "is a package module")))
1473
1474 multiRootsErr mod files
1475   = throwDyn (ProgramError (showSDoc (
1476         text "module" <+> quotes (ppr mod) <+> 
1477         text "is defined in multiple files:" <+>
1478         sep (map text files))))
1479
1480 cyclicModuleErr :: [ModSummary] -> SDoc
1481 cyclicModuleErr ms
1482   = hang (ptext SLIT("Module imports form a cycle for modules:"))
1483        2 (vcat (map show_one ms))
1484   where
1485     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1486                         nest 2 $ ptext SLIT("imports:") <+> 
1487                                    (pp_imps HsBootFile (ms_srcimps ms)
1488                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
1489     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1490     pp_imps src mods = fsep (map (show_mod src) mods)
1491
1492
1493 -- | Inform GHC that the working directory has changed.  GHC will flush
1494 -- its cache of module locations, since it may no longer be valid.
1495 -- Note: if you change the working directory, you should also unload
1496 -- the current program (set targets to empty, followed by load).
1497 workingDirectoryChanged :: Session -> IO ()
1498 workingDirectoryChanged s = withSession s $ \hsc_env ->
1499   flushFinderCache (hsc_FC hsc_env)
1500
1501 -- -----------------------------------------------------------------------------
1502 -- inspecting the session
1503
1504 -- | Get the module dependency graph.
1505 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1506 getModuleGraph s = withSession s (return . hsc_mod_graph)
1507
1508 isLoaded :: Session -> Module -> IO Bool
1509 isLoaded s m = withSession s $ \hsc_env ->
1510   return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1511
1512 getBindings :: Session -> IO [TyThing]
1513 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1514
1515 getPrintUnqual :: Session -> IO PrintUnqualified
1516 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1517
1518 -- | Container for information about a 'Module'.
1519 data ModuleInfo = ModuleInfo {
1520         minf_type_env :: TypeEnv,
1521         minf_exports  :: NameSet,
1522         minf_rdr_env  :: Maybe GlobalRdrEnv
1523   }
1524         -- ToDo: this should really contain the ModIface too
1525         -- We don't want HomeModInfo here, because a ModuleInfo applies
1526         -- to package modules too.
1527
1528 -- | Request information about a loaded 'Module'
1529 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1530 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1531   case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1532     Nothing  -> do
1533 #ifdef GHCI
1534         mb_names <- getModuleExports hsc_env mdl
1535         case mb_names of
1536            Nothing -> return Nothing
1537            Just names -> do
1538                 eps <- readIORef (hsc_EPS hsc_env)
1539                 let 
1540                     pte    = eps_PTE eps
1541                     n_list = nameSetToList names
1542                     tys    = [ ty | name <- n_list,
1543                                     Just ty <- [lookupTypeEnv pte name] ]
1544                 --
1545                 return (Just (ModuleInfo {
1546                                 minf_type_env = mkTypeEnv tys,
1547                                 minf_exports  = names,
1548                                 minf_rdr_env  = Just $! nameSetToGlobalRdrEnv names mdl
1549                         }))
1550 #else
1551         -- bogusly different for non-GHCI (ToDo)
1552         return Nothing
1553 #endif
1554     Just hmi -> 
1555         let details = hm_details hmi in
1556         return (Just (ModuleInfo {
1557                         minf_type_env = md_types details,
1558                         minf_exports  = md_exports details,
1559                         minf_rdr_env  = mi_globals $! hm_iface hmi
1560                         }))
1561
1562         -- ToDo: we should be able to call getModuleInfo on a package module,
1563         -- even one that isn't loaded yet.
1564
1565 -- | The list of top-level entities defined in a module
1566 modInfoTyThings :: ModuleInfo -> [TyThing]
1567 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1568
1569 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1570 modInfoTopLevelScope minf
1571   = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1572
1573 modInfoExports :: ModuleInfo -> [Name]
1574 modInfoExports minf = nameSetToList $! minf_exports minf
1575
1576 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1577 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1578
1579 isDictonaryId :: Id -> Bool
1580 isDictonaryId id
1581   = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1582
1583 -- | Looks up a global name: that is, any top-level name in any
1584 -- visible module.  Unlike 'lookupName', lookupGlobalName does not use
1585 -- the interactive context, and therefore does not require a preceding
1586 -- 'setContext'.
1587 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1588 lookupGlobalName s name = withSession s $ \hsc_env -> do
1589    eps <- readIORef (hsc_EPS hsc_env)
1590    return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1591
1592 #if 0
1593
1594 data ObjectCode
1595   = ByteCode
1596   | BinaryCode FilePath
1597
1598 -- ToDo: typechecks abstract syntax or renamed abstract syntax.  Issues:
1599 --   - typechecked syntax includes extra dictionary translation and
1600 --     AbsBinds which need to be translated back into something closer to
1601 --     the original source.
1602
1603 -- ToDo:
1604 --   - Data and Typeable instances for HsSyn.
1605
1606 -- ToDo:
1607 --   - things that aren't in the output of the renamer:
1608 --     - the export list
1609 --     - the imports
1610
1611 -- ToDo:
1612 --   - things that aren't in the output of the typechecker right now:
1613 --     - the export list
1614 --     - the imports
1615 --     - type signatures
1616 --     - type/data/newtype declarations
1617 --     - class declarations
1618 --     - instances
1619 --   - extra things in the typechecker's output:
1620 --     - default methods are turned into top-level decls.
1621 --     - dictionary bindings
1622
1623 -- ToDo: check for small transformations that happen to the syntax in
1624 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1625
1626 -- ToDo: maybe use TH syntax instead of IfaceSyn?  There's already a way
1627 -- to get from TyCons, Ids etc. to TH syntax (reify).
1628
1629 -- :browse will use either lm_toplev or inspect lm_interface, depending
1630 -- on whether the module is interpreted or not.
1631
1632 -- This is for reconstructing refactored source code
1633 -- Calls the lexer repeatedly.
1634 -- ToDo: add comment tokens to token stream
1635 getTokenStream :: Session -> Module -> IO [Located Token]
1636 #endif
1637
1638 -- -----------------------------------------------------------------------------
1639 -- Interactive evaluation
1640
1641 #ifdef GHCI
1642
1643 -- | Set the interactive evaluation context.
1644 --
1645 -- Setting the context doesn't throw away any bindings; the bindings
1646 -- we've built up in the InteractiveContext simply move to the new
1647 -- module.  They always shadow anything in scope in the current context.
1648 setContext :: Session
1649            -> [Module]  -- entire top level scope of these modules
1650            -> [Module]  -- exports only of these modules
1651            -> IO ()
1652 setContext (Session ref) toplevs exports = do 
1653   hsc_env <- readIORef ref
1654   let old_ic  = hsc_IC     hsc_env
1655       hpt     = hsc_HPT    hsc_env
1656
1657   mapM_ (checkModuleExists hsc_env hpt) exports
1658   export_env  <- mkExportEnv hsc_env exports
1659   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1660   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1661   writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1662                                             ic_exports      = exports,
1663                                             ic_rn_gbl_env   = all_env } }
1664
1665 -- Make a GlobalRdrEnv based on the exports of the modules only.
1666 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1667 mkExportEnv hsc_env mods = do
1668   mb_name_sets <- mapM (getModuleExports hsc_env) mods
1669   let 
1670         gres = [ nameSetToGlobalRdrEnv name_set mod
1671                | (Just name_set, mod) <- zip mb_name_sets mods ]
1672   --
1673   return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1674
1675 nameSetToGlobalRdrEnv :: NameSet -> Module -> GlobalRdrEnv
1676 nameSetToGlobalRdrEnv names mod =
1677   mkGlobalRdrEnv [ GRE  { gre_name = name, gre_prov = vanillaProv mod }
1678                  | name <- nameSetToList names ]
1679
1680 vanillaProv :: Module -> Provenance
1681 -- We're building a GlobalRdrEnv as if the user imported
1682 -- all the specified modules into the global interactive module
1683 vanillaProv mod = Imported [ImportSpec { is_mod = mod, is_as = mod, 
1684                                          is_qual = False, is_explicit = False,
1685                                          is_loc = srcLocSpan interactiveSrcLoc }]
1686
1687 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1688 checkModuleExists hsc_env hpt mod = 
1689   case lookupModuleEnv hpt mod of
1690     Just mod_info -> return ()
1691     _not_a_home_module -> do
1692           res <- findPackageModule hsc_env mod True
1693           case res of
1694             Found _ _ -> return  ()
1695             err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1696                    throwDyn (CmdLineError (showSDoc msg))
1697
1698 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1699 mkTopLevEnv hpt modl
1700  = case lookupModuleEnv hpt modl of
1701       Nothing ->        
1702          throwDyn (ProgramError ("mkTopLevEnv: not a home module " 
1703                         ++ showSDoc (pprModule modl)))
1704       Just details ->
1705          case mi_globals (hm_iface details) of
1706                 Nothing  -> 
1707                    throwDyn (ProgramError ("mkTopLevEnv: not interpreted " 
1708                                                 ++ showSDoc (pprModule modl)))
1709                 Just env -> return env
1710
1711 -- | Get the interactive evaluation context, consisting of a pair of the
1712 -- set of modules from which we take the full top-level scope, and the set
1713 -- of modules from which we take just the exports respectively.
1714 getContext :: Session -> IO ([Module],[Module])
1715 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1716                                 return (ic_toplev_scope ic, ic_exports ic))
1717
1718 -- | Returns 'True' if the specified module is interpreted, and hence has
1719 -- its full top-level scope available.
1720 moduleIsInterpreted :: Session -> Module -> IO Bool
1721 moduleIsInterpreted s modl = withSession s $ \h ->
1722  case lookupModuleEnv (hsc_HPT h) modl of
1723       Just details       -> return (isJust (mi_globals (hm_iface details)))
1724       _not_a_home_module -> return False
1725
1726 -- | Looks up an identifier in the current interactive context (for :info)
1727 {-# DEPRECATED getInfo "we should be using parseName/lookupName instead" #-}
1728 getInfo :: Session -> String -> IO [GetInfoResult]
1729 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1730
1731 -- | Returns all names in scope in the current interactive context
1732 getNamesInScope :: Session -> IO [Name]
1733 getNamesInScope s = withSession s $ \hsc_env -> do
1734   return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1735
1736 -- | Parses a string as an identifier, and returns the list of 'Name's that
1737 -- the identifier can refer to in the current interactive context.
1738 parseName :: Session -> String -> IO [Name]
1739 parseName s str = withSession s $ \hsc_env -> do
1740    maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1741    case maybe_rdr_name of
1742         Nothing -> return []
1743         Just (L _ rdr_name) -> do
1744             mb_names <- tcRnLookupRdrName hsc_env rdr_name
1745             case mb_names of
1746                 Nothing -> return []
1747                 Just ns -> return ns
1748                 -- ToDo: should return error messages
1749
1750 -- | Returns the 'TyThing' for a 'Name'.  The 'Name' may refer to any
1751 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1752 lookupName :: Session -> Name -> IO (Maybe TyThing)
1753 lookupName s name = withSession s $ \hsc_env -> do
1754   case lookupTypeEnv (ic_type_env (hsc_IC hsc_env)) name of
1755         Just tt -> return (Just tt)
1756         Nothing -> do
1757             eps <- readIORef (hsc_EPS hsc_env)
1758             return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1759
1760 -- -----------------------------------------------------------------------------
1761 -- Getting the type of an expression
1762
1763 -- | Get the type of an expression
1764 exprType :: Session -> String -> IO (Maybe Type)
1765 exprType s expr = withSession s $ \hsc_env -> do
1766    maybe_stuff <- hscTcExpr hsc_env expr
1767    case maybe_stuff of
1768         Nothing -> return Nothing
1769         Just ty -> return (Just tidy_ty)
1770              where 
1771                 tidy_ty = tidyType emptyTidyEnv ty
1772                 dflags  = hsc_dflags hsc_env
1773
1774 -- -----------------------------------------------------------------------------
1775 -- Getting the kind of a type
1776
1777 -- | Get the kind of a  type
1778 typeKind  :: Session -> String -> IO (Maybe Kind)
1779 typeKind s str = withSession s $ \hsc_env -> do
1780    maybe_stuff <- hscKcType hsc_env str
1781    case maybe_stuff of
1782         Nothing -> return Nothing
1783         Just kind -> return (Just kind)
1784
1785 -----------------------------------------------------------------------------
1786 -- cmCompileExpr: compile an expression and deliver an HValue
1787
1788 compileExpr :: Session -> String -> IO (Maybe HValue)
1789 compileExpr s expr = withSession s $ \hsc_env -> do
1790   maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1791   case maybe_stuff of
1792         Nothing -> return Nothing
1793         Just (new_ic, names, hval) -> do
1794                         -- Run it!
1795                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1796
1797                 case (names,hvals) of
1798                   ([n],[hv]) -> return (Just hv)
1799                   _          -> panic "compileExpr"
1800
1801 -- -----------------------------------------------------------------------------
1802 -- running a statement interactively
1803
1804 data RunResult
1805   = RunOk [Name]                -- ^ names bound by this evaluation
1806   | RunFailed                   -- ^ statement failed compilation
1807   | RunException Exception      -- ^ statement raised an exception
1808
1809 -- | Run a statement in the current interactive context.  Statemenet
1810 -- may bind multple values.
1811 runStmt :: Session -> String -> IO RunResult
1812 runStmt (Session ref) expr
1813    = do 
1814         hsc_env <- readIORef ref
1815
1816         -- Turn off -fwarn-unused-bindings when running a statement, to hide
1817         -- warnings about the implicit bindings we introduce.
1818         let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1819             hsc_env' = hsc_env{ hsc_dflags = dflags' }
1820
1821         maybe_stuff <- hscStmt hsc_env' expr
1822
1823         case maybe_stuff of
1824            Nothing -> return RunFailed
1825            Just (new_hsc_env, names, hval) -> do
1826
1827                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1828                 either_hvals <- sandboxIO thing_to_run
1829
1830                 case either_hvals of
1831                     Left e -> do
1832                         -- on error, keep the *old* interactive context,
1833                         -- so that 'it' is not bound to something
1834                         -- that doesn't exist.
1835                         return (RunException e)
1836
1837                     Right hvals -> do
1838                         -- Get the newly bound things, and bind them.  
1839                         -- Don't need to delete any shadowed bindings;
1840                         -- the new ones override the old ones. 
1841                         extendLinkEnv (zip names hvals)
1842                         
1843                         writeIORef ref new_hsc_env
1844                         return (RunOk names)
1845
1846
1847 -- We run the statement in a "sandbox" to protect the rest of the
1848 -- system from anything the expression might do.  For now, this
1849 -- consists of just wrapping it in an exception handler, but see below
1850 -- for another version.
1851
1852 sandboxIO :: IO a -> IO (Either Exception a)
1853 sandboxIO thing = Exception.try thing
1854
1855 {-
1856 -- This version of sandboxIO runs the expression in a completely new
1857 -- RTS main thread.  It is disabled for now because ^C exceptions
1858 -- won't be delivered to the new thread, instead they'll be delivered
1859 -- to the (blocked) GHCi main thread.
1860
1861 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1862
1863 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1864 sandboxIO thing = do
1865   st_thing <- newStablePtr (Exception.try thing)
1866   alloca $ \ p_st_result -> do
1867     stat <- rts_evalStableIO st_thing p_st_result
1868     freeStablePtr st_thing
1869     if stat == 1
1870         then do st_result <- peek p_st_result
1871                 result <- deRefStablePtr st_result
1872                 freeStablePtr st_result
1873                 return (Right result)
1874         else do
1875                 return (Left (fromIntegral stat))
1876
1877 foreign import "rts_evalStableIO"  {- safe -}
1878   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1879   -- more informative than the C type!
1880 -}
1881
1882 -- ---------------------------------------------------------------------------
1883 -- cmBrowseModule: get all the TyThings defined in a module
1884
1885 {-# DEPRECATED browseModule "we should be using getModuleInfo instead" #-}
1886 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1887 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1888   mb_decls <- getModuleContents hsc_env modl exports_only
1889   case mb_decls of
1890         Nothing -> return []            -- An error of some kind
1891         Just ds -> return ds
1892
1893
1894 -----------------------------------------------------------------------------
1895 -- show a module and it's source/object filenames
1896
1897 showModule :: Session -> ModSummary -> IO String
1898 showModule s mod_summary = withSession s $ \hsc_env -> do
1899   case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1900         Nothing       -> panic "missing linkable"
1901         Just mod_info -> return (showModMsg obj_linkable mod_summary)
1902                       where
1903                          obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))
1904
1905 #endif /* GHCI */