TcRnDriver.lhs 43.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[TcModule]{Typechecking a whole module}

\begin{code}
module TcRnDriver (
#ifdef GHCI
	mkGlobalContext, getModuleContents,
#endif
11 12
	tcRnModule, checkOldIface, 
	importSupportingDecls, tcTopSrcDecls,
13 14 15 16 17
	tcRnIface, tcRnExtCore, tcRnStmt, tcRnExpr, tcRnThing
    ) where

#include "HsVersions.h"

18
#ifdef GHCI
chak's avatar
chak committed
19
import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
20
import		      DsMeta   ( templateHaskellNames )
21 22
#endif

23
import CmdLineOpts	( DynFlag(..), opt_PprStyle_Debug, dopt )
24 25
import DriverState	( v_MainModIs, v_MainFunIs )
import DriverUtil	( split_longest_prefix )
26
import HsSyn		( HsModule(..), HsBinds(..), MonoBinds(..), HsExpr(..),
27
			  Stmt(..), Pat(VarPat), HsStmtContext(..), RuleDecl(..),
28
			  HsGroup(..), SpliceDecl(..),
29
			  mkSimpleMatch, placeHolderType, toHsType, andMonoBinds,
30
			  isSrcRule, collectStmtsBinders
31
			)
32
import RdrHsSyn		( RdrNameHsModule, RdrNameHsDecl, RdrNameStmt, RdrNameHsExpr,
33
			  emptyGroup, mkGroup, findSplice, addImpDecls, main_RDR_Unqual )
34 35 36 37 38 39

import PrelNames	( iNTERACTIVE, ioTyConName, printName,
			  returnIOName, bindIOName, failIOName, thenIOName, runIOName, 
			  dollarMainName, itName, mAIN_Name
			)
import MkId		( unsafeCoerceId )
40
import RdrName		( RdrName, getRdrName, mkRdrUnqual, 
41 42
			  lookupRdrEnv, elemRdrEnv )

43
import RnHsSyn		( RenamedStmt, RenamedTyClDecl, 
44 45
			  ruleDeclFVs, instDeclFVs, tyClDeclFVs )
import TcHsSyn		( TypecheckedHsExpr, TypecheckedRuleDecl,
46
			  zonkTopDecls, mkHsLet,
47
			  zonkTopExpr, zonkTopBndrs
48 49
			)

50
import TcExpr 		( tcInferRho )
51 52 53
import TcRnMonad
import TcMType		( newTyVarTy, zonkTcType )
import TcType		( Type, liftedTypeKind, 
54
			  tyVarsOfType, tcFunResultTy, tidyTopType,
55 56 57 58 59 60 61
			  mkForAllTys, mkFunTys, mkTyConApp, tcSplitForAllTys
			)
import TcMatches	( tcStmtsAndThen )
import Inst		( showLIE )
import TcBinds		( tcTopBinds )
import TcClassDcl	( tcClassDecls2 )
import TcDefaults	( tcDefaults )
62
import TcEnv		( tcExtendGlobalValEnv, 
63 64 65 66 67 68 69 70 71 72 73
			  tcExtendInstEnv, tcExtendRules,
			  tcLookupTyCon, tcLookupGlobal,
			  tcLookupId 
			)
import TcRules		( tcRules )
import TcForeign	( tcForeignImports, tcForeignExports )
import TcIfaceSig	( tcInterfaceSigs, tcCoreBinds )
import TcInstDcls	( tcInstDecls1, tcIfaceInstDecls, tcInstDecls2 )
import TcSimplify	( tcSimplifyTop, tcSimplifyInfer )
import TcTyClsDecls	( tcTyAndClassDecls )

74
import RnNames		( importsFromLocalDecls, rnImports, exportsFromAvail, 
75
			  reportUnusedNames )
76 77
import RnIfaces		( slurpImpDecls, checkVersions, RecompileRequired, outOfDate )
import RnHiFiles	( readIface, loadOldIface )
78
import RnEnv		( lookupSrcName, lookupOccRn, plusGlobalRdrEnv,
79 80
			  ubiquitousNames, implicitModuleFVs, implicitStmtFVs, dataTcOccs )
import RnExpr		( rnStmts, rnExpr )
81
import RnSource		( rnSrcDecls, checkModDeprec, rnStats )
82 83 84 85 86

import CoreUnfold	( unfoldingTemplate )
import CoreSyn		( IdCoreRule, Bind(..) )
import PprCore		( pprIdRules, pprCoreBindings )
import TysWiredIn	( mkListTy, unitTy )
87
import ErrUtils		( mkDumpDoc, showPass, pprBagOfErrors )
88 89 90
import Id		( Id, mkLocalId, isLocalId, idName, idType, idUnfolding, setIdLocalExported )
import IdInfo		( GlobalIdDetails(..) )
import Var		( Var, setGlobalIdDetails )
91 92
import Module           ( Module, ModuleName, mkHomeModule, mkModuleName, moduleName, moduleUserString, moduleEnvElts )
import OccName		( mkVarOcc )
93 94 95 96 97 98 99 100 101 102 103
import Name		( Name, isExternalName, getSrcLoc, nameOccName )
import NameEnv		( delListFromNameEnv )
import NameSet
import TyCon		( tyConGenInfo )
import BasicTypes       ( EP(..), RecFlag(..) )
import SrcLoc		( noSrcLoc )
import Outputable
import HscTypes		( PersistentCompilerState(..), InteractiveContext(..),
			  ModIface, ModDetails(..), ModGuts(..),
			  HscEnv(..), 
			  ModIface(..), ModDetails(..), IfaceDecls(..),
104
			  GhciMode(..), noDependencies,
105 106 107 108 109 110 111 112 113 114 115
			  Deprecations(..), plusDeprecs,
			  emptyGlobalRdrEnv,
			  GenAvailInfo(Avail), availsToNameSet, 
			  ForeignStubs(..),
			  TypeEnv, TyThing, typeEnvTyCons, 
			  extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
			  extendLocalRdrEnv, emptyFixityEnv
			)
#ifdef GHCI
import RdrName		( rdrEnvElts )
import RnHiFiles	( loadInterface )
116
import RnEnv		( mkGlobalRdrEnv )
117 118 119 120
import HscTypes		( GlobalRdrElt(..), GlobalRdrEnv, ImportReason(..), Provenance(..), 
			  isLocalGRE )
#endif

121 122
import DATA_IOREF	( readIORef )
import FastString	( mkFastString )
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
import Panic		( showException )
import List		( partition )
import Util		( sortLt )
\end{code}



%************************************************************************
%*									*
	Typecheck and rename a module
%*									*
%************************************************************************


\begin{code}
tcRnModule :: HscEnv -> PersistentCompilerState
	   -> RdrNameHsModule 
	   -> IO (PersistentCompilerState, Maybe TcGblEnv)

tcRnModule hsc_env pcs
143
	   (HsModule maybe_mod exports import_decls local_decls mod_deprec loc)
144 145
 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;

146 147 148 149
   let { this_mod = case maybe_mod of
			Nothing  -> mkHomeModule mAIN_Name	-- 'module M where' is omitted
			Just mod -> mod } ;			-- The normal case
		
150 151 152 153
   initTc hsc_env pcs this_mod $ addSrcLoc loc $
   do { 	-- Deal with imports; sets tcg_rdr_env, tcg_imports
	(rdr_env, imports) <- rnImports import_decls ;
	updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
154
				   tcg_imports = tcg_imports gbl `plusImportAvails` imports }) 
155
		     $ do {
156
	traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
157 158 159 160 161 162 163
		-- Fail if there are any errors so far
		-- The error printing (if needed) takes advantage 
		-- of the tcg_env we have now set
	failIfErrsM ;

	traceRn (text "rn1a") ;
		-- Rename and type check the declarations
164
	(tcg_env, src_dus) <- tcRnSrcDecls local_decls ;
165 166 167 168 169 170 171 172 173 174 175 176
	setGblEnv tcg_env		$ do {

	traceRn (text "rn3") ;
		-- Check whether the entire module is deprecated
		-- This happens only once per module
		-- Returns the full new deprecations; a module deprecation 
		-- 	over-rides the earlier ones
	let { mod_deprecs = checkModDeprec mod_deprec } ;
	updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` mod_deprecs })
		  $ do {

		-- Process the export list
177
	export_avails <- exportsFromAvail maybe_mod exports ;
178 179 180
	updGblEnv (\gbl -> gbl { tcg_exports = export_avails })
		  $  do {

181 182 183 184 185 186
		-- Get any supporting decls for the exports that have not already
		-- been sucked in for the declarations in the body of the module.
		-- (This can happen if something is imported only to be re-exported.)
		--
		-- Importing these supporting declarations is required 
		--	*only* to gether usage information
187 188 189 190 191 192 193 194 195
		--	(see comments with MkIface.mkImportInfo for why)
		-- For OneShot compilation we could just throw away the decls
		-- but for Batch or Interactive we must put them in the type
		-- envt because they've been removed from the holding pen
	let { export_fvs = availsToNameSet export_avails } ;
	tcg_env <- importSupportingDecls export_fvs ;
	setGblEnv tcg_env $ do {

		-- Report unused names
196 197
	let { all_dus = src_dus `plusDU` usesOnly export_fvs } ;
 	reportUnusedNames tcg_env all_dus ;
198 199 200 201

		-- Dump output and return
	tcDump tcg_env ;
	return tcg_env
202
    }}}}}}}
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
\end{code}


%*********************************************************
%*						 	 *
\subsection{Closing up the interface decls}
%*							 *
%*********************************************************

Suppose we discover we don't need to recompile.   Then we start from the
IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.

\begin{code}
tcRnIface :: HscEnv
	  -> PersistentCompilerState
	  -> ModIface 	-- Get the decls from here
	  -> IO (PersistentCompilerState, Maybe ModDetails)
				-- Nothing <=> errors happened
tcRnIface hsc_env pcs
	    (ModIface {mi_module = mod, mi_decls = iface_decls})
  = initTc hsc_env pcs mod $ do {

	-- Get the supporting decls, and typecheck them all together
	-- so that any mutually recursive types are done right
    extra_decls <- slurpImpDecls needed ;
228
    env <- typecheckIfaceDecls (group `addImpDecls` extra_decls) ;
229 230 231 232 233 234 235 236 237 238

    returnM (ModDetails { md_types = tcg_type_env env,
			  md_insts = tcg_insts env,
			  md_rules = hsCoreRules (tcg_rules env)
		  -- All the rules from an interface are of the IfaceRuleOut form
		 }) }
  where
	rule_decls = dcl_rules iface_decls
	inst_decls = dcl_insts iface_decls
	tycl_decls = dcl_tycl  iface_decls
239 240 241
	group = emptyGroup { hs_ruleds = rule_decls,
			     hs_instds = inst_decls,
			     hs_tyclds = tycl_decls }
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
		 unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
		 unionManyNameSets (map tyClDeclFVs tycl_decls) `unionNameSets`
		 ubiquitousNames
			-- Data type decls with record selectors,
			-- which may appear in the decls, need unpackCString
			-- and friends. It's easier to just grab them right now.

hsCoreRules :: [TypecheckedRuleDecl] -> [IdCoreRule]
-- All post-typechecking Iface rules have the form IfaceRuleOut
hsCoreRules rules = [(id,rule) | IfaceRuleOut id rule <- rules]
\end{code}


%************************************************************************
%*									*
		The interactive interface 
%*									*
%************************************************************************

\begin{code}
tcRnStmt :: HscEnv -> PersistentCompilerState
	 -> InteractiveContext
	 -> RdrNameStmt
	 -> IO (PersistentCompilerState, 
		Maybe (InteractiveContext, [Name], TypecheckedHsExpr))
268
		-- The returned [Name] is the same as the input except for
269
		-- ExprStmt, in which case the returned [Name] is [itName]
270 271 272
		--
		-- The returned TypecheckedHsExpr is of type IO [ () ],
		-- a list of the bound values, coerced to ().
273 274 275 276 277 278

tcRnStmt hsc_env pcs ictxt rdr_stmt
  = initTc hsc_env pcs iNTERACTIVE $ 
    setInteractiveContext ictxt $ do {

    -- Rename; use CmdLineMode because tcRnStmt is only used interactively
279 280
    ([rn_stmt], fvs) <- initRnInteractive ictxt 
					(rnStmts DoExpr [rdr_stmt]) ;
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
    failIfErrsM ;
    
    -- Suck in the supporting declarations and typecheck them
    tcg_env <- importSupportingDecls (fvs `plusFV` implicitStmtFVs fvs) ;
	-- NB: an earlier version deleted (rdrEnvElts local_env) from
	--     the fvs.  But (a) that isn't necessary, because previously
	--     bound things in the local_env will be in the TypeEnv, and 
	--     the renamer doesn't re-slurp such things, and 
	-- (b) it's WRONG to delete them. Consider in GHCi:
	--	  Mod> let x = e :: T
	--	  Mod> let y = x + 3
	--     We need to pass 'x' among the fvs to slurpImpDecls, so that
	--     the latter can see that T is a gate, and hence import the Num T 
	--     instance decl.  (See the InTypEnv case in RnIfaces.slurpSourceRefs.)
    setGblEnv tcg_env $ do {
    
    -- The real work is done here
299
    ((bound_ids, tc_expr), lie) <- getLIE (tcUserStmt rn_stmt) ;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    
    traceTc (text "tcs 1") ;
    let {	-- Make all the bound ids "global" ids, now that
    		-- they're notionally top-level bindings.  This is
	    	-- important: otherwise when we come to compile an expression
	    	-- using these ids later, the byte code generator will consider
	    	-- the occurrences to be free rather than global.
	global_ids     = map globaliseId bound_ids ;
	globaliseId id = setGlobalIdDetails id VanillaGlobal ;
    
		-- Update the interactive context
	rn_env   = ic_rn_local_env ictxt ;
	type_env = ic_type_env ictxt ;

	bound_names = map idName global_ids ;
	new_rn_env  = extendLocalRdrEnv rn_env bound_names ;

		-- Remove any shadowed bindings from the type_env;
		-- they are inaccessible but might, I suppose, cause 
		-- a space leak if we leave them there
	shadowed = [ n | name <- bound_names,
			 let rdr_name = mkRdrUnqual (nameOccName name),
			 Just n <- [lookupRdrEnv rn_env rdr_name] ] ;

	filtered_type_env = delListFromNameEnv type_env shadowed ;
	new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;

	new_ic = ictxt { ic_rn_local_env = new_rn_env, 
		  	 ic_type_env     = new_type_env }
    } ;

    dumpOptTcRn Opt_D_dump_tc 
    	(vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
    	       text "Typechecked expr" <+> ppr tc_expr]) ;

    returnM (new_ic, bound_names, tc_expr)
    }}
\end{code}		


Here is the grand plan, implemented in tcUserStmt

	What you type			The IO [HValue] that hscStmt returns
	-------------			------------------------------------
	let pat = expr		==> 	let pat = expr in return [coerce HVal x, coerce HVal y, ...]
					bindings: [x,y,...]

	pat <- expr		==> 	expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
					bindings: [x,y,...]

	expr (of IO type)	==>	expr >>= \ v -> return [coerce HVal v]
	  [NB: result not printed]	bindings: [it]
	  
	expr (of non-IO type,	==>	let v = expr in print v >> return [coerce HVal v]
	  result showable)		bindings: [it]

	expr (of non-IO type, 
	  result not showable)	==>	error


\begin{code}
---------------------------
362 363 364
tcUserStmt :: RenamedStmt -> TcM ([Id], TypecheckedHsExpr)
tcUserStmt (ExprStmt expr _ loc)
  = newUnique 		`thenM` \ uniq ->
365 366 367 368 369
    let 
	fresh_it = itName uniq
        the_bind = FunMonoBind fresh_it False 
			[ mkSimpleMatch [] expr placeHolderType loc ] loc
    in
370
    tryTcLIE_ (do { 	-- Try this if the other fails
371
		traceTc (text "tcs 1b") ;
372
		tc_stmts [
373 374 375 376 377
		    LetStmt (MonoBind the_bind [] NonRecursive),
		    ExprStmt (HsApp (HsVar printName) (HsVar fresh_it)) 
			     placeHolderType loc] })
	  (do { 	-- Try this first 
		traceTc (text "tcs 1a") ;
378
		tc_stmts [BindStmt (VarPat fresh_it) expr loc] })
379

380
tcUserStmt stmt = tc_stmts [stmt]
381 382

---------------------------
383
tc_stmts stmts
384 385 386 387 388
 = do { io_ids <- mappM tcLookupId 
			[returnIOName, failIOName, bindIOName, thenIOName] ;
	ioTyCon <- tcLookupTyCon ioTyConName ;
	res_ty  <- newTyVarTy liftedTypeKind ;
	let {
389
	    names      = collectStmtsBinders stmts ;
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	    return_id  = head io_ids ;	-- Rather gruesome

	    io_ty = (\ ty -> mkTyConApp ioTyCon [ty], res_ty) ;

		-- mk_return builds the expression
		--	returnIO @ [()] [coerce () x, ..,  coerce () z]
	    mk_return ids = HsApp (TyApp (HsVar return_id) [mkListTy unitTy]) 
			          (ExplicitList unitTy (map mk_item ids)) ;

	    mk_item id = HsApp (TyApp (HsVar unsafeCoerceId) [idType id, unitTy])
		    	       (HsVar id) } ;

	-- OK, we're ready to typecheck the stmts
	traceTc (text "tcs 2") ;
	((ids, tc_stmts), lie) <- 
405
		getLIE $ tcStmtsAndThen combine DoExpr io_ty stmts $ 
406 407 408 409 410 411 412 413 414 415
		do {
		    -- Look up the names right in the middle,
		    -- where they will all be in scope
		    ids <- mappM tcLookupId names ;
		    return (ids, [ResultStmt (mk_return ids) noSrcLoc])
		} ;

	-- Simplify the context right here, so that we fail
	-- if there aren't enough instances.  Notably, when we see
	--		e
416
	-- we use recoverTc_ to try	it <- e
417 418 419 420 421 422 423 424 425 426
	-- and then			let it = e
	-- It's the simplify step that rejects the first.
	traceTc (text "tcs 3") ;
	const_binds <- tcSimplifyTop lie ;

	-- Build result expression and zonk it
	let { expr = mkHsLet const_binds $
		     HsDo DoExpr tc_stmts io_ids
		 	  (mkTyConApp ioTyCon [mkListTy unitTy]) noSrcLoc } ;
	zonked_expr <- zonkTopExpr expr ;
427
	zonked_ids  <- zonkTopBndrs ids ;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

	return (zonked_ids, zonked_expr)
	}
  where
    combine stmt (ids, stmts) = (ids, stmt:stmts)
\end{code}


tcRnExpr just finds the type of an expression

\begin{code}
tcRnExpr :: HscEnv -> PersistentCompilerState
	 -> InteractiveContext
	 -> RdrNameHsExpr
	 -> IO (PersistentCompilerState, Maybe Type)
tcRnExpr hsc_env pcs ictxt rdr_expr
  = initTc hsc_env pcs iNTERACTIVE $ 
    setInteractiveContext ictxt $ do {

    (rn_expr, fvs) <- initRnInteractive ictxt (rnExpr rdr_expr) ;
    failIfErrsM ;

	-- Suck in the supporting declarations and typecheck them
    tcg_env <- importSupportingDecls (fvs `plusFV` ubiquitousNames) ;
    setGblEnv tcg_env $ do {
    
	-- Now typecheck the expression; 
	-- it might have a rank-2 type (e.g. :t runST)
456
    ((tc_expr, res_ty), lie)	   <- getLIE (tcInferRho rn_expr) ;
457 458 459 460 461 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
    ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
    tcSimplifyTop lie_top ;

    let { all_expr_ty = mkForAllTys qtvs 		$
    		        mkFunTys (map idType dict_ids)	$
    		        res_ty } ;
    zonkTcType all_expr_ty
    }}
  where
    smpl_doc = ptext SLIT("main expression")
\end{code}


\begin{code}
tcRnThing :: HscEnv -> PersistentCompilerState
	  -> InteractiveContext
	  -> RdrName
	  -> IO (PersistentCompilerState, Maybe [TyThing])
-- Look up a RdrName and return all the TyThings it might be
-- We treat a capitalised RdrName as both a data constructor 
-- and as a type or class constructor; hence we return up to two results
tcRnThing hsc_env pcs ictxt rdr_name
  = initTc hsc_env pcs iNTERACTIVE $ 
    setInteractiveContext ictxt $ do {

	-- If the identifier is a constructor (begins with an
	-- upper-case letter), then we need to consider both
	-- constructor and type class identifiers.
    let { rdr_names = dataTcOccs rdr_name } ;

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
	-- results :: [(Messages, Maybe Name)]
    results <- initRnInteractive ictxt
			    (mapM (tryTc . lookupOccRn) rdr_names) ;

	-- The successful lookups will be (Just name)
    let { (warns_s, good_names) = unzip [ (msgs, name) 
					| (msgs, Just name) <- results] ;
	  errs_s = [msgs | (msgs, Nothing) <- results] } ;

	-- Fail if nothing good happened, else add warnings
    if null good_names then	-- Fail
	do { addMessages (head errs_s) ; failM }
      else 			-- Add deprecation warnings
	mapM_ addMessages warns_s ;
	
502
	-- Slurp in the supporting declarations
503
    tcg_env <- importSupportingDecls (mkFVs good_names) ;
504 505 506
    setGblEnv tcg_env $ do {

	-- And lookup up the entities
507 508
    mapM tcLookupGlobal good_names
    }}
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
\end{code}


\begin{code}
setInteractiveContext :: InteractiveContext -> TcRn m a -> TcRn m a
setInteractiveContext icxt thing_inside 
  = traceTc (text "setIC" <+> ppr (ic_type_env icxt))	`thenM_`
    updGblEnv (\ env -> env { tcg_rdr_env  = ic_rn_gbl_env icxt,
			      tcg_type_env = ic_type_env   icxt })
	      thing_inside

initRnInteractive :: InteractiveContext -> RnM a -> TcM a
-- Set the local RdrEnv from the interactive context
initRnInteractive ictxt rn_thing
  = initRn CmdLineMode $
    setLocalRdrEnv (ic_rn_local_env ictxt) $
    rn_thing
\end{code}

%************************************************************************
%*									*
	Type-checking external-core modules
%*									*
%************************************************************************

\begin{code}
tcRnExtCore :: HscEnv -> PersistentCompilerState 
	    -> RdrNameHsModule 
	    -> IO (PersistentCompilerState, Maybe ModGuts)
	-- Nothing => some error occurred 

540 541
tcRnExtCore hsc_env pcs (HsModule (Just this_mod) _ _ decls _ loc)
	-- For external core, the module name is syntactically reqd
542 543 544 545 546 547 548 549 550
	-- Rename the (Core) module.  It's a bit like an interface
	-- file: all names are original names
 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;

   initTc hsc_env pcs this_mod $ addSrcLoc loc $ do {

	-- Rename the source, only in interface mode.
	-- rnSrcDecls handles fixity decls etc too, which won't occur
	-- but that doesn't matter
551 552
   let { local_group = mkGroup decls } ;
   (_, rn_decls, dus) <- initRn (InterfaceMode this_mod) 
553
				      (rnSrcDecls local_group) ;
554 555
   failIfErrsM ;

556
 	-- Get the supporting decls
557
   rn_imp_decls <- slurpImpDecls (duUses dus) ;
558
   let { rn_decls = rn_decls `addImpDecls` rn_imp_decls } ;
559 560 561 562 563 564 565 566

	-- Dump trace of renaming part
   rnDump (ppr rn_decls) ;
   rnStats rn_imp_decls ;

	-- Typecheck them all together so that
	-- any mutually recursive types are done right
   tcg_env <- typecheckIfaceDecls rn_decls ;
567 568 569
   setGblEnv tcg_env $ do {
   
	-- Now the core bindings
570
   core_prs <- tcCoreBinds (hs_coreds rn_decls) ;
571 572 573 574 575 576 577 578 579 580 581
   tcExtendGlobalValEnv (map fst core_prs) $ do {
   
	-- Wrap up
   let {
	bndrs 	   = map fst core_prs ;
	my_exports = map (Avail . idName) bndrs ;
		-- ToDo: export the data types also?

	final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;

	mod_guts = ModGuts {	mg_module   = this_mod,
582 583
				mg_usages   = [],		-- ToDo: compute usage
				mg_dir_imps = [],		-- ??
584
				mg_deps     = noDependencies,	-- ??
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
				mg_exports  = my_exports,
				mg_types    = final_type_env,
				mg_insts    = tcg_insts tcg_env,
				mg_rules    = hsCoreRules (tcg_rules tcg_env),
				mg_binds    = [Rec core_prs],

				-- Stubs
				mg_rdr_env  = emptyGlobalRdrEnv,
				mg_fix_env  = emptyFixityEnv,
				mg_deprecs  = NoDeprecs,
				mg_foreign  = NoStubs
		    } } ;

   tcCoreDump mod_guts ;

   return mod_guts
   }}}}
\end{code}


%************************************************************************
%*									*
	Type-checking the top level of a module
%*									*
%************************************************************************

611
\begin{code}
612
tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, DefUses)
613
	-- Returns the variables free in the decls
614
	-- Reason: solely to report unused imports and bindings
615 616
tcRnSrcDecls decls
 = do { 	-- Do all the declarations
617
	((tc_envs, dus), lie) <- getLIE (tc_rn_src_decls decls) ;
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

	     -- tcSimplifyTop deals with constant or ambiguous InstIds.  
	     -- How could there be ambiguous ones?  They can only arise if a
	     -- top-level decl falls under the monomorphism
	     -- restriction, and no subsequent decl instantiates its
	     -- type.  (Usually, ambiguous type variables are resolved
	     -- during the generalisation step.)
        traceTc (text "Tc8") ;
	setEnvs tc_envs		$ do {
		-- Setting the global env exposes the instances to tcSimplifyTop
		-- Setting the local env exposes the local Ids, so that
		-- we get better error messages (monomorphism restriction)
	inst_binds <- tcSimplifyTop lie ;

	    -- Backsubstitution.  This must be done last.
	    -- Even tcSimplifyTop may do some unification.
        traceTc (text "Tc9") ;
	let { (tcg_env, _) = tc_envs ;
	      TcGblEnv { tcg_type_env = type_env, tcg_binds = binds, 
		         tcg_rules = rules, tcg_fords = fords } = tcg_env } ;

	(bind_ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
							   rules fords ;

	return (tcg_env { tcg_type_env = extendTypeEnvWithIds type_env bind_ids,
			  tcg_binds = binds', tcg_rules = rules', tcg_fords = fords' }, 
644
		dus)
645 646
    }}

647
tc_rn_src_decls :: [RdrNameHsDecl] -> TcM ((TcGblEnv, TcLclEnv), DefUses)
648 649

tc_rn_src_decls ds
650
 = do { let { (first_group, group_tail) = findSplice ds } ;
651
		-- If ds is [] we get ([], Nothing)
652

653
	-- Type check the decls up to, but not including, the first splice
654
	(tc_envs@(_,tcl_env), src_dus1) <- tcRnGroup first_group ;
655

656 657 658 659
	-- Bale out if errors; for example, error recovery when checking
	-- the RHS of 'main' can mean that 'main' is not in the envt for 
	-- the subsequent checkMain test
	failIfErrsM ;
660

661 662
	setEnvs tc_envs $

663
	-- If there is no splice, we're nearly done
664
	case group_tail of {
665 666
	   Nothing -> do { 	-- Last thing: check for `main'
			   (tcg_env, main_fvs) <- checkMain ;
667 668
			   return ((tcg_env, tcl_env), 
				    src_dus1 `plusDU` usesOnly main_fvs)
669 670 671
		      } ;

	-- If there's a splice, we must carry on
672
	   Just (SpliceDecl splice_expr splice_loc, rest_ds) -> do {
673 674 675
#ifndef GHCI
	failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
#else
676

677
	-- Rename the splice expression, and get its supporting decls
678 679 680 681
	(rn_splice_expr, splice_fvs) <- initRn SourceMode $
				 	addSrcLoc splice_loc $
				 	rnExpr splice_expr ;
	tcg_env <- importSupportingDecls (splice_fvs `plusFV` templateHaskellNames) ;
682 683 684 685 686 687
	setGblEnv tcg_env $ do {

	-- Execute the splice
	spliced_decls <- tcSpliceDecls rn_splice_expr ;

	-- Glue them on the front of the remaining decls and loop
688
	(tc_envs, src_dus2) <- tc_rn_src_decls (spliced_decls ++ rest_ds) ;
689

690
	return (tc_envs, src_dus1 `plusDU` usesOnly splice_fvs `plusDU` src_dus2)
691
    }
692
#endif /* GHCI */
693
    }}}
694
\end{code}
695 696 697 698 699 700 701 702


%************************************************************************
%*									*
	Type-checking the top level of a module
%*									*
%************************************************************************

703
tcRnGroup takes a bunch of top-level source-code declarations, and
704 705 706 707 708 709 710 711 712 713 714
 * renames them
 * gets supporting declarations from interface files
 * typechecks them
 * zonks them
 * and augments the TcGblEnv with the results

In Template Haskell it may be called repeatedly for each group of
declarations.  It expects there to be an incoming TcGblEnv in the
monad; it augments it and returns the new TcGblEnv.

\begin{code}
715
tcRnGroup :: HsGroup RdrName -> TcM ((TcGblEnv, TcLclEnv), DefUses)
716
	-- Returns the variables free in the decls, for unused-binding reporting
717
tcRnGroup decls
718
 = do {		-- Rename the declarations
719
	(tcg_env, rn_decls, src_dus) <- rnTopSrcDecls decls ;
720 721 722
	setGblEnv tcg_env $ do {

		-- Typecheck the declarations
723
	tc_envs <- tcTopSrcDecls rn_decls ;
724

725
	return (tc_envs, src_dus)
726 727 728
  }}

------------------------------------------------
729
rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name, DefUses)
730 731 732 733 734 735 736 737 738
rnTopSrcDecls group
 = do { 	-- Bring top level binders into scope
	(rdr_env, imports) <- importsFromLocalDecls group ;
	updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv`
						  tcg_rdr_env gbl,
				 tcg_imports = imports `plusImportAvails` 
						  tcg_imports gbl }) 
		     $ do {

739 740
	failIfErrsM ;	-- No point in continuing if (say) we have duplicate declarations

741
		-- Rename the source decls
742
	(tcg_env, rn_src_decls, src_dus) <- initRn SourceMode (rnSrcDecls group) ;
743 744 745 746 747
	setGblEnv tcg_env $ do {

	failIfErrsM ;

		-- Import consquential imports
748
	let { src_fvs = duUses src_dus } ;
749
	rn_imp_decls <- slurpImpDecls (src_fvs `plusFV` implicitModuleFVs src_fvs) ;
750
	let { rn_decls = rn_src_decls `addImpDecls` rn_imp_decls } ;
751 752

		-- Dump trace of renaming part
753
	rnDump (ppr rn_decls) ;
754 755
	rnStats rn_imp_decls ;

756
	return (tcg_env, rn_decls, src_dus)
757
  }}}
758 759

------------------------------------------------
760 761
tcTopSrcDecls :: HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
tcTopSrcDecls
762 763 764 765 766 767
	(HsGroup { hs_tyclds = tycl_decls, 
		   hs_instds = inst_decls,
		   hs_fords  = foreign_decls,
		   hs_defds  = default_decls,
		   hs_ruleds = rule_decls,
		   hs_valds  = val_binds })
768
 = do {		-- Type-check the type and class decls, and all imported decls
769
		-- The latter come in via tycl_decls
770
        traceTc (text "Tc2") ;
771
	tcg_env <- tcTyClDecls tycl_decls ;
772 773 774 775 776 777 778 779 780 781 782 783 784
	setGblEnv tcg_env	$ do {

		-- Source-language instances, including derivings,
		-- and import the supporting declarations
        traceTc (text "Tc3") ;
	(tcg_env, inst_infos, deriv_binds, fvs) <- tcInstDecls1 tycl_decls inst_decls ;
	setGblEnv tcg_env	$ do {
	tcg_env <- importSupportingDecls fvs ;
	setGblEnv tcg_env	$ do {

	        -- Foreign import declarations next.  No zonking necessary
		-- here; we can tuck them straight into the global environment.
        traceTc (text "Tc4") ;
785
	(fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
786 787 788 789 790 791
	tcExtendGlobalValEnv fi_ids		     $
	updGblEnv (\gbl -> gbl { tcg_fords = tcg_fords gbl ++ fi_decls }) 
		  $ do {

		-- Default declarations
        traceTc (text "Tc4a") ;
792
	default_tys <- tcDefaults default_decls ;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
	
		-- Value declarations next
		-- We also typecheck any extra binds that came out 
		-- of the "deriving" process
        traceTc (text "Tc5") ;
	(tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
	setLclTypeEnv lcl_env 	$ do {

	     	-- Second pass over class and instance declarations, 
		-- plus rules and foreign exports, to generate bindings
        traceTc (text "Tc6") ;
	(cls_dm_binds, dm_ids) <- tcClassDecls2 tycl_decls ;
	tcExtendGlobalValEnv dm_ids	$ do {
	inst_binds <- tcInstDecls2 inst_infos ;
808
	showLIE (text "after instDecls2") ;
809 810 811 812

		-- Foreign exports
		-- They need to be zonked, so we return them
        traceTc (text "Tc7") ;
813
	(foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828

		-- Rules
		-- Need to partition them because the source rules
		-- must be zonked before adding them to tcg_rules
		-- NB: built-in rules come in as IfaceRuleOut's, and
		--     get added to tcg_rules right here by tcExtendRules
	rules <- tcRules rule_decls ;
	let { (src_rules, iface_rules) = partition isSrcRule rules } ;
	tcExtendRules iface_rules $ do {

		-- Wrap up
	tcg_env <- getGblEnv ;
	let { all_binds = tc_val_binds	 `AndMonoBinds`
			  inst_binds	 `AndMonoBinds`
			  cls_dm_binds	 `AndMonoBinds`
829
			  foe_binds  ;
830

831 832 833 834 835 836 837
		-- Extend the GblEnv with the (as yet un-zonked) 
		-- bindings, rules, foreign decls
	      tcg_env' = tcg_env {  tcg_binds = tcg_binds tcg_env `andMonoBinds` all_binds,
				    tcg_rules = tcg_rules tcg_env ++ src_rules,
				    tcg_fords = tcg_fords tcg_env ++ foe_decls } } ;
	
  	return (tcg_env', lcl_env)
838 839 840 841
     }}}}}}}}}
\end{code}

\begin{code}
842
tcTyClDecls :: [RenamedTyClDecl]
843 844 845 846 847 848 849 850 851 852
	    -> TcM TcGblEnv

-- tcTyClDecls deals with 
--	type and class decls (some source, some imported)
--	interface signatures (checked lazily)
--
-- It returns the TcGblEnv for this module, and side-effects the
-- persistent compiler state to reflect the things imported from
-- other modules

853
tcTyClDecls tycl_decls
854 855 856 857 858
  = checkNoErrs $
	-- tcTyAndClassDecls recovers internally, but if anything gave rise to
	-- an error we'd better stop now, to avoid a cascade
	
    traceTc (text "TyCl1")		`thenM_`
859 860 861
    tcTyAndClassDecls tycl_decls	`thenM` \ tcg_env ->
	-- Returns the extended environment
    setGblEnv tcg_env 			$
862 863 864 865 866 867

    traceTc (text "TyCl2")		`thenM_`
    tcInterfaceSigs tycl_decls		`thenM` \ tcg_env ->
	-- Returns the extended environment

    returnM tcg_env
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
\end{code}    



%************************************************************************
%*									*
	Load the old interface file for this module (unless
	we have it aleady), and check whether it is up to date
	
%*									*
%************************************************************************

\begin{code}
checkOldIface :: HscEnv
	      -> PersistentCompilerState
	      -> Module
	      -> FilePath		-- Where the interface file is
	      -> Bool 			-- Source unchanged
	      -> Maybe ModIface 	-- Old interface from compilation manager, if any
	      -> IO (PersistentCompilerState, Maybe (RecompileRequired, Maybe ModIface))
				-- Nothing <=> errors happened

checkOldIface hsc_env pcs mod iface_path source_unchanged maybe_iface
  = do { showPass (hsc_dflags hsc_env) 
	          ("Checking old interface for " ++ moduleUserString mod) ;

	 initTc hsc_env pcs mod
		(check_old_iface iface_path source_unchanged maybe_iface)
     }

check_old_iface iface_path source_unchanged maybe_iface
 = 	-- CHECK WHETHER THE SOURCE HAS CHANGED
    ifM (not source_unchanged)
	(traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
					      	`thenM_`

     -- If the source has changed and we're in interactive mode, avoid reading
     -- an interface; just return the one we might have been supplied with.
    getGhciMode					`thenM` \ ghci_mode ->
    if (ghci_mode == Interactive) && not source_unchanged then
         returnM (outOfDate, maybe_iface)
    else

911
    case maybe_iface of {
912 913 914 915
       Just old_iface -> -- Use the one we already have
                         checkVersions source_unchanged old_iface	`thenM` \ recomp ->
			 returnM (recomp, Just old_iface)

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 944 945 946 947 948
    ;  Nothing ->

	-- Try and read the old interface for the current module
	-- from the .hi file left from the last time we compiled it
    getModule					`thenM` \ this_mod ->
    readIface this_mod iface_path False	`thenM` \ read_result ->
    case read_result of {
       Left err ->	-- Old interface file not found, or garbled; give up
		   traceHiDiffs (text "FYI: cannot read old interface file:"
			   	 $$ nest 4 (text (showException err))) 	`thenM_`
	           returnM (outOfDate, Nothing)

    ;  Right parsed_iface ->	

	-- We found the file and parsed it; now load it
    tryTc (initRn (InterfaceMode this_mod)
		  (loadOldIface parsed_iface))	`thenM` \ ((_,errs), mb_iface) ->
    case mb_iface of {
	Nothing ->	-- Something went wrong in loading.  The main likely thing
			-- is that the usages mentioned B.f, where B.hi and B.hs no
			-- longer exist.  Then newGlobalName2 fails with an error message
			-- This isn't an error; we just don't have an old iface file to
			-- look at.  Spit out a traceHiDiffs for info though.
		   traceHiDiffs (text "FYI: loading old interface file failed"
				   $$ nest 4 (docToSDoc (pprBagOfErrors errs)))	`thenM_`
		   return (outOfDate, Nothing)

    ;	Just iface -> 

	-- At last, we have got the old iface; check its versions
    checkVersions source_unchanged iface	`thenM` \ recomp ->
    returnM (recomp, Just iface)
    }}}
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
\end{code}


%************************************************************************
%*									*
	Type-check and rename supporting declarations
	This is used to deal with the free vars of a splice,
	or derived code: slurp in the necessary declarations,
	typecheck them, and add them to the EPS
%*									*
%************************************************************************

\begin{code}
importSupportingDecls :: FreeVars -> TcM TcGblEnv
-- Completely deal with the supporting imports needed
-- by the specified free-var set
importSupportingDecls fvs
 = do { traceRn (text "Import supporting decls for" <+> ppr (nameSetToList fvs)) ;
	decls <- slurpImpDecls fvs ;
	traceRn (text "...namely:" <+> vcat (map ppr decls)) ;
969
	typecheckIfaceDecls (mkGroup decls) }
970

971
typecheckIfaceDecls :: HsGroup Name -> TcM TcGblEnv
972 973 974 975 976 977 978
  -- The decls are all interface-file declarations
  -- Usually they are all from other modules, but when we are reading
  -- this module's interface from a file, it's possible that some of
  -- them are for the module being compiled.
  -- That is why the tcExtendX functions need to do partitioning.
  --
  -- If all the decls are from other modules, the returned TcGblEnv
979 980
  -- will have an empty tc_genv, but its tc_inst_env
  -- cache may have been augmented.
981 982 983 984
typecheckIfaceDecls (HsGroup { hs_tyclds = tycl_decls,
			       hs_instds = inst_decls,
			       hs_ruleds = rule_decls })
 = do {		-- Typecheck the type, class, and interface-sig decls
985
	tcg_env <- tcTyClDecls tycl_decls ;
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 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
	setGblEnv tcg_env		$ do {
	
    	-- Typecheck the instance decls, and rules
	-- Note that imported dictionary functions are already
	-- in scope from the preceding tcTyClDecls
	tcIfaceInstDecls inst_decls	`thenM` \ dfuns ->
	tcExtendInstEnv dfuns		$
	tcRules rule_decls		`thenM` \ rules ->
	tcExtendRules rules		$
    
	getGblEnv		-- Return the environment
   }}
\end{code}



%*********************************************************
%*						 	 *
	mkGlobalContext: make up an interactive context

	Used for initialising the lexical environment
	of the interactive read-eval-print loop
%*							 *
%*********************************************************

\begin{code}
#ifdef GHCI
mkGlobalContext
	:: HscEnv -> PersistentCompilerState
	-> [Module] 	-- Expose these modules' top-level scope
	-> [Module]	-- Expose these modules' exports only
        -> IO (PersistentCompilerState, Maybe GlobalRdrEnv)

mkGlobalContext hsc_env pcs toplevs exports
  = initTc hsc_env pcs iNTERACTIVE $ do {

    toplev_envs <- mappM getTopLevScope   toplevs ;
    export_envs <- mappM getModuleExports exports ;
    returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv
		   (toplev_envs ++ export_envs))
    }

getTopLevScope :: Module -> TcRn m GlobalRdrEnv
getTopLevScope mod
  = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
 	 case mi_globals iface of
		Nothing  -> panic "getTopLevScope"
		Just env -> returnM env }

getModuleExports :: Module -> TcRn m GlobalRdrEnv
getModuleExports mod 
  = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
         returnM (foldl add emptyGlobalRdrEnv (mi_exports iface)) }
  where
    prov_fn n = NonLocalDef ImplicitImport
    add env (mod,avails)
	= plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)

contextDoc = text "context for compiling statements"
\end{code}

\begin{code}
getModuleContents
  :: HscEnv
  -> PersistentCompilerState    -- IN: persistent compiler state
  -> Module			-- module to inspect
  -> Bool			-- grab just the exports, or the whole toplev
  -> IO (PersistentCompilerState, Maybe [TyThing])

getModuleContents hsc_env pcs mod exports_only
 = initTc hsc_env pcs iNTERACTIVE $ do {   

	-- Load the interface if necessary (a home module will certainly
	-- alraedy be loaded, but a package module might not be)
	iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;

        let { export_names = availsToNameSet export_avails ;
	      export_avails = [ avail | (mn, avails) <- mi_exports iface, 
		  	                avail <- avails ] } ;

	all_names <- if exports_only then 
			return export_names
		     else case mi_globals iface of {
			   Just rdr_env -> 
				return (get_locals rdr_env) ;

			   Nothing -> do { addErr (noRdrEnvErr mod) ;
					   return export_names } } ;
	   			-- Invariant; we only have (not exports_only) 
				-- for a home module so it must already be in the HIT
				-- So the Nothing case is a bug

	env <- importSupportingDecls all_names ;
	setGblEnv env (mappM tcLookupGlobal (nameSetToList all_names))
    }
  where
	-- Grab all the things from the global env that are locally def'd
    get_locals rdr_env = mkNameSet [ gre_name gre
				   | elts <- rdrEnvElts rdr_env, 
				     gre <- elts, 
				     isLocalGRE gre ]
	-- Make a set because a name is often in the envt in
	-- both qualified and unqualified forms

noRdrEnvErr mod = ptext SLIT("No top-level environment available for module") 
		  <+> quotes (ppr mod)
#endif
\end{code}

%************************************************************************
%*									*
	Checking for 'main'
%*									*
%************************************************************************

\begin{code}
checkMain 
  = do { ghci_mode <- getGhciMode ;
	 tcg_env   <- getGblEnv ;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

	 mb_main_mod <- readMutVar v_MainModIs ;
	 mb_main_fn  <- readMutVar v_MainFunIs ;
	 let { main_mod = case mb_main_mod of {
				Just mod -> mkModuleName mod ;
				Nothing  -> mAIN_Name } ;
	        main_fn  = case mb_main_fn of {
				Just fn -> mkRdrUnqual (mkVarOcc (mkFastString fn)) ;
				Nothing -> main_RDR_Unqual } } ;
	
	 check_main ghci_mode tcg_env main_mod main_fn
1116 1117
    }

1118 1119

check_main ghci_mode tcg_env main_mod main_fn
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
     -- If we are in module Main, check that 'main' is defined.
     -- It may be imported from another module, in which case 
     -- we have to drag in its.
     -- 
     -- Also form the definition
     --		$main = runIO main
     -- so we need to slurp in runIO too.
     --
     -- ToDo: We have to return the main_name separately, because it's a
     -- bona fide 'use', and should be recorded as such, but the others
     -- aren't 
     -- 
     -- Blimey: a whole page of code to do this...

1134
 | mod_name /= main_mod
1135 1136
 = return (tcg_env, emptyFVs)

1137 1138 1139 1140 1141
	-- Check that 'main' is in scope
	-- It might be imported from another module!
	-- 
	-- We use a guard for this (rather than letting lookupSrcName fail)
	-- because it's not an error in ghci)
1142
 | not (main_fn `elemRdrEnv` rdr_env)
1143 1144
 = do { complain_no_main; return (tcg_env, emptyFVs) }

1145 1146 1147
 | otherwise	-- OK, so the appropriate 'main' is in scope
		-- 
 = do { main_name <- lookupSrcName main_fn ;
1148 1149

	tcg_env <- importSupportingDecls (unitFV runIOName) ;
1150 1151 1152 1153

	addSrcLoc (getSrcLoc main_name)	$
	addErrCtxt mainCtxt		$
	setGblEnv tcg_env 		$ do {
1154 1155 1156
	
	-- $main :: IO () = runIO main
	let { rhs = HsApp (HsVar runIOName) (HsVar main_name) } ;
1157
	(main_expr, ty) <- tcInferRho rhs ;
1158

1159 1160 1161 1162
	let { dollar_main_id = setIdLocalExported (mkLocalId dollarMainName ty) ;
	      main_bind      = VarMonoBind dollar_main_id main_expr ;
	      tcg_env' 	     = tcg_env { tcg_binds = tcg_binds tcg_env 
						     `andMonoBinds` main_bind } } ;
1163 1164 1165 1166 1167 1168 1169 1170

	return (tcg_env', unitFV main_name)
    }}
  where
    mod_name = moduleName (tcg_mod tcg_env) 
    rdr_env  = tcg_rdr_env tcg_env
 
    complain_no_main | ghci_mode == Interactive = return ()
1171
		     | otherwise 		= failWithTc noMainMsg
1172
	-- In interactive mode, don't worry about the absence of 'main'
1173 1174
	-- In other modes, fail altogether, so that we don't go on
	-- and complain a second time when processing the export list.
1175

1176 1177 1178
    mainCtxt  = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
    noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn) 
		<+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
\end{code}


%************************************************************************
%*									*
		Degugging output
%*									*
%************************************************************************

\begin{code}
rnDump :: SDoc -> TcRn m ()
-- Dump, with a banner, if -ddump-rn
rnDump doc = dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc)

tcDump :: TcGblEnv -> TcRn m ()
tcDump env
 = do { dflags <- getDOpts ;

	-- Dump short output if -ddump-types or -ddump-tc
	ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
	    (dumpTcRn short_dump) ;

	-- Dump bindings if -ddump-tc
	dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
   }
  where
    short_dump = pprTcGblEnv env
    full_dump  = ppr (tcg_binds env)
	-- NB: foreign x-d's have undefined's in their types; 
	--     hence can't show the tc_fords

tcCoreDump mod_guts
 = do { dflags <- getDOpts ;
	ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
 	    (dumpTcRn (pprModGuts mod_guts)) ;

	-- Dump bindings if -ddump-tc
	dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
  where
    full_dump = pprCoreBindings (mg_binds mod_guts)

-- It's unpleasant having both pprModGuts and pprModDetails here
pprTcGblEnv :: TcGblEnv -> SDoc
pprTcGblEnv (TcGblEnv { tcg_type_env = type_env, 
		        tcg_insts    = dfun_ids, 
1224 1225
		        tcg_rules    = rules,
			tcg_imports  = imports })
1226 1227 1228
  = vcat [ ppr_types dfun_ids type_env
	 , ppr_insts dfun_ids
	 , vcat (map ppr rules)
1229
	 , ppr_gen_tycons (typeEnvTyCons type_env)
1230 1231
	 , ptext SLIT("Dependent modules:") <+> ppr (moduleEnvElts (imp_dep_mods imports))
	 , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263

pprModGuts :: ModGuts -> SDoc
pprModGuts (ModGuts { mg_types = type_env,
		      mg_rules = rules })
  = vcat [ ppr_types [] type_env,
	   ppr_rules rules ]


ppr_types :: [Var] -> TypeEnv -> SDoc
ppr_types dfun_ids type_env
  = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
  where
    ids = [id | id <- typeEnvIds type_env, want_sig id]
    want_sig id | opt_PprStyle_Debug = True
	        | otherwise	     = isLocalId id && 
				       isExternalName (idName id) && 
				       not (id `elem` dfun_ids)
	-- isLocalId ignores data constructors, records selectors etc.
	-- The isExternalName ignores local dictionary and method bindings
	-- that the type checker has invented.  Top-level user-defined things 
	-- have External names.

ppr_insts :: [Var] -> SDoc
ppr_insts []       = empty
ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)

ppr_sigs :: [Var] -> SDoc
ppr_sigs ids
	-- Print type signatures
   	-- Convert to HsType so that we get source-language style printing
	-- And sort by RdrName
  = vcat $ map ppr_sig $ sortLt lt_sig $
1264
    [ (getRdrName id, toHsType (tidyTopType (idType id)))
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    | id <- ids ]
  where
    lt_sig (n1,_) (n2,_) = n1 < n2
    ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t


ppr_rules :: [IdCoreRule] -> SDoc
ppr_rules [] = empty
ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
		      nest 4 (pprIdRules rs),
		      ptext SLIT("#-}")]

ppr_gen_tycons []  = empty
1278 1279
ppr_gen_tycons tcs = vcat [ptext SLIT("Generic type constructor details:"),
			   nest 2 (vcat (map ppr_gen_tycon tcs))
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
		     ]

-- x&y are now Id's, not CoreExpr's 
ppr_gen_tycon tycon 
  | Just ep <- tyConGenInfo tycon
  = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)

  | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")

ppr_ep (EP from to)
  = vcat [ ptext SLIT("Rep type:") <+> ppr (tcFunResultTy from_tau),
	   ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
	   ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
    ]
  where
    (_,from_tau) = tcSplitForAllTys (idType from)
\end{code}