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