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