GHC.hs 71.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
	-- * 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 212 213
import GetImports	( getImports )
import Packages		( isHomePackage )
import Finder
214
import HscMain		( newHscEnv, hscFileCheck, HscResult(..) )
215 216 217 218 219 220 221
import HscTypes
import DynFlags
import StaticFlags
import SysTools		( initSysTools, cleanTempFiles )
import Module
import FiniteMap
import Panic
222
import Digraph
223
import Bag		( unitBag )
224
import ErrUtils		( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
225
			  mkPlainErrMsg, printBagOfErrors, printErrorsAndWarnings )
226
import qualified ErrUtils
227
import Util
228
import StringBuffer	( StringBuffer, hGetStringBuffer )
229 230
import Outputable
import SysTools		( cleanTempFilesExcept )
231
import BasicTypes
232
import TcType           ( tcSplitSigmaTy, isDictTy )
233
import Maybes		( expectJust, mapCatMaybes )
234 235 236 237 238 239 240 241 242 243 244 245

import Control.Concurrent
import System.Directory ( getModificationTime, doesFileExist )
import Data.Maybe	( isJust, isNothing, fromJust )
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
246
import System.IO.Error	( isDoesNotExistError )
247
import System.IO.Unsafe	( unsafePerformIO )
248
import Prelude hiding (init)
249

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

256
-- -----------------------------------------------------------------------------
257
-- Exception handlers
258 259 260 261 262

-- | 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.
263 264
defaultErrorHandler :: DynFlags -> IO a -> IO a
defaultErrorHandler dflags inner = 
265 266 267 268 269
  -- 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
270 271
		IOException _ ->
		  fatalErrorMsg dflags (text (show exception))
272
		AsyncException StackOverflow ->
273 274 275
		  fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
		_other ->
		  fatalErrorMsg dflags (text (show (Panic (show exception))))
276 277 278
	   exitWith (ExitFailure 1)
         ) $

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

  -- error messages propagated as exceptions
285 286 287 288 289
  handleDyn (\dyn -> do
  		hFlush stdout
  		case dyn of
		     PhaseFailed _ code -> exitWith code
		     Interrupted -> exitWith (ExitFailure 1)
290
		     _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
291 292 293 294 295 296 297 298
			     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.
299 300
defaultCleanupHandler :: DynFlags -> IO a -> IO a
defaultCleanupHandler dflags inner = 
301
   -- make sure we clean up after ourselves
302 303
   later (unless (dopt Opt_KeepTmpFiles dflags) $ 
	    cleanTempFiles dflags) 
304 305 306 307 308 309 310
	-- 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
311
-- TopDir path without the '-B' prefix.
312

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

320
   dflags0 <- initSysTools mbMinusB defaultDynFlags
321
   writeIORef v_initDynFlags dflags0
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336
-- | 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))
337 338 339 340

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

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

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

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

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

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
-- | 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 } }

393
-- -----------------------------------------------------------------------------
394
-- Targets
395 396 397 398 399 400

-- 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
401
-- the program\/library.  Unloading the current program is achieved by
402
-- setting the current set of targets to be empty, followed by load.
403
setTargets :: Session -> [Target] -> IO ()
404
setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
405 406

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

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

415 416 417 418 419 420
-- | 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 ]
421

422 423 424 425 426 427 428 429 430
-- 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
--
431 432 433 434
guessTarget :: String -> Maybe Phase -> IO Target
guessTarget file (Just phase)
   = return (Target (TargetFile file (Just phase)) Nothing)
guessTarget file Nothing
435
   | isHaskellSrcFilename file
436
   = return (Target (TargetFile file Nothing) Nothing)
437 438
   | otherwise
   = do exists <- doesFileExist hs_file
439 440 441
	if exists
	   then return (Target (TargetFile hs_file Nothing) Nothing)
	   else do
442
	exists <- doesFileExist lhs_file
443 444 445
	if exists
	   then return (Target (TargetFile lhs_file Nothing) Nothing)
	   else do
446 447
	return (Target (TargetModule (mkModule file)) Nothing)
     where 
448 449
	 hs_file  = file `joinFileExt` "hs"
	 lhs_file = file `joinFileExt` "lhs"
450 451 452

-- -----------------------------------------------------------------------------
-- Loading the program
453

454 455
-- Perform a dependency analysis starting from the current targets
-- and update the session with the new module graph.
456
depanal :: Session -> [Module] -> Bool -> IO (Maybe ModuleGraph)
457
depanal (Session ref) excluded_mods allow_dup_roots = do
458 459 460 461 462 463 464 465
  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"
466
  when (gmode == BatchCompile) $
467
	debugTraceMsg dflags 1 (hcat [
468
		     text "Chasing modules from: ",
469
	     		hcat (punctuate comma (map pprTarget targets))])
470

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

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
{-
-- | 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
496
   | LoadDependenciesOf Module
497 498 499 500

-- | 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.
501
load :: Session -> LoadHowMuch -> IO SuccessFlag
502
load s@(Session ref) how_much
503
   = do 
504 505 506 507
	-- 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.
508
	mb_graph <- depanal s [] False
509 510 511
	case mb_graph of	   
	   Just mod_graph -> load2 s how_much mod_graph 
	   Nothing        -> return Failed
512

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

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

	-- 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)]
526
#ifdef DEBUG
527 528
	    bad_boot_mods = [s 	      | s <- mod_graph, isBootSummary s,
					not (ms_mod s `elem` all_home_mods)]
529
#endif
530 531 532 533 534 535 536 537
	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]
538
	    mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
539

540 541 542 543 544 545 546 547 548 549 550 551 552
	    -- 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

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

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

573 574 575 576 577 578
        -- 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.
579
        let full_mg :: [SCC ModSummary]
580
	    full_mg    = topSortModuleGraph False mod_graph Nothing
581 582 583

	    maybe_top_mod = case how_much of
				LoadUpTo m           -> Just m
584
			  	LoadDependenciesOf m -> Just m
585 586
			  	_		     -> Nothing

587 588 589 590 591 592 593 594 595 596 597 598 599 600
	    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
  
601 602 603 604 605 606 607 608 609
	    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

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

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

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

622
        let modsDone = reverse modsUpswept
623 624 625 626 627 628 629 630

        -- 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.
631
           do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
632 633 634 635 636 637 638 639 640 641 642 643 644

	      -- 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 
645 646
	 	main_mod = mainModIs dflags
		a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
647 648
		do_linking = a_root_is_Main || no_hs_main

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

	      -- link everything together
655
              linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
656

657
	      loadFinish Succeeded linkresult ref hsc_env1
658 659 660 661 662

         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.
663
           do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
664 665 666 667 668 669 670 671 672 673 674

              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) 
675
					      (hsc_HPT hsc_env1)
676 677 678 679

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

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

687
	      let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
	      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

704

705 706 707 708 709 710 711 712 713 714 715 716
-- 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.
ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]

717 718 719 720 721
-- -----------------------------------------------------------------------------
-- Check module

data CheckedModule = 
  CheckedModule { parsedSource      :: ParsedSource,
722
		  renamedSource     :: Maybe RenamedSource,
723 724 725
		  typecheckedSource :: Maybe TypecheckedSource,
		  checkedModuleInfo :: Maybe ModuleInfo
	        }
726 727 728 729 730
	-- 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.
731

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

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
-- NOTE:
--   - things that aren't in the output of the renamer:
--     - the export list
--     - the imports
--   - 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


752 753 754 755
-- | 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.
756 757
checkModule :: Session -> Module -> IO (Maybe CheckedModule)
checkModule session@(Session ref) mod = do
758
	-- load up the dependencies first
759
   r <- load session (LoadDependenciesOf mod)
760 761 762 763 764 765 766 767
   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 
768 769 770 771 772 773
	   -- Add in the OPTIONS from the source file This is nasty:
	   -- we've done this once already, in the compilation manager
	   -- It might be better to cache the flags in the
	   -- ml_hspp_file field, say
	   let dflags0 = hsc_dflags hsc_env
	       hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
774 775
	       filename = fromJust (ml_hs_file (ms_location ms))
	       opts = getOptionsFromStringBuffer hspp_buf filename
776 777
	   (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
	   if (not (null leftovers))
778
		then do printErrorsAndWarnings dflags1 (optionsErrorMsgs leftovers opts filename)
779 780 781
		        return Nothing
		else do

782
	   r <- hscFileCheck hsc_env{hsc_dflags=dflags1} ms
783 784 785
	   case r of
		HscFail -> 
		   return Nothing
786 787 788 789 790 791 792 793
		HscChecked parsed renamed Nothing ->
		   return (Just (CheckedModule {
					parsedSource = parsed,
					renamedSource = renamed,
					typecheckedSource = Nothing,
					checkedModuleInfo = Nothing }))
		HscChecked parsed renamed
			   (Just (tc_binds, rdr_env, details)) -> do
794
		   let minf = ModuleInfo {
795 796 797 798
				minf_type_env  = md_types details,
				minf_exports   = md_exports details,
				minf_rdr_env   = Just rdr_env,
				minf_instances = md_insts details
799 800 801
			      }
		   return (Just (CheckedModule {
					parsedSource = parsed,
802
					renamedSource = renamed,
803 804
					typecheckedSource = Just tc_binds,
					checkedModuleInfo = Just minf }))
805 806
		_other ->
			panic "checkModule"
807 808

-- ---------------------------------------------------------------------------
809 810 811 812 813
-- Unloading

unload :: HscEnv -> [Linkable] -> IO ()
unload hsc_env stable_linkables	-- Unload everthing *except* 'stable_linkables'
  = case ghcMode (hsc_dflags hsc_env) of
814 815
	BatchCompile  -> return ()
	JustTypecheck -> return ()
816 817 818 819 820 821 822
#ifdef GHCI
	Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
#else
	Interactive -> panic "unload: no interpreter"
#endif
	other -> panic "unload: strange mode"

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 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
-- -----------------------------------------------------------------------------
-- 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
915
				_other  -> True
916
		-- why '>=' rather than '>' above?  If the filesystem stores
917 918 919 920 921 922
		-- 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.

923 924 925 926 927
	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
928
		_other  -> False
929

930
ms_allimps :: ModSummary -> [Module]
931
ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
932

933 934
-- -----------------------------------------------------------------------------
-- Prune the HomePackageTable
935

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
-- 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)
966

967
        ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
968

969 970 971
	is_stable m = m `elem` stable_obj || m `elem` stable_bco

-- -----------------------------------------------------------------------------
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992

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

993 994 995 996 997
-- -----------------------------------------------------------------------------
-- 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.
998 999

-- There better had not be any cyclic groups here -- we check for them.
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

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

1011 1012
upsweep hsc_env old_hpt stable_mods cleanup mods
   = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1013

1014
upsweep' hsc_env old_hpt stable_mods cleanup
1015
     [] _ _
1016 1017
   = return (Succeeded, hsc_env, [])

1018
upsweep' hsc_env old_hpt stable_mods cleanup
1019
     (CyclicSCC ms:_) _ _
1020
   = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1021 1022
        return (Failed, hsc_env, [])

1023
upsweep' hsc_env old_hpt stable_mods cleanup
1024
     (AcyclicSCC mod:mods) mod_index nmods
1025 1026 1027 1028
   = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
	--	     show (map (moduleUserString.moduleName.mi_module.hm_iface) 
	--		       (moduleEnvElts (hsc_HPT hsc_env)))

1029
        mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
wolfgang's avatar