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