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