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