GHC.hs 71.3 KB
Newer Older
1
-- -----------------------------------------------------------------------------
2
--
3
-- (c) The University of Glasgow, 2005
4
5
6
--
-- The GHC API
--
7
-- -----------------------------------------------------------------------------
8
9
10

module GHC (
	-- * Initialisation
11
	Session,
12
13
	defaultErrorHandler,
	defaultCleanupHandler,
14
	init, initFromArgs,
15
16
17
	newSession,

	-- * Flags and settings
18
	DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
19
	parseDynamicFlags,
20
	initPackages,
21
22
	getSessionDynFlags,
	setSessionDynFlags,
23
24

	-- * Targets
25
	Target(..), TargetId(..), Phase,
26
27
28
	setTargets,
	getTargets,
	addTarget,
29
	removeTarget,
30
31
	guessTarget,
	
32
	-- * Loading\/compiling the program
33
	depanal,
34
	load, LoadHowMuch(..), SuccessFlag(..),	-- also does depanal
35
	workingDirectoryChanged,
36
	checkModule, CheckedModule(..),
37
	TypecheckedSource, ParsedSource, RenamedSource,
38
39

	-- * Inspecting the module structure of the program
40
	ModuleGraph, ModSummary(..), ModLocation(..),
41
	getModuleGraph,
42
	isLoaded,
43
44
	topSortModuleGraph,

45
46
47
48
	-- * Inspecting modules
	ModuleInfo,
	getModuleInfo,
	modInfoTyThings,
49
	modInfoTopLevelScope,
50
51
	modInfoPrintUnqualified,
	modInfoExports,
52
	modInfoInstances,
53
54
	modInfoIsExportedName,
	modInfoLookupName,
55
	lookupGlobalName,
56

57
58
59
	-- * Printing
	PrintUnqualified, alwaysQualify,

60
61
62
63
	-- * Interactive evaluation
	getBindings, getPrintUnqual,
#ifdef GHCI
	setContext, getContext,	
64
	getNamesInScope,
Simon Marlow's avatar
Simon Marlow committed
65
	getRdrNamesInScope,
66
	moduleIsInterpreted,
67
	getInfo,
68
69
	exprType,
	typeKind,
70
	parseName,
71
72
73
74
	RunResult(..),
	runStmt,
	showModule,
	compileExpr, HValue,
75
	lookupName,
76
77
78
#endif

	-- * Abstract syntax elements
79
80

	-- ** Modules
81
	Module, mkModule, pprModule,
82

83
	-- ** Names
84
85
86
	Name, 
	nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
	NamedThing(..),
Simon Marlow's avatar
Simon Marlow committed
87
	RdrName(Qual,Unqual),
88
89
	
	-- ** Identifiers
90
	Id, idType,
91
	isImplicitId, isDeadBinder,
92
	isExportedId, isLocalId, isGlobalId,
93
	isRecordSelector,
94
	isPrimOpId, isFCallId, isClassOpId_maybe,
95
96
	isDataConWorkId, idDataCon,
	isBottomingId, isDictonaryId,
97
	recordSelectorFieldLabel,
98
99
100

	-- ** Type constructors
	TyCon, 
101
	tyConTyVars, tyConDataCons, tyConArity,
102
	isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
103
	synTyConDefn, synTyConRhs,
104

105
106
107
108
	-- ** Type variables
	TyVar,
	alphaTyVars,

109
110
	-- ** Data constructors
	DataCon,
111
112
113
114
	dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
	dataConIsInfix, isVanillaDataCon,
	dataConStrictMarks,  
	StrictnessMark(..), isMarkedStrict,
115
116
117

	-- ** Classes
	Class, 
118
119
	classMethods, classSCTheta, classTvsFds,
	pprFundeps,
120

121
	-- ** Instances
122
	Instance, 
123
	instanceDFunId, pprInstance, pprInstanceHdr,
124

125
	-- ** Types and Kinds
126
	Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
127
	Kind,
128
129
	PredType,
	ThetaType, pprThetaArrow,
130
131

	-- ** Entities
132
133
	TyThing(..), 

134
135
136
	-- ** Syntax
	module HsSyn, -- ToDo: remove extraneous bits

137
138
139
140
141
142
143
144
145
	-- ** Fixities
	FixityDirection(..), 
	defaultFixity, maxPrecedence, 
	negateFixity,
	compareFixity,

	-- ** Source locations
	SrcLoc, pprDefnLoc,

146
147
148
149
	-- * Exceptions
	GhcException(..), showGhcException,

	-- * Miscellaneous
150
151
	sessionHscEnv,
	cyclicModuleErr,
152
153
  ) where

154
155
156
{-
 ToDo:

157
  * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
158
159
160
161
162
163
164
165
166
167
  * we need to expose DynFlags, so should parseDynamicFlags really be
    part of this interface?
  * what StaticFlags should we expose, if any?
-}

#include "HsVersions.h"

#ifdef GHCI
import qualified Linker
import Linker		( HValue, extendLinkEnv )
168
169
import TcRnDriver	( tcRnLookupRdrName, tcRnGetInfo,
			  tcRnLookupName, getModuleExports )
170
171
import RdrName		( plusGlobalRdrEnv, Provenance(..), 
			  ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
172
			  emptyGlobalRdrEnv, mkGlobalRdrEnv )
173
import HscMain		( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
174
175
176
177
178
import Type		( tidyType )
import VarEnv		( emptyTidyEnv )
import GHC.Exts		( unsafeCoerce# )
#endif

179
import Packages		( initPackages )
180
import NameSet		( NameSet, nameSetToList, elemNameSet )
Simon Marlow's avatar
Simon Marlow committed
181
import RdrName		( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..), 
182
			  globalRdrEnvElts )
183
import HsSyn
184
185
186
import Type		( Kind, Type, dropForAlls, PredType, ThetaType,
			  pprThetaArrow, pprParendType, splitForAllTys,
			  funResultTy )
187
import Id		( Id, idType, isImplicitId, isDeadBinder,
188
                          isExportedId, isLocalId, isGlobalId,
189
190
                          isRecordSelector, recordSelectorFieldLabel,
                          isPrimOpId, isFCallId, isClassOpId_maybe,
191
192
                          isDataConWorkId, idDataCon,
                          isBottomingId )
193
194
import Var		( TyVar )
import TysPrim		( alphaTyVars )
195
import TyCon		( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
196
			  isPrimTyCon, isFunTyCon, tyConArity,
197
			  tyConTyVars, tyConDataCons, synTyConDefn, synTyConRhs )
198
199
200
201
202
203
import Class		( Class, classSCTheta, classTvsFds, classMethods )
import FunDeps		( pprFundeps )
import DataCon		( DataCon, dataConWrapId, dataConSig, dataConTyCon,
			  dataConFieldLabels, dataConStrictMarks, 
			  dataConIsInfix, isVanillaDataCon )
import Name		( Name, nameModule, NamedThing(..), nameParent_maybe,
Simon Marlow's avatar
Simon Marlow committed
204
			  nameSrcLoc, nameOccName )
205
import OccName		( parenSymOcc )
206
import NameEnv		( nameEnvElts )
207
import InstEnv		( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
208
import SrcLoc
209
210
import DriverPipeline
import DriverPhases	( Phase(..), isHaskellSrcFilename, startPhase )
211
import HeaderInfo	( getImports, getOptions )
212
213
import Packages		( isHomePackage )
import Finder
214
import HscMain		( newHscEnv, hscFileCheck, HscChecked(..) )
215
216
217
218
219
220
import HscTypes
import DynFlags
import SysTools		( initSysTools, cleanTempFiles )
import Module
import FiniteMap
import Panic
221
import Digraph
222
import Bag		( unitBag )
223
import ErrUtils		( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
224
			  mkPlainErrMsg, printBagOfErrors, printErrorsAndWarnings )
225
import qualified ErrUtils
226
import Util
227
import StringBuffer	( StringBuffer, hGetStringBuffer )
228
229
import Outputable
import SysTools		( cleanTempFilesExcept )
230
import BasicTypes
231
import TcType           ( tcSplitSigmaTy, isDictTy )
232
import Maybes		( expectJust, mapCatMaybes )
233
234
235

import Control.Concurrent
import System.Directory ( getModificationTime, doesFileExist )
236
import Data.Maybe	( isJust, isNothing )
237
238
239
240
241
242
243
244
import Data.List	( partition, nub )
import qualified Data.List as List
import Control.Monad	( unless, when )
import System.Exit	( exitWith, ExitCode(..) )
import System.Time	( ClockTime )
import Control.Exception as Exception hiding (handle)
import Data.IORef
import System.IO
245
import System.IO.Error	( isDoesNotExistError )
246
import Prelude hiding (init)
247

248
249
250
251
252
253
#if __GLASGOW_HASKELL__ < 600
import System.IO as System.IO.Error ( try )
#else
import System.IO.Error	( try )
#endif

254
-- -----------------------------------------------------------------------------
255
-- Exception handlers
256
257
258
259
260

-- | Install some default exception handlers and run the inner computation.
-- Unless you want to handle exceptions yourself, you should wrap this around
-- the top level of your program.  The default handlers output the error
-- message(s) to stderr and exit cleanly.
261
262
defaultErrorHandler :: DynFlags -> IO a -> IO a
defaultErrorHandler dflags inner = 
263
264
265
266
267
  -- top-level exception handler: any unrecognised exception is a compiler bug.
  handle (\exception -> do
  	   hFlush stdout
	   case exception of
		-- an IO exception probably isn't our fault, so don't panic
268
269
		IOException _ ->
		  fatalErrorMsg dflags (text (show exception))
270
		AsyncException StackOverflow ->
271
272
273
		  fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
		_other ->
		  fatalErrorMsg dflags (text (show (Panic (show exception))))
274
275
276
	   exitWith (ExitFailure 1)
         ) $

277
278
  -- program errors: messages with locations attached.  Sometimes it is
  -- convenient to just throw these as exceptions.
279
  handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
280
281
282
			exitWith (ExitFailure 1)) $

  -- error messages propagated as exceptions
283
284
285
286
287
  handleDyn (\dyn -> do
  		hFlush stdout
  		case dyn of
		     PhaseFailed _ code -> exitWith code
		     Interrupted -> exitWith (ExitFailure 1)
288
		     _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
289
290
291
292
293
294
295
296
			     exitWith (ExitFailure 1)
	    ) $
  inner

-- | Install a default cleanup handler to remove temporary files
-- deposited by a GHC run.  This is seperate from
-- 'defaultErrorHandler', because you might want to override the error
-- handling, but still get the ordinary cleanup behaviour.
297
298
defaultCleanupHandler :: DynFlags -> IO a -> IO a
defaultCleanupHandler dflags inner = 
299
   -- make sure we clean up after ourselves
300
301
   later (unless (dopt Opt_KeepTmpFiles dflags) $ 
	    cleanTempFiles dflags) 
302
303
304
305
306
307
308
	-- exceptions will be blocked while we clean the temporary files,
	-- so there shouldn't be any difficulty if we receive further
	-- signals.
   inner


-- | Initialises GHC.  This must be done /once/ only.  Takes the
309
-- TopDir path without the '-B' prefix.
310

311
312
init :: Maybe String -> IO ()
init mbMinusB = do
313
   -- catch ^C
314
315
   main_thread <- myThreadId
   putMVar interruptTargetThread [main_thread]
316
317
   installSignalHandlers

318
   dflags0 <- initSysTools mbMinusB defaultDynFlags
319
   writeIORef v_initDynFlags dflags0
320

321
322
323
324
325
326
327
328
329
330
331
332
333
334
-- | Initialises GHC. This must be done /once/ only. Takes the
-- command-line arguments.  All command-line arguments which aren't
-- understood by GHC will be returned.

initFromArgs :: [String] -> IO [String]
initFromArgs args
    = do init mbMinusB
         return argv1
    where -- Grab the -B option if there is one
          (minusB_args, argv1) = partition (prefixMatch "-B") args
          mbMinusB | null minusB_args
                       = Nothing
                   | otherwise
                       = Just (drop 2 (last minusB_args))
335
336
337
338

GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
	-- stores the DynFlags between the call to init and subsequent
	-- calls to newSession.
339
340
341

-- | Starts a new session.  A session consists of a set of loaded
-- modules, a set of options (DynFlags), and an interactive context.
342
-- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
343
344
345
-- code".
newSession :: GhcMode -> IO Session
newSession mode = do
346
347
348
  dflags0 <- readIORef v_initDynFlags
  dflags <- initDynFlags dflags0
  env <- newHscEnv dflags{ ghcMode=mode }
349
  ref <- newIORef env
350
351
352
353
354
355
356
357
358
359
360
361
  return (Session ref)

-- tmp: this breaks the abstraction, but required because DriverMkDepend
-- needs to call the Finder.  ToDo: untangle this.
sessionHscEnv :: Session -> IO HscEnv
sessionHscEnv (Session ref) = readIORef ref

withSession :: Session -> (HscEnv -> IO a) -> IO a
withSession (Session ref) f = do h <- readIORef ref; f h

modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
362
363
364
365
366
367

-- -----------------------------------------------------------------------------
-- Flags & settings

-- | Grabs the DynFlags from the Session
getSessionDynFlags :: Session -> IO DynFlags
368
getSessionDynFlags s = withSession s (return . hsc_dflags)
369
370

-- | Updates the DynFlags in a Session
371
372
setSessionDynFlags :: Session -> DynFlags -> IO ()
setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
373

374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
-- | If there is no -o option, guess the name of target executable
-- by using top-level source file name as a base.
guessOutputFile :: Session -> IO ()
guessOutputFile s = modifySession s $ \env ->
    let dflags = hsc_dflags env
        mod_graph = hsc_mod_graph env
        mainModuleSrcPath, guessedName :: Maybe String
        mainModuleSrcPath = do
            let isMain = (== mainModIs dflags) . ms_mod
            [ms] <- return (filter isMain mod_graph)
            ml_hs_file (ms_location ms)
        guessedName = fmap basenameOf mainModuleSrcPath
    in
    case outputFile dflags of
        Just _ -> env
        Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }

391
-- -----------------------------------------------------------------------------
392
-- Targets
393
394
395
396
397
398

-- ToDo: think about relative vs. absolute file paths. And what
-- happens when the current directory changes.

-- | Sets the targets for this session.  Each target may be a module name
-- or a filename.  The targets correspond to the set of root modules for
399
-- the program\/library.  Unloading the current program is achieved by
400
-- setting the current set of targets to be empty, followed by load.
401
setTargets :: Session -> [Target] -> IO ()
402
setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
403
404

-- | returns the current set of targets
405
406
getTargets :: Session -> IO [Target]
getTargets s = withSession s (return . hsc_targets)
407

408
-- | Add another target
409
410
411
addTarget :: Session -> Target -> IO ()
addTarget s target
  = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
412

413
414
415
416
417
418
-- | Remove a target
removeTarget :: Session -> TargetId -> IO ()
removeTarget s target_id
  = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
  where
   filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
419

420
421
422
423
424
425
426
427
428
-- Attempts to guess what Target a string refers to.  This function implements
-- the --make/GHCi command-line syntax for filenames: 
--
-- 	- if the string looks like a Haskell source filename, then interpret
--	  it as such
--	- if adding a .hs or .lhs suffix yields the name of an existing file,
--	  then use that
-- 	- otherwise interpret the string as a module name
--
429
430
431
432
guessTarget :: String -> Maybe Phase -> IO Target
guessTarget file (Just phase)
   = return (Target (TargetFile file (Just phase)) Nothing)
guessTarget file Nothing
433
   | isHaskellSrcFilename file
434
   = return (Target (TargetFile file Nothing) Nothing)
435
436
   | otherwise
   = do exists <- doesFileExist hs_file
437
438
439
	if exists
	   then return (Target (TargetFile hs_file Nothing) Nothing)
	   else do
440
	exists <- doesFileExist lhs_file
441
442
443
	if exists
	   then return (Target (TargetFile lhs_file Nothing) Nothing)
	   else do
444
445
	return (Target (TargetModule (mkModule file)) Nothing)
     where 
446
447
	 hs_file  = file `joinFileExt` "hs"
	 lhs_file = file `joinFileExt` "lhs"
448
449
450

-- -----------------------------------------------------------------------------
-- Loading the program
451

452
453
-- Perform a dependency analysis starting from the current targets
-- and update the session with the new module graph.
454
depanal :: Session -> [Module] -> Bool -> IO (Maybe ModuleGraph)
455
depanal (Session ref) excluded_mods allow_dup_roots = do
456
457
458
459
460
461
462
463
  hsc_env <- readIORef ref
  let
	 dflags  = hsc_dflags hsc_env
	 gmode   = ghcMode (hsc_dflags hsc_env)
	 targets = hsc_targets hsc_env
	 old_graph = hsc_mod_graph hsc_env
	
  showPass dflags "Chasing dependencies"
464
  when (gmode == BatchCompile) $
465
	debugTraceMsg dflags 1 (hcat [
466
		     text "Chasing modules from: ",
467
	     		hcat (punctuate comma (map pprTarget targets))])
468

469
  r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
470
  case r of
471
    Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
472
473
    _ -> return ()
  return r
474

475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
{-
-- | The result of load.
data LoadResult
  = LoadOk	Errors	-- ^ all specified targets were loaded successfully.
  | LoadFailed  Errors	-- ^ not all modules were loaded.

type Errors = [String]

data ErrMsg = ErrMsg { 
	errMsgSeverity  :: Severity,  -- warning, error, etc.
	errMsgSpans     :: [SrcSpan],
	errMsgShortDoc  :: Doc,
	errMsgExtraInfo :: Doc
	}
-}

data LoadHowMuch
   = LoadAllTargets
   | LoadUpTo Module
494
   | LoadDependenciesOf Module
495
496
497
498

-- | Try to load the program.  If a Module is supplied, then just
-- attempt to load up to this target.  If no Module is supplied,
-- then try to load all targets.
499
load :: Session -> LoadHowMuch -> IO SuccessFlag
500
load s@(Session ref) how_much
501
   = do 
502
503
504
505
	-- Dependency analysis first.  Note that this fixes the module graph:
	-- even if we don't get a fully successful upsweep, the full module
	-- graph is still retained in the Session.  We can tell which modules
	-- were successfully loaded by inspecting the Session's HPT.
506
	mb_graph <- depanal s [] False
507
508
509
	case mb_graph of	   
	   Just mod_graph -> load2 s how_much mod_graph 
	   Nothing        -> return Failed
510

511
load2 s@(Session ref) how_much mod_graph = do
512
        guessOutputFile s
513
514
515
516
	hsc_env <- readIORef ref

        let hpt1      = hsc_HPT hsc_env
        let dflags    = hsc_dflags hsc_env
517
        let ghci_mode = ghcMode dflags -- this never changes
518
519
520
521
522
523

	-- The "bad" boot modules are the ones for which we have
	-- B.hs-boot in the module graph, but no B.hs
	-- The downsweep should have ensured this does not happen
	-- (see msDeps)
        let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
524
#ifdef DEBUG
525
526
	    bad_boot_mods = [s 	      | s <- mod_graph, isBootSummary s,
					not (ms_mod s `elem` all_home_mods)]
527
#endif
528
529
530
531
532
533
534
535
	ASSERT( null bad_boot_mods ) return ()

        -- mg2_with_srcimps drops the hi-boot nodes, returning a 
	-- graph with cycles.  Among other things, it is used for
        -- backing out partially complete cycles following a failed
        -- upsweep, and for removing from hpt all the modules
        -- not in strict downwards closure, during calls to compile.
        let mg2_with_srcimps :: [SCC ModSummary]
536
	    mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
537

538
539
540
541
542
543
544
545
546
547
548
549
550
	    -- check the stability property for each module.
	    stable_mods@(stable_obj,stable_bco)
		| BatchCompile <- ghci_mode = ([],[])
	        | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods

	    -- prune bits of the HPT which are definitely redundant now,
	    -- to save space.
	    pruned_hpt = pruneHomePackageTable hpt1 
				(flattenSCCs mg2_with_srcimps)
				stable_mods

	evaluate pruned_hpt

551
552
	debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
				text "Stable BCO:" <+> ppr stable_bco)
553
554

	-- Unload any modules which are going to be re-linked this time around.
555
556
557
558
	let stable_linkables = [ linkable
			       | m <- stable_obj++stable_bco,
				 Just hmi <- [lookupModuleEnv pruned_hpt m],
				 Just linkable <- [hm_linkable hmi] ]
559
560
561
562
563
564
565
566
567
568
569
570
	unload hsc_env stable_linkables

        -- We could at this point detect cycles which aren't broken by
        -- a source-import, and complain immediately, but it seems better
        -- to let upsweep_mods do this, so at least some useful work gets
        -- done before the upsweep is abandoned.
        --hPutStrLn stderr "after tsort:\n"
        --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))

        -- Now do the upsweep, calling compile for each module in
        -- turn.  Final result is version 3 of everything.

571
572
573
574
575
576
        -- Topologically sort the module graph, this time including hi-boot
	-- nodes, and possibly just including the portion of the graph
	-- reachable from the module specified in the 2nd argument to load.
	-- This graph should be cycle-free.
	-- If we're restricting the upsweep to a portion of the graph, we
	-- also want to retain everything that is still stable.
577
        let full_mg :: [SCC ModSummary]
578
	    full_mg    = topSortModuleGraph False mod_graph Nothing
579
580
581

	    maybe_top_mod = case how_much of
				LoadUpTo m           -> Just m
582
			  	LoadDependenciesOf m -> Just m
583
584
			  	_		     -> Nothing

585
586
587
588
589
590
591
592
593
594
595
596
597
598
	    partial_mg0 :: [SCC ModSummary]
	    partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod

	    -- LoadDependenciesOf m: we want the upsweep to stop just
	    -- short of the specified module (unless the specified module
	    -- is stable).
	    partial_mg
		| LoadDependenciesOf mod <- how_much
		= ASSERT( case last partial_mg0 of 
			    AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
		  List.init partial_mg0
		| otherwise
		= partial_mg0
  
599
600
601
602
603
604
605
606
607
	    stable_mg = 
		[ AcyclicSCC ms
	        | AcyclicSCC ms <- full_mg,
		  ms_mod ms `elem` stable_obj++stable_bco,
		  ms_mod ms `notElem` [ ms_mod ms' | 
					AcyclicSCC ms' <- partial_mg ] ]

	    mg = stable_mg ++ partial_mg

608
609
	-- clean up between compilations
	let cleanup = cleanTempFilesExcept dflags
610
			  (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
611

612
613
        (upsweep_ok, hsc_env1, modsUpswept)
           <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
614
			   pruned_hpt stable_mods cleanup mg
615
616
617
618
619

	-- Make modsDone be the summaries for each home module now
	-- available; this should equal the domain of hpt3.
        -- Get in in a roughly top .. bottom order (hence reverse).

620
        let modsDone = reverse modsUpswept
621
622
623
624
625
626
627
628

        -- Try and do linking in some form, depending on whether the
        -- upsweep was completely or only partially successful.

        if succeeded upsweep_ok

         then 
           -- Easy; just relink it all.
629
           do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
630
631
632
633
634
635
636
637
638
639
640
641
642

	      -- Clean up after ourselves
	      cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)

	      -- Issue a warning for the confusing case where the user
	      -- said '-o foo' but we're not going to do any linking.
	      -- We attempt linking if either (a) one of the modules is
	      -- called Main, or (b) the user said -no-hs-main, indicating
	      -- that main() is going to come from somewhere else.
	      --
	      let ofile = outputFile dflags
	      let no_hs_main = dopt Opt_NoHsMain dflags
	      let 
643
644
	 	main_mod = mainModIs dflags
		a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
645
646
		do_linking = a_root_is_Main || no_hs_main

647
	      when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
648
649
	        debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
				              "but no output will be generated\n" ++
650
				              "because there is no " ++ moduleString main_mod ++ " module."))
651
652

	      -- link everything together
653
              linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
654

655
	      loadFinish Succeeded linkresult ref hsc_env1
656
657
658
659
660

         else 
           -- Tricky.  We need to back out the effects of compiling any
           -- half-done cycles, both so as to clean up the top level envs
           -- and to avoid telling the interactive linker to link them.
661
           do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
662
663
664
665
666
667
668
669
670
671
672

              let modsDone_names
                     = map ms_mod modsDone
              let mods_to_zap_names 
                     = findPartiallyCompletedCycles modsDone_names 
			  mg2_with_srcimps
              let mods_to_keep
                     = filter ((`notElem` mods_to_zap_names).ms_mod) 
			  modsDone

              let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep) 
673
					      (hsc_HPT hsc_env1)
674
675
676
677

	      -- Clean up after ourselves
	      cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)

678
679
680
681
	      -- there should be no Nothings where linkables should be, now
	      ASSERT(all (isJust.hm_linkable) 
			(moduleEnvElts (hsc_HPT hsc_env))) do
	
682
683
684
	      -- Link everything together
              linkresult <- link ghci_mode dflags False hpt4

685
	      let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
	      loadFinish Failed linkresult ref hsc_env4

-- Finish up after a load.

-- If the link failed, unload everything and return.
loadFinish all_ok Failed ref hsc_env
  = do unload hsc_env []
       writeIORef ref $! discardProg hsc_env
       return Failed

-- Empty the interactive context and set the module context to the topmost
-- newly loaded module, or the Prelude if none were loaded.
loadFinish all_ok Succeeded ref hsc_env
  = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
       return all_ok

702

703
704
705
706
707
708
709
710
711
712
-- Forget the current program, but retain the persistent info in HscEnv
discardProg :: HscEnv -> HscEnv
discardProg hsc_env
  = hsc_env { hsc_mod_graph = emptyMG, 
	      hsc_IC = emptyInteractiveContext,
	      hsc_HPT = emptyHomePackageTable }

-- used to fish out the preprocess output files for the purposes of
-- cleaning up.  The preprocessed file *might* be the same as the
-- source file, but that doesn't do any harm.
713
ppFilesFromSummaries summaries = map ms_hspp_file summaries
714

715
716
717
718
719
-- -----------------------------------------------------------------------------
-- Check module

data CheckedModule = 
  CheckedModule { parsedSource      :: ParsedSource,
720
		  renamedSource     :: Maybe RenamedSource,
721
722
723
		  typecheckedSource :: Maybe TypecheckedSource,
		  checkedModuleInfo :: Maybe ModuleInfo
	        }
724
725
726
727
728
	-- ToDo: improvements that could be made here:
	--  if the module succeeded renaming but not typechecking,
	--  we can still get back the GlobalRdrEnv and exports, so
	--  perhaps the ModuleInfo should be split up into separate
	--  fields within CheckedModule.
729

730
type ParsedSource      = Located (HsModule RdrName)
731
type RenamedSource     = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name])
732
733
type TypecheckedSource = LHsBinds Id

734
735
736
737
738
739
740
741
742
743
744
745
746
-- NOTE:
--   - things that aren't in the output of the typechecker right now:
--     - the export list
--     - the imports
--     - type signatures
--     - type/data/newtype declarations
--     - class declarations
--     - instances
--   - extra things in the typechecker's output:
--     - default methods are turned into top-level decls.
--     - dictionary bindings


747
748
749
750
-- | This is the way to get access to parsed and typechecked source code
-- for a module.  'checkModule' loads all the dependencies of the specified
-- module in the Session, and then attempts to typecheck the module.  If
-- successful, it returns the abstract syntax for the module.
751
752
checkModule :: Session -> Module -> IO (Maybe CheckedModule)
checkModule session@(Session ref) mod = do
753
	-- load up the dependencies first
754
   r <- load session (LoadDependenciesOf mod)
755
756
757
758
759
760
761
762
   if (failed r) then return Nothing else do

	-- now parse & typecheck the module
   hsc_env <- readIORef ref   
   let mg  = hsc_mod_graph hsc_env
   case [ ms | ms <- mg, ms_mod ms == mod ] of
	[] -> return Nothing
	(ms:_) -> do 
763
	   mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
764
765
766
	   case mbChecked of
             Nothing -> return Nothing
             Just (HscChecked parsed renamed Nothing) ->
767
768
769
770
771
		   return (Just (CheckedModule {
					parsedSource = parsed,
					renamedSource = renamed,
					typecheckedSource = Nothing,
					checkedModuleInfo = Nothing }))
772
773
             Just (HscChecked parsed renamed
			   (Just (tc_binds, rdr_env, details))) -> do
774
		   let minf = ModuleInfo {
775
776
777
778
				minf_type_env  = md_types details,
				minf_exports   = md_exports details,
				minf_rdr_env   = Just rdr_env,
				minf_instances = md_insts details
779
780
781
			      }
		   return (Just (CheckedModule {
					parsedSource = parsed,
782
					renamedSource = renamed,
783
784
785
786
					typecheckedSource = Just tc_binds,
					checkedModuleInfo = Just minf }))

-- ---------------------------------------------------------------------------
787
788
789
790
791
-- Unloading

unload :: HscEnv -> [Linkable] -> IO ()
unload hsc_env stable_linkables	-- Unload everthing *except* 'stable_linkables'
  = case ghcMode (hsc_dflags hsc_env) of
792
793
	BatchCompile  -> return ()
	JustTypecheck -> return ()
794
795
796
797
798
799
800
#ifdef GHCI
	Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
#else
	Interactive -> panic "unload: no interpreter"
#endif
	other -> panic "unload: strange mode"

801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
-- -----------------------------------------------------------------------------
-- checkStability

{-
  Stability tells us which modules definitely do not need to be recompiled.
  There are two main reasons for having stability:
  
   - avoid doing a complete upsweep of the module graph in GHCi when
     modules near the bottom of the tree have not changed.

   - to tell GHCi when it can load object code: we can only load object code
     for a module when we also load object code fo  all of the imports of the
     module.  So we need to know that we will definitely not be recompiling
     any of these modules, and we can use the object code.

  NB. stability is of no importance to BatchCompile at all, only Interactive.
  (ToDo: what about JustTypecheck?)

  The stability check is as follows.  Both stableObject and
  stableBCO are used during the upsweep phase later.

  -------------------
  stable m = stableObject m || stableBCO m

  stableObject m = 
	all stableObject (imports m)
	&& old linkable does not exist, or is == on-disk .o
	&& date(on-disk .o) > date(.hs)

  stableBCO m =
	all stable (imports m)
	&& date(BCO) > date(.hs)
  -------------------    

  These properties embody the following ideas:

    - if a module is stable:
	- if it has been compiled in a previous pass (present in HPT)
	  then it does not need to be compiled or re-linked.
        - if it has not been compiled in a previous pass,
	  then we only need to read its .hi file from disk and
	  link it to produce a ModDetails.

    - if a modules is not stable, we will definitely be at least
      re-linking, and possibly re-compiling it during the upsweep.
      All non-stable modules can (and should) therefore be unlinked
      before the upsweep.

    - Note that objects are only considered stable if they only depend
      on other objects.  We can't link object code against byte code.
-}

checkStability
	:: HomePackageTable		-- HPT from last compilation
	-> [SCC ModSummary]		-- current module graph (cyclic)
	-> [Module]			-- all home modules
	-> ([Module],			-- stableObject
	    [Module])			-- stableBCO

checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
  where
   checkSCC (stable_obj, stable_bco) scc0
     | stableObjects = (scc_mods ++ stable_obj, stable_bco)
     | stableBCOs    = (stable_obj, scc_mods ++ stable_bco)
     | otherwise     = (stable_obj, stable_bco)
     where
	scc = flattenSCC scc0
	scc_mods = map ms_mod scc
	home_module m   = m `elem` all_home_mods && m `notElem` scc_mods

        scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
	    -- all imports outside the current SCC, but in the home pkg
	
	stable_obj_imps = map (`elem` stable_obj) scc_allimps
	stable_bco_imps = map (`elem` stable_bco) scc_allimps

	stableObjects = 
	   and stable_obj_imps
	   && all object_ok scc

	stableBCOs = 
	   and (zipWith (||) stable_obj_imps stable_bco_imps)
	   && all bco_ok scc

	object_ok ms
	  | Just t <- ms_obj_date ms  =  t >= ms_hs_date ms 
					 && same_as_prev t
	  | otherwise = False
	  where
	     same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
				Just hmi  | Just l <- hm_linkable hmi
				 -> isObjectLinkable l && t == linkableTime l
893
				_other  -> True
894
		-- why '>=' rather than '>' above?  If the filesystem stores
895
896
897
898
899
900
		-- times to the nearset second, we may occasionally find that
		-- the object & source have the same modification time, 
		-- especially if the source was automatically generated
		-- and compiled.  Using >= is slightly unsafe, but it matches
		-- make's behaviour.

901
902
903
904
905
	bco_ok ms
	  = case lookupModuleEnv hpt (ms_mod ms) of
		Just hmi  | Just l <- hm_linkable hmi ->
			not (isObjectLinkable l) && 
			linkableTime l >= ms_hs_date ms
906
		_other  -> False
907

908
ms_allimps :: ModSummary -> [Module]
909
ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
910

911
912
-- -----------------------------------------------------------------------------
-- Prune the HomePackageTable
913

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
-- Before doing an upsweep, we can throw away:
--
--   - For non-stable modules:
--	- all ModDetails, all linked code
--   - all unlinked code that is out of date with respect to
--     the source file
--
-- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
-- space at the end of the upsweep, because the topmost ModDetails of the
-- old HPT holds on to the entire type environment from the previous
-- compilation.

pruneHomePackageTable
   :: HomePackageTable
   -> [ModSummary]
   -> ([Module],[Module])
   -> HomePackageTable

pruneHomePackageTable hpt summ (stable_obj, stable_bco)
  = mapModuleEnv prune hpt
  where prune hmi
	  | is_stable modl = hmi'
	  | otherwise      = hmi'{ hm_details = emptyModDetails }
	  where
	   modl = mi_module (hm_iface hmi)
	   hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
		= hmi{ hm_linkable = Nothing }
		| otherwise
		= hmi
		where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
944

945
        ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
946

947
948
949
	is_stable m = m `elem` stable_obj || m `elem` stable_bco

-- -----------------------------------------------------------------------------
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970

-- Return (names of) all those in modsDone who are part of a cycle
-- as defined by theGraph.
findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
findPartiallyCompletedCycles modsDone theGraph
   = chew theGraph
     where
        chew [] = []
        chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
        chew ((CyclicSCC vs):rest)
           = let names_in_this_cycle = nub (map ms_mod vs)
                 mods_in_this_cycle  
                    = nub ([done | done <- modsDone, 
                                   done `elem` names_in_this_cycle])
                 chewed_rest = chew rest
             in 
             if   notNull mods_in_this_cycle
                  && length mods_in_this_cycle < length names_in_this_cycle
             then mods_in_this_cycle ++ chewed_rest
             else chewed_rest

971
972
973
974
975
-- -----------------------------------------------------------------------------
-- The upsweep

-- This is where we compile each module in the module graph, in a pass
-- from the bottom to the top of the graph.
976
977

-- There better had not be any cyclic groups here -- we check for them.
978
979
980
981
982
983
984
985
986
987
988

upsweep
    :: HscEnv			-- Includes initially-empty HPT
    -> HomePackageTable		-- HPT from last time round (pruned)
    -> ([Module],[Module])	-- stable modules (see checkStability)
    -> IO ()			-- How to clean up unwanted tmp files
    -> [SCC ModSummary]		-- Mods to do (the worklist)
    -> IO (SuccessFlag,
           HscEnv,		-- With an updated HPT
           [ModSummary])	-- Mods which succeeded

989
990
upsweep hsc_env old_hpt stable_mods cleanup mods
   = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
991

992
upsweep' hsc_env old_hpt stable_mods cleanup
993
     [] _ _
994
995
   = return (Succeeded, hsc_env, [])

996
upsweep' hsc_env old_hpt stable_mods cleanup
997
     (CyclicSCC ms:_) _ _
998
   = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
999
1000
        return (Failed, hsc_env, [])

1001
upsweep' hsc_env old_hpt stable_mods cleanup
1002
     (AcyclicSCC mod:mods) mod_index nmods
1003
1004
1005
1006
   = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
	--	     show (map (moduleUserString.moduleName.mi_module.hm_iface) 
	--		       (moduleEnvElts (hsc_HPT hsc_env)))

1007
        mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
1008
                       mod_index nmods
1009
1010
1011
1012
1013
1014
1015
1016
1017

	cleanup		-- Remove unwanted tmp files between compilations

        case mb_mod_info of
	    Nothing -> return (Failed, hsc_env, [])
	    Just mod_info -> do 
		{ let this_mod = ms_mod mod

			-- Add new info to hsc_env
1018
1019
		      hpt1     = extendModuleEnv (hsc_HPT hsc_env) 
					this_mod mod_info
1020
		      hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1021
1022
1023
1024

			-- Space-saving: delete the old HPT entry
			-- for mod BUT if mod is a hs-boot
			-- node, don't delete it.  For the
1025
1026
1027
			-- interface, the HPT entry is probaby for the
			-- main Haskell source file.  Deleting it
			-- would force .. (what?? --SDM)
1028
1029
		      old_hpt1 | isBootSummary mod = old_hpt
			       | otherwise = delModuleEnv old_hpt this_mod
1030

1031
		; (restOK, hsc_env2, modOKs) 
1032
			<- upsweep' hsc_env1 old_hpt1 stable_mods cleanup 
1033
				mods (mod_index+1) nmods
1034
1035
		; return (restOK, hsc_env2, mod:modOKs)
		}
1036
1037
1038
1039
1040


-- Compile a single module.  Always produce a Linkable for it if 
-- successful.  If no compilation happened, return the old Linkable.
upsweep_mod :: HscEnv
1041
1042
            -> HomePackageTable
	    -> ([Module],[Module])
1043
            -> ModSummary
1044
1045
            -> Int  -- index of module
            -> Int  -- total number of modules
1046
1047
            -> IO (Maybe HomeModInfo)	-- Nothing => Failed

1048
upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1049
   = do 
1050
1051
1052
1053
1054
1055
1056
        let 
	    this_mod    = ms_mod summary
	    mb_obj_date = ms_obj_date summary
	    obj_fn	= ml_obj_file (ms_location summary)
	    hs_date     = ms_hs_date summary

	    compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1057
	    compile_it  = upsweep_compile hsc_env old_hpt this_mod 
1058
				summary mod_index nmods
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

	case ghcMode (hsc_dflags hsc_env) of
	    BatchCompile ->
		case () of
		   -- Batch-compilating is easy: just check whether we have
		   -- an up-to-date object file.  If we do, then the compiler
		   -- needs to do a recompilation check.
		   _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
		           linkable <- 
				findObjectLinkable this_mod obj_fn obj_date
			   compile_it (Just linkable)

		     | otherwise ->
		           compile_it Nothing

	    interactive ->
		case () of
		    _ | is_stable_obj, isJust old_hmi ->
			   return old_hmi
			-- object is stable, and we have an entry in the
			-- old HPT: nothing to do

		      | is_stable_obj, isNothing old_hmi -> do
		           linkable <-
				findObjectLinkable this_mod obj_fn 
					(expectJust "upseep1" mb_obj_date)
			   compile_it (Just linkable)
			-- object is stable, but we need to load the interface
			-- off disk to make a HMI.

		      | is_stable_bco -> 
			   ASSERT(isJust old_hmi) -- must be in the old_hpt
			   return old_hmi
			-- BCO is stable: nothing to do

		      | Just hmi <- old_hmi,
			Just l <- hm_linkable hmi, not (isObjectLinkable l),
			linkableTime l >= ms_hs_date summary ->
			   compile_it (Just l)
			-- we have an old BCO that is up to date with respect
			-- to the source: do a recompilation check as normal.

		      | otherwise ->
			  compile_it Nothing
			-- no existing code at all: we must recompile.
		   where
		    is_stable_obj = this_mod `elem` stable_obj
		    is_stable_bco = this_mod `elem` stable_bco

		    old_hmi = lookupModuleEnv old_hpt this_mod

-- Run hsc to compile a module
1111
upsweep_compile hsc_env old_hpt this_mod summary
1112
1113
                mod_index nmods
                mb_old_linkable = do
1114
  let
1115
1116
	-- The old interface is ok if it's in the old HPT 
	--	a) we're compiling a source file, and the old HPT
1117
	--	   entry is for a source file
1118
1119
1120
1121
1122
1123
	--	b) we're compiling a hs-boot file
	-- Case (b) allows an hs-boot file to get the interface of its
	-- real source file on the second iteration of the compilation
	-- manager, but that does no harm.  Otherwise the hs-boot file
	-- will always be recompiled

1124
        mb_old_iface 
1125
1126
1127
1128
1129
1130
1131
1132
		= case lookupModuleEnv old_hpt this_mod of
		     Nothing	 			  -> Nothing
		     Just hm_info | isBootSummary summary -> Just iface
				  | not (mi_boot iface)   -> Just iface
				  | otherwise		  -> Nothing
				   where 
				     iface = hm_iface hm_info

1133
  compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1134
                        mod_index nmods
1135

1136
1137
1138
  case compresult of
        -- Compilation failed.  Compile may still have updated the PCS, tho.
        CompErrs -> return Nothing
1139

1140
1141
1142
1143
1144
	-- Compilation "succeeded", and may or may not have returned a new
	-- linkable (depending on whether compilation was actually performed
	-- or not).
	CompOK new_details new_iface new_linkable
              -> do let new_info = HomeModInfo { hm_iface = new_iface,
1145
1146
1147
1148
1149
1150
1151
1152
						 hm_details = new_details,
						 hm_linkable = new_linkable }
                    return (Just new_info)


-- Filter modules in the HPT
retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
retainInTopLevelEnvs keep_these hpt
1153
   = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
		 | mod <- keep_these
		 , let mb_mod_info = lookupModuleEnv hpt mod
		 , isJust mb_mod_info ]

-- ---------------------------------------------------------------------------
-- Topological sort of the module graph

topSortModuleGraph
	  :: Bool 		-- Drop hi-boot nodes? (see below)
	  -> [ModSummary]
1164
	  -> Maybe Module
1165
1166
	  -> [SCC ModSummary]
-- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1167
1168
1169
1170
-- The resulting list of strongly-connected-components is in topologically
-- sorted order, starting with the module(s) at the bottom of the
-- dependency graph (ie compile them first) and ending with the ones at
-- the top.
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
--
-- Drop hi-boot nodes (first boolean arg)? 
--
--   False:	treat the hi-boot summaries as nodes of the graph,
--		so the graph must be acyclic
--
--   True:	eliminate the hi-boot nodes, and instead pretend
--		the a source-import of Foo is an import of Foo
--		The resulting graph has no hi-boot nodes, but can by cyclic

1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
topSortModuleGraph drop_hs_boot_nodes summaries Nothing
  = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
  = stronglyConnComp (map vertex_fn (reachable graph root))
  where 
	-- restrict the graph to just those modules reachable from
	-- the specified module.  We do this by building a graph with
	-- the full set of nodes, and determining the reachable set from
	-- the specified node.
	(nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
	(graph, vertex_fn, key_fn) = graphFromEdges' nodes
	root 
	  | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
	  | otherwise  = throwDyn (ProgramError "module does not exist")

moduleGraphNodes :: Bool -> [ModSummary]
  -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1199
1200
1201
1202
1203
1204
1205
   where
	-- Drop hs-boot nodes by using HsSrcFile as the key
	hs_boot_key | drop_hs_boot_nodes = HsSrcFile
		    | otherwise		 = HsBootFile	

	-- We use integers as the keys for the SCC algorithm
	nodes :: [(ModSummary, Int, [Int])]	
1206
	nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)), 
1207
1208
		     out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
		     out_edge_keys HsSrcFile   (map unLoc (ms_imps s))    )
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
		| s <- summaries
		, not (isBootSummary s && drop_hs_boot_nodes) ]
		-- Drop the hi-boot ones if told to do so

	key_map :: NodeMap Int
	key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
			   `zip` [1..])

	lookup_key :: HscSource -> Module -> Maybe Int
	lookup_key hs_src mod = lookupFM key_map (mod, hs_src)

	out_edge_keys :: HscSource -> [Module] -> [Int]
        out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
		-- If we want keep_hi_boot_nodes, then we do lookup_key with
		-- the IsBootInterface parameter True; else False


type NodeKey   = (Module, HscSource)	  -- The nodes of the graph are 
type NodeMap a = FiniteMap NodeKey a	  -- keyed by (mod, src_file_type) pairs

msKey :: ModSummary -> NodeKey
msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)

mkNodeMap :: [ModSummary] -> NodeMap ModSummary
mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
	
nodeMapElts :: NodeMap a -> [a]
nodeMapElts = eltsFM

-----------------------------------------------------------------------------
-- Downsweep (dependency analysis)

-- Chase downwards from the specified root set, returning summaries
-- for all home modules encountered.  Only follow source-import
-- links.

-- We pass in the previous collection of summaries, which is used as a
-- cache to avoid recalculating a module summary if the source is
-- unchanged.
--
-- The returned list of [ModSummary] nodes has one node for each home-package
-- module, plus one for any hs-boot files.  The imports of these nodes 
-- are all there, including the imports of non-home-package modules.

downsweep :: HscEnv
	  -> [ModSummary]	-- Old summaries
1255
1256
1257
1258
1259
	  -> [Module]		-- Ignore dependencies on these; treat
				-- them as if they were package modules
	  -> Bool		-- True <=> allow multiple targets to have 
				-- 	    the same module name; this is 
				--	    very useful for ghc -M
1260
	  -> IO (Maybe [ModSummary])
1261
1262
1263
1264
		-- The elts of [ModSummary] all have distinct
		-- (Modules, IsBoot) identifiers, unless the Bool is true
		-- in which case there can be repeats
downsweep hsc_env old_summaries excl_mods allow_dup_roots
1265
   = -- catch error messages and return them
1266
     handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1267
       rootSummaries <- mapM getRootSummary roots
1268
1269
1270
       let root_map = mkRootMap rootSummaries
       checkDuplicates root_map
       summs <- loop (concatMap msDeps rootSummaries) root_map
1271
       return (Just summs)
1272
1273
1274
1275
1276
1277
1278
     where
	roots = hsc_targets hsc_env

	old_summary_map :: NodeMap ModSummary
	old_summary_map = mkNodeMap old_summaries

	getRootSummary :: Target -> IO ModSummary
1279
	getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1280
	   = do exists <- doesFileExist file
1281
		if exists