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