GHC.hs 73.9 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
33
34
35
36
37
        -- * Extending the program scope 
        extendGlobalRdrScope,  -- :: Session -> [GlobalRdrElt] -> IO ()
        setGlobalRdrScope,     -- :: Session -> [GlobalRdrElt] -> IO ()
        extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
        setGlobalTypeScope,    -- :: Session -> [Id] -> IO ()

38
	-- * Loading\/compiling the program
39
	depanal,
40
	load, LoadHowMuch(..), SuccessFlag(..),	-- also does depanal
41
	workingDirectoryChanged,
42
	checkModule, CheckedModule(..),
43
	TypecheckedSource, ParsedSource, RenamedSource,
44
45

	-- * Inspecting the module structure of the program
Simon Marlow's avatar
Simon Marlow committed
46
	ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
47
	getModuleGraph,
48
	isLoaded,
49
50
	topSortModuleGraph,

51
52
53
54
	-- * Inspecting modules
	ModuleInfo,
	getModuleInfo,
	modInfoTyThings,
55
	modInfoTopLevelScope,
56
57
	modInfoPrintUnqualified,
	modInfoExports,
58
	modInfoInstances,
59
60
	modInfoIsExportedName,
	modInfoLookupName,
61
	lookupGlobalName,
62

63
64
65
	-- * Printing
	PrintUnqualified, alwaysQualify,

66
67
	-- * Interactive evaluation
	getBindings, getPrintUnqual,
Simon Marlow's avatar
Simon Marlow committed
68
        findModule,
69
70
#ifdef GHCI
	setContext, getContext,	
71
	getNamesInScope,
Simon Marlow's avatar
Simon Marlow committed
72
	getRdrNamesInScope,
73
	moduleIsInterpreted,
74
	getInfo,
75
76
	exprType,
	typeKind,
77
	parseName,
78
79
80
81
	RunResult(..),
	runStmt,
	showModule,
	compileExpr, HValue,
82
	lookupName,
83
84
85
#endif

	-- * Abstract syntax elements
86

Simon Marlow's avatar
Simon Marlow committed
87
88
89
        -- ** Packages
        PackageId,

90
	-- ** Modules
Simon Marlow's avatar
Simon Marlow committed
91
92
	Module, mkModule, pprModule, moduleName, modulePackageId,
        ModuleName, mkModuleName, moduleNameString,
93

94
	-- ** Names
95
96
97
	Name, 
	nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
	NamedThing(..),
Simon Marlow's avatar
Simon Marlow committed
98
	RdrName(Qual,Unqual),
99
100
	
	-- ** Identifiers
101
	Id, idType,
102
	isImplicitId, isDeadBinder,
103
	isExportedId, isLocalId, isGlobalId,
104
	isRecordSelector,
105
	isPrimOpId, isFCallId, isClassOpId_maybe,
106
107
	isDataConWorkId, idDataCon,
	isBottomingId, isDictonaryId,
108
	recordSelectorFieldLabel,
109
110
111

	-- ** Type constructors
	TyCon, 
112
	tyConTyVars, tyConDataCons, tyConArity,
113
	isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
114
	synTyConDefn, synTyConRhs,
115

116
117
118
119
	-- ** Type variables
	TyVar,
	alphaTyVars,

120
121
	-- ** Data constructors
	DataCon,
122
123
124
125
	dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
	dataConIsInfix, isVanillaDataCon,
	dataConStrictMarks,  
	StrictnessMark(..), isMarkedStrict,
126
127
128

	-- ** Classes
	Class, 
129
130
	classMethods, classSCTheta, classTvsFds,
	pprFundeps,
131

132
	-- ** Instances
133
	Instance, 
134
	instanceDFunId, pprInstance, pprInstanceHdr,
135

136
	-- ** Types and Kinds
137
	Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
138
	Kind,
139
140
	PredType,
	ThetaType, pprThetaArrow,
141
142

	-- ** Entities
143
144
	TyThing(..), 

145
146
147
	-- ** Syntax
	module HsSyn, -- ToDo: remove extraneous bits

148
149
150
151
152
153
154
155
156
	-- ** Fixities
	FixityDirection(..), 
	defaultFixity, maxPrecedence, 
	negateFixity,
	compareFixity,

	-- ** Source locations
	SrcLoc, pprDefnLoc,

157
158
159
160
	-- * Exceptions
	GhcException(..), showGhcException,

	-- * Miscellaneous
161
162
	sessionHscEnv,
	cyclicModuleErr,
163
164
  ) where

165
166
167
{-
 ToDo:

168
  * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
169
170
171
172
173
174
175
176
177
178
  * 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 )
179
180
import TcRnDriver	( tcRnLookupRdrName, tcRnGetInfo,
			  tcRnLookupName, getModuleExports )
181
182
import RdrName		( plusGlobalRdrEnv, Provenance(..), 
			  ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
183
			  mkGlobalRdrEnv )
184
import HscMain		( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
Simon Marlow's avatar
Simon Marlow committed
185
import Name		( nameOccName )
186
187
188
189
190
import Type		( tidyType )
import VarEnv		( emptyTidyEnv )
import GHC.Exts		( unsafeCoerce# )
#endif

191
import Packages		( initPackages )
192
import NameSet		( NameSet, nameSetToList, elemNameSet )
Simon Marlow's avatar
Simon Marlow committed
193
import RdrName		( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..), 
194
195
			  globalRdrEnvElts, extendGlobalRdrEnv,
                          emptyGlobalRdrEnv )
196
import HsSyn
197
198
199
import Type		( Kind, Type, dropForAlls, PredType, ThetaType,
			  pprThetaArrow, pprParendType, splitForAllTys,
			  funResultTy )
200
import Id		( Id, idType, isImplicitId, isDeadBinder,
201
                          isExportedId, isLocalId, isGlobalId,
202
203
                          isRecordSelector, recordSelectorFieldLabel,
                          isPrimOpId, isFCallId, isClassOpId_maybe,
204
205
                          isDataConWorkId, idDataCon,
                          isBottomingId )
206
207
import Var		( TyVar )
import TysPrim		( alphaTyVars )
208
import TyCon		( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
209
			  isPrimTyCon, isFunTyCon, tyConArity,
210
			  tyConTyVars, tyConDataCons, synTyConDefn, synTyConRhs )
211
212
213
214
215
216
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
217
			  nameSrcLoc )
218
import OccName		( parenSymOcc )
219
import NameEnv		( nameEnvElts )
220
import InstEnv		( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
221
import SrcLoc
222
223
import DriverPipeline
import DriverPhases	( Phase(..), isHaskellSrcFilename, startPhase )
224
import HeaderInfo	( getImports, getOptions )
225
import Finder
226
import HscMain		( newHscEnv, hscFileCheck, HscChecked(..) )
227
228
229
230
import HscTypes
import DynFlags
import SysTools		( initSysTools, cleanTempFiles )
import Module
Simon Marlow's avatar
Simon Marlow committed
231
232
import UniqFM
import PackageConfig    ( PackageId )
233
234
import FiniteMap
import Panic
235
import Digraph
236
import Bag		( unitBag )
237
import ErrUtils		( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
Simon Marlow's avatar
Simon Marlow committed
238
			  mkPlainErrMsg, printBagOfErrors )
239
import qualified ErrUtils
240
import Util
241
import StringBuffer	( StringBuffer, hGetStringBuffer )
242
243
import Outputable
import SysTools		( cleanTempFilesExcept )
244
import BasicTypes
245
import TcType           ( tcSplitSigmaTy, isDictTy )
246
import Maybes		( expectJust, mapCatMaybes )
247
248
249

import Control.Concurrent
import System.Directory ( getModificationTime, doesFileExist )
250
import Data.Maybe	( isJust, isNothing )
251
252
253
254
255
256
257
258
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
259
import System.IO.Error	( isDoesNotExistError )
260
import Prelude hiding (init)
261

262
263
264
265
266
267
#if __GLASGOW_HASKELL__ < 600
import System.IO as System.IO.Error ( try )
#else
import System.IO.Error	( try )
#endif

268
-- -----------------------------------------------------------------------------
269
-- Exception handlers
270
271
272
273
274

-- | 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.
275
276
defaultErrorHandler :: DynFlags -> IO a -> IO a
defaultErrorHandler dflags inner = 
277
278
279
280
281
  -- 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
282
283
		IOException _ ->
		  fatalErrorMsg dflags (text (show exception))
284
		AsyncException StackOverflow ->
285
286
287
		  fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
		_other ->
		  fatalErrorMsg dflags (text (show (Panic (show exception))))
288
289
290
	   exitWith (ExitFailure 1)
         ) $

291
292
  -- program errors: messages with locations attached.  Sometimes it is
  -- convenient to just throw these as exceptions.
293
  handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
294
295
296
			exitWith (ExitFailure 1)) $

  -- error messages propagated as exceptions
297
298
299
300
301
  handleDyn (\dyn -> do
  		hFlush stdout
  		case dyn of
		     PhaseFailed _ code -> exitWith code
		     Interrupted -> exitWith (ExitFailure 1)
302
		     _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
303
304
305
306
307
308
309
310
			     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.
311
312
defaultCleanupHandler :: DynFlags -> IO a -> IO a
defaultCleanupHandler dflags inner = 
313
   -- make sure we clean up after ourselves
314
315
   later (unless (dopt Opt_KeepTmpFiles dflags) $ 
	    cleanTempFiles dflags) 
316
317
318
319
320
321
322
	-- 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
323
-- TopDir path without the '-B' prefix.
324

325
326
init :: Maybe String -> IO ()
init mbMinusB = do
327
   -- catch ^C
328
329
   main_thread <- myThreadId
   putMVar interruptTargetThread [main_thread]
330
331
   installSignalHandlers

332
   dflags0 <- initSysTools mbMinusB defaultDynFlags
333
   writeIORef v_initDynFlags dflags0
334

335
336
337
338
339
340
341
342
343
344
345
346
347
348
-- | 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))
349
350
351
352

GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
	-- stores the DynFlags between the call to init and subsequent
	-- calls to newSession.
353
354
355

-- | Starts a new session.  A session consists of a set of loaded
-- modules, a set of options (DynFlags), and an interactive context.
356
-- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
357
358
359
-- code".
newSession :: GhcMode -> IO Session
newSession mode = do
360
361
362
  dflags0 <- readIORef v_initDynFlags
  dflags <- initDynFlags dflags0
  env <- newHscEnv dflags{ ghcMode=mode }
363
  ref <- newIORef env
364
365
366
367
368
369
370
371
372
373
374
375
  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
376
377
378
379
380
381

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

-- | Grabs the DynFlags from the Session
getSessionDynFlags :: Session -> IO DynFlags
382
getSessionDynFlags s = withSession s (return . hsc_dflags)
383
384

-- | Updates the DynFlags in a Session
385
386
setSessionDynFlags :: Session -> DynFlags -> IO ()
setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
387

388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
-- | 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 } }

405
-- -----------------------------------------------------------------------------
406
-- Targets
407
408
409
410
411
412

-- 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
413
-- the program\/library.  Unloading the current program is achieved by
414
-- setting the current set of targets to be empty, followed by load.
415
setTargets :: Session -> [Target] -> IO ()
416
setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
417
418

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

422
-- | Add another target
423
424
425
addTarget :: Session -> Target -> IO ()
addTarget s target
  = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
426

427
428
429
430
431
432
-- | 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 ]
433

434
435
436
437
438
439
440
441
442
-- 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
--
443
444
445
446
guessTarget :: String -> Maybe Phase -> IO Target
guessTarget file (Just phase)
   = return (Target (TargetFile file (Just phase)) Nothing)
guessTarget file Nothing
447
   | isHaskellSrcFilename file
448
   = return (Target (TargetFile file Nothing) Nothing)
449
450
   | otherwise
   = do exists <- doesFileExist hs_file
451
452
453
	if exists
	   then return (Target (TargetFile hs_file Nothing) Nothing)
	   else do
454
	exists <- doesFileExist lhs_file
455
456
457
	if exists
	   then return (Target (TargetFile lhs_file Nothing) Nothing)
	   else do
Simon Marlow's avatar
Simon Marlow committed
458
	return (Target (TargetModule (mkModuleName file)) Nothing)
459
     where 
460
461
	 hs_file  = file `joinFileExt` "hs"
	 lhs_file = file `joinFileExt` "lhs"
462

463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
-- -----------------------------------------------------------------------------
-- Extending the program scope

extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
extendGlobalRdrScope session rdrElts
    = modifySession session $ \hscEnv ->
      let global_rdr = hsc_global_rdr_env hscEnv
      in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }

setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
setGlobalRdrScope session rdrElts
    = modifySession session $ \hscEnv ->
      hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }

extendGlobalTypeScope :: Session -> [Id] -> IO ()
extendGlobalTypeScope session ids
    = modifySession session $ \hscEnv ->
      let global_type = hsc_global_type_env hscEnv
      in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }

setGlobalTypeScope :: Session -> [Id] -> IO ()
setGlobalTypeScope session ids
    = modifySession session $ \hscEnv ->
      hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }

488
489
-- -----------------------------------------------------------------------------
-- Loading the program
490

491
492
-- Perform a dependency analysis starting from the current targets
-- and update the session with the new module graph.
Simon Marlow's avatar
Simon Marlow committed
493
depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
494
depanal (Session ref) excluded_mods allow_dup_roots = do
495
496
497
498
499
500
501
502
  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"
503
  when (gmode == BatchCompile) $
504
	debugTraceMsg dflags 2 (hcat [
505
		     text "Chasing modules from: ",
506
	     		hcat (punctuate comma (map pprTarget targets))])
507

508
  r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
509
  case r of
510
    Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
511
512
    _ -> return ()
  return r
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
{-
-- | 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
Simon Marlow's avatar
Simon Marlow committed
532
533
   | LoadUpTo ModuleName
   | LoadDependenciesOf ModuleName
534
535
536
537

-- | 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.
538
load :: Session -> LoadHowMuch -> IO SuccessFlag
539
load s@(Session ref) how_much
540
   = do 
541
542
543
544
	-- 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.
545
	mb_graph <- depanal s [] False
546
547
548
	case mb_graph of	   
	   Just mod_graph -> load2 s how_much mod_graph 
	   Nothing        -> return Failed
549

550
load2 s@(Session ref) how_much mod_graph = do
551
        guessOutputFile s
552
553
554
555
	hsc_env <- readIORef ref

        let hpt1      = hsc_HPT hsc_env
        let dflags    = hsc_dflags hsc_env
556
        let ghci_mode = ghcMode dflags -- this never changes
557
558
559
560
561

	-- 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)
Simon Marlow's avatar
Simon Marlow committed
562
563
        let all_home_mods = [ms_mod_name s 
			    | s <- mod_graph, not (isBootSummary s)]
564
#ifdef DEBUG
565
	    bad_boot_mods = [s 	      | s <- mod_graph, isBootSummary s,
Simon Marlow's avatar
Simon Marlow committed
566
					not (ms_mod_name s `elem` all_home_mods)]
567
#endif
568
569
570
571
572
573
574
575
	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]
576
	    mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
577

578
579
580
581
582
583
584
585
586
587
588
589
590
	    -- 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

591
592
	debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
				text "Stable BCO:" <+> ppr stable_bco)
593
594

	-- Unload any modules which are going to be re-linked this time around.
595
596
	let stable_linkables = [ linkable
			       | m <- stable_obj++stable_bco,
Simon Marlow's avatar
Simon Marlow committed
597
				 Just hmi <- [lookupUFM pruned_hpt m],
598
				 Just linkable <- [hm_linkable hmi] ]
599
600
601
602
603
604
605
606
607
608
609
610
	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.

611
612
613
614
615
616
        -- 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.
617
        let full_mg :: [SCC ModSummary]
618
	    full_mg    = topSortModuleGraph False mod_graph Nothing
619
620
621

	    maybe_top_mod = case how_much of
				LoadUpTo m           -> Just m
622
			  	LoadDependenciesOf m -> Just m
623
624
			  	_		     -> Nothing

625
626
627
628
629
630
631
632
633
	    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 
Simon Marlow's avatar
Simon Marlow committed
634
			    AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
635
636
637
638
		  List.init partial_mg0
		| otherwise
		= partial_mg0
  
639
640
641
	    stable_mg = 
		[ AcyclicSCC ms
	        | AcyclicSCC ms <- full_mg,
Simon Marlow's avatar
Simon Marlow committed
642
643
644
		  ms_mod_name ms `elem` stable_obj++stable_bco,
		  ms_mod_name ms `notElem` [ ms_mod_name ms' | 
						AcyclicSCC ms' <- partial_mg ] ]
645
646
647

	    mg = stable_mg ++ partial_mg

648
649
	-- clean up between compilations
	let cleanup = cleanTempFilesExcept dflags
650
			  (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
651

652
653
        (upsweep_ok, hsc_env1, modsUpswept)
           <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
654
			   pruned_hpt stable_mods cleanup mg
655
656
657
658
659

	-- 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).

660
        let modsDone = reverse modsUpswept
661
662
663
664
665
666
667
668

        -- 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.
669
           do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
670
671
672
673
674
675
676
677
678
679
680
681
682

	      -- 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 
683
684
	 	main_mod = mainModIs dflags
		a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
685
686
		do_linking = a_root_is_Main || no_hs_main

687
	      when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
688
689
	        debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
				              "but no output will be generated\n" ++
Simon Marlow's avatar
Simon Marlow committed
690
				              "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
691
692

	      -- link everything together
693
              linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
694

695
	      loadFinish Succeeded linkresult ref hsc_env1
696
697
698
699
700

         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.
701
           do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
702
703
704
705
706
707
708
709
710
711

              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

Simon Marlow's avatar
Simon Marlow committed
712
              let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep) 
713
					      (hsc_HPT hsc_env1)
714
715
716
717

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

718
719
	      -- there should be no Nothings where linkables should be, now
	      ASSERT(all (isJust.hm_linkable) 
Simon Marlow's avatar
Simon Marlow committed
720
			(eltsUFM (hsc_HPT hsc_env))) do
721
	
722
723
724
	      -- Link everything together
              linkresult <- link ghci_mode dflags False hpt4

725
	      let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
	      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

742

743
744
745
746
747
748
749
750
751
752
-- 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.
753
ppFilesFromSummaries summaries = map ms_hspp_file summaries
754

755
756
757
758
759
-- -----------------------------------------------------------------------------
-- Check module

data CheckedModule = 
  CheckedModule { parsedSource      :: ParsedSource,
760
		  renamedSource     :: Maybe RenamedSource,
761
762
763
		  typecheckedSource :: Maybe TypecheckedSource,
		  checkedModuleInfo :: Maybe ModuleInfo
	        }
764
765
766
767
768
	-- 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.
769

770
type ParsedSource      = Located (HsModule RdrName)
771
type RenamedSource     = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name])
772
773
type TypecheckedSource = LHsBinds Id

774
775
776
777
778
779
780
781
782
783
784
785
786
-- 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


787
788
789
790
-- | 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.
Simon Marlow's avatar
Simon Marlow committed
791
checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
792
checkModule session@(Session ref) mod = do
793
	-- load up the dependencies first
794
   r <- load session (LoadDependenciesOf mod)
795
796
797
798
799
   if (failed r) then return Nothing else do

	-- now parse & typecheck the module
   hsc_env <- readIORef ref   
   let mg  = hsc_mod_graph hsc_env
Simon Marlow's avatar
Simon Marlow committed
800
   case [ ms | ms <- mg, ms_mod_name ms == mod ] of
801
802
	[] -> return Nothing
	(ms:_) -> do 
803
	   mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
804
805
806
	   case mbChecked of
             Nothing -> return Nothing
             Just (HscChecked parsed renamed Nothing) ->
807
808
809
810
811
		   return (Just (CheckedModule {
					parsedSource = parsed,
					renamedSource = renamed,
					typecheckedSource = Nothing,
					checkedModuleInfo = Nothing }))
812
813
             Just (HscChecked parsed renamed
			   (Just (tc_binds, rdr_env, details))) -> do
814
		   let minf = ModuleInfo {
815
816
817
818
				minf_type_env  = md_types details,
				minf_exports   = md_exports details,
				minf_rdr_env   = Just rdr_env,
				minf_instances = md_insts details
819
820
821
			      }
		   return (Just (CheckedModule {
					parsedSource = parsed,
822
					renamedSource = renamed,
823
824
825
826
					typecheckedSource = Just tc_binds,
					checkedModuleInfo = Just minf }))

-- ---------------------------------------------------------------------------
827
828
829
830
831
-- Unloading

unload :: HscEnv -> [Linkable] -> IO ()
unload hsc_env stable_linkables	-- Unload everthing *except* 'stable_linkables'
  = case ghcMode (hsc_dflags hsc_env) of
832
833
	BatchCompile  -> return ()
	JustTypecheck -> return ()
834
835
836
837
838
839
840
#ifdef GHCI
	Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
#else
	Interactive -> panic "unload: no interpreter"
#endif
	other -> panic "unload: strange mode"

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
893
894
895
-- -----------------------------------------------------------------------------
-- 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)
Simon Marlow's avatar
Simon Marlow committed
896
897
898
	-> [ModuleName]			-- all home modules
	-> ([ModuleName],		-- stableObject
	    [ModuleName])		-- stableBCO
899
900
901
902
903
904
905
906
907

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
Simon Marlow's avatar
Simon Marlow committed
908
	scc_mods = map ms_mod_name scc
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
	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
Simon Marlow's avatar
Simon Marlow committed
930
	     same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
931
932
				Just hmi  | Just l <- hm_linkable hmi
				 -> isObjectLinkable l && t == linkableTime l
933
				_other  -> True
934
		-- why '>=' rather than '>' above?  If the filesystem stores
935
936
937
938
939
940
		-- 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.

941
	bco_ok ms
Simon Marlow's avatar
Simon Marlow committed
942
	  = case lookupUFM hpt (ms_mod_name ms) of
943
944
945
		Just hmi  | Just l <- hm_linkable hmi ->
			not (isObjectLinkable l) && 
			linkableTime l >= ms_hs_date ms
946
		_other  -> False
947

Simon Marlow's avatar
Simon Marlow committed
948
ms_allimps :: ModSummary -> [ModuleName]
949
ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
950

951
952
-- -----------------------------------------------------------------------------
-- Prune the HomePackageTable
953

954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
-- 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]
Simon Marlow's avatar
Simon Marlow committed
969
   -> ([ModuleName],[ModuleName])
970
971
972
   -> HomePackageTable

pruneHomePackageTable hpt summ (stable_obj, stable_bco)
Simon Marlow's avatar
Simon Marlow committed
973
  = mapUFM prune hpt
974
975
976
977
  where prune hmi
	  | is_stable modl = hmi'
	  | otherwise      = hmi'{ hm_details = emptyModDetails }
	  where
Simon Marlow's avatar
Simon Marlow committed
978
	   modl = moduleName (mi_module (hm_iface hmi))
979
980
981
982
	   hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
		= hmi{ hm_linkable = Nothing }
		| otherwise
		= hmi
Simon Marlow's avatar
Simon Marlow committed
983
		where ms = expectJust "prune" (lookupUFM ms_map modl)
984

Simon Marlow's avatar
Simon Marlow committed
985
        ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
986

987
988
989
	is_stable m = m `elem` stable_obj || m `elem` stable_bco

-- -----------------------------------------------------------------------------
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

-- 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

1011
1012
1013
1014
1015
-- -----------------------------------------------------------------------------
-- 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.
1016
1017

-- There better had not be any cyclic groups here -- we check for them.
1018
1019
1020
1021

upsweep
    :: HscEnv			-- Includes initially-empty HPT
    -> HomePackageTable		-- HPT from last time round (pruned)
Simon Marlow's avatar
Simon Marlow committed
1022
    -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1023
1024
1025
1026
1027
1028
    -> 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

1029
1030
upsweep hsc_env old_hpt stable_mods cleanup mods
   = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1031

1032
upsweep' hsc_env old_hpt stable_mods cleanup
1033
     [] _ _
1034
1035
   = return (Succeeded, hsc_env, [])

1036
upsweep' hsc_env old_hpt stable_mods cleanup
1037
     (CyclicSCC ms:_) _ _
1038
   = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1039
1040
        return (Failed, hsc_env, [])

1041
upsweep' hsc_env old_hpt stable_mods cleanup
1042
     (AcyclicSCC mod:mods) mod_index nmods
1043
1044
1045
1046
   = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
	--	     show (map (moduleUserString.moduleName.mi_module.hm_iface) 
	--		       (moduleEnvElts (hsc_HPT hsc_env)))

1047
        mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
1048
                       mod_index nmods
1049
1050
1051
1052
1053
1054

	cleanup		-- Remove unwanted tmp files between compilations

        case mb_mod_info of
	    Nothing -> return (Failed, hsc_env, [])
	    Just mod_info -> do 
Simon Marlow's avatar
Simon Marlow committed
1055
		{ let this_mod = ms_mod_name mod
1056
1057

			-- Add new info to hsc_env
Simon Marlow's avatar
Simon Marlow committed
1058
		      hpt1     = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1059
		      hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1060
1061
1062
1063

			-- Space-saving: delete the old HPT entry
			-- for mod BUT if mod is a hs-boot
			-- node, don't delete it.  For the
1064
1065
1066
			-- interface, the HPT entry is probaby for the
			-- main Haskell source file.  Deleting it
			-- would force .. (what?? --SDM)
1067
		      old_hpt1 | isBootSummary mod = old_hpt
Simon Marlow's avatar
Simon Marlow committed
1068
			       | otherwise = delFromUFM old_hpt this_mod
1069

1070
		; (restOK, hsc_env2, modOKs) 
1071
			<- upsweep' hsc_env1 old_hpt1 stable_mods cleanup 
1072
				mods (mod_index+1) nmods
1073
1074
		; return (restOK, hsc_env2, mod:modOKs)
		}
1075
1076
1077
1078
1079


-- Compile a single module.  Always produce a Linkable for it if 
-- successful.  If no compilation happened, return the old Linkable.
upsweep_mod :: HscEnv
1080
            -> HomePackageTable
Simon Marlow's avatar
Simon Marlow committed
1081
	    -> ([ModuleName],[ModuleName])
1082
            -> ModSummary
1083
1084
            -> Int  -- index of module
            -> Int  -- total number of modules
1085
1086
            -> IO (Maybe HomeModInfo)	-- Nothing => Failed

1087
upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1088
   = do 
1089
        let 
Simon Marlow's avatar
Simon Marlow committed
1090
	    this_mod_name = ms_mod_name summary
1091
1092
1093
1094
1095
1096
	    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)
Simon Marlow's avatar
Simon Marlow committed
1097
	    compile_it  = upsweep_compile hsc_env old_hpt this_mod_name 
1098
				summary mod_index nmods
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144

	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
Simon Marlow's avatar
Simon Marlow committed
1145
1146
		    is_stable_obj = this_mod_name `elem` stable_obj
		    is_stable_bco = this_mod_name `elem` stable_bco
1147

Simon Marlow's avatar
Simon Marlow committed
1148
		    old_hmi = lookupUFM old_hpt this_mod_name
1149
1150

-- Run hsc to compile a module
1151
upsweep_compile hsc_env old_hpt this_mod summary
1152
1153
                mod_index nmods
                mb_old_linkable = do
1154
  let
1155
1156
	-- The old interface is ok if it's in the old HPT 
	--	a) we're compiling a source file, and the old HPT
1157
	--	   entry is for a source file
1158
1159
1160
1161
1162
1163
	--	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

1164
        mb_old_iface 
Simon Marlow's avatar
Simon Marlow committed
1165
		= case lookupUFM old_hpt this_mod of
1166
1167
1168
1169
1170
1171
1172
		     Nothing	 			  -> Nothing
		     Just hm_info | isBootSummary summary -> Just iface
				  | not (mi_boot iface)   -> Just iface
				  | otherwise		  -> Nothing
				   where 
				     iface = hm_iface hm_info

1173
  compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1174
                        mod_index nmods
1175