RnNames.lhs 56.4 KB
Newer Older
1 2 3 4 5 6 7
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[RnNames]{Extracting imported and top-level names in scope}

\begin{code}
module RnNames (
8 9
	rnImports, getLocalNonValBinders,
	rnExports, extendGlobalRdrEnvRn,
Ian Lynagh's avatar
Ian Lynagh committed
10
	reportUnusedNames, finishWarnings,
11 12 13 14
    ) where

#include "HsVersions.h"

15
import DynFlags
Ian Lynagh's avatar
Ian Lynagh committed
16
import HsSyn
17
import TcEnv		( isBrackStage )
18
import RnEnv
19
import RnHsDoc          ( rnHsDoc )
20
import IfaceEnv		( ifaceExportNames )
21
import LoadIface	( loadSrcInterface, loadSysInterface )
22
import TcRnMonad hiding (LIE)
23

Simon Marlow's avatar
Simon Marlow committed
24 25
import PrelNames
import Module
26
import Name
27
import NameEnv
28
import NameSet
29 30
import HscTypes
import RdrName
31
import Outputable
32
import Maybes
33
import SrcLoc
34 35
import FiniteMap
import ErrUtils
36
import Util
37
import FastString
38
import ListSetOps
39 40
import Data.List        ( partition, (\\), delete )
import qualified Data.Set as Set
41
import IO		( openFile, IOMode(..) )
42
import Monad		( when, mplus )
43 44 45 46 47 48
\end{code}



%************************************************************************
%*									*
49
		rnImports
50 51 52 53
%*									*
%************************************************************************

\begin{code}
54
rnImports :: [LImportDecl RdrName]
55
           -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
56

57
rnImports imports
58 59 60 61 62
         -- PROCESS IMPORT DECLS
         -- Do the non {- SOURCE -} ones first, so that we get a helpful
         -- warning for {- SOURCE -} ones that are unnecessary
    = do this_mod <- getModule
         implicit_prelude <- doptM Opt_ImplicitPrelude
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
63 64
         let prel_imports	= mkPrelImports this_mod implicit_prelude imports
             (source, ordinary) = partition is_source_import imports
65
             is_source_import (L _ (ImportDecl _ _ is_boot _ _ _)) = is_boot
66

67 68 69 70
         ifOptM Opt_WarnImplicitPrelude (
            when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
          )

71
         stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
72
         stuff2 <- mapM (rnImportDecl this_mod) source
73 74
         let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
         return (decls, rdr_env, imp_avails,hpc_usage) 
75

76
    where
77 78 79 80 81
   combine :: [(LImportDecl Name,  GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
           -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
   combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
        where plus (decl,  gbl_env1, imp_avails1,hpc_usage1)
                   (decls, gbl_env2, imp_avails2,hpc_usage2)
82 83
                = (decl:decls, 
                   gbl_env1 `plusGlobalRdrEnv` gbl_env2,
84 85
                   imp_avails1 `plusImportAvails` imp_avails2,
		   hpc_usage1 || hpc_usage2)
86

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100
mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
-- Consruct the implicit declaration "import Prelude" (or not)
--
-- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
-- because the former doesn't even look at Prelude.hi for instance 
-- declarations, whereas the latter does.
mkPrelImports this_mod implicit_prelude import_decls
  | this_mod == pRELUDE
   || explicit_prelude_import
   || not implicit_prelude
  = []
  | otherwise = [preludeImportDecl]
  where
      explicit_prelude_import
101
       = notNull [ () | L _ (ImportDecl mod Nothing _ _ _ _) <- import_decls, 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
102 103 104 105 106 107
	           unLoc mod == pRELUDE_NAME ]

      preludeImportDecl :: LImportDecl RdrName
      preludeImportDecl
        = L loc $
	  ImportDecl (L loc pRELUDE_NAME)
108
               Nothing {- no specific package -}
109 110 111 112
	       False {- Not a boot interface -}
	       False	{- Not qualified -}
	       Nothing	{- No "as" -}
	       Nothing	{- No import list -}
113

Ian Lynagh's avatar
Ian Lynagh committed
114
      loc = mkGeneralSrcSpan (fsLit "Implicit import declaration")         
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
115

116

117 118
rnImportDecl  :: Module
	      -> LImportDecl RdrName
119
	      -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
120

121
rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
122
                                         qual_only as_mod imp_details))
123
  = setSrcSpan loc $ do
124

125 126 127 128
    when (isJust mb_pkg) $ do
        pkg_imports <- doptM Opt_PackageImports
        when (not pkg_imports) $ addErr packageImportErr

129 130
	-- If there's an error in loadInterface, (e.g. interface
	-- file not found) we get lots of spurious errors from 'filterImports'
131
    let
132
	imp_mod_name = unLoc loc_imp_mod_name
Ian Lynagh's avatar
Ian Lynagh committed
133
	doc = ppr imp_mod_name <+> ptext (sLit "is directly imported")
134

135
    iface <- loadSrcInterface doc imp_mod_name want_boot mb_pkg
136

137 138
	-- Compiler sanity check: if the import didn't say
	-- {-# SOURCE #-} we should not get a hi-boot file
139
    WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
140

141 142
	-- Issue a user warning for a redundant {- SOURCE -} import
	-- NB that we arrange to read all the ordinary imports before 
Ian Lynagh's avatar
Ian Lynagh committed
143 144 145 146 147 148 149 150
	-- any of the {- SOURCE -} imports.
        --
        -- in --make and GHCi, the compilation manager checks for this,
        -- and indeed we shouldn't do it here because the existence of
        -- the non-boot module depends on the compilation order, which
        -- is not deterministic.  The hs-boot test can show this up.
    dflags <- getDOpts
    warnIf (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags))
151
	   (warnRedundantSourceImport imp_mod_name)
152

153
    let
154
	imp_mod	   = mi_module iface
Ian Lynagh's avatar
Ian Lynagh committed
155
	warns	   = mi_warns iface
156
	orph_iface = mi_orphan iface 
157 158
	has_finsts = mi_finsts iface 
	deps 	   = mi_deps iface
159 160

	filtered_exports = filter not_this_mod (mi_exports iface)
161
	not_this_mod (mod,_) = mod /= this_mod
162 163 164 165 166 167 168
	-- If the module exports anything defined in this module, just
	-- ignore it.  Reason: otherwise it looks as if there are two
	-- local definition sites for the thing, and an error gets
	-- reported.  Easiest thing is just to filter them out up
	-- front. This situation only arises if a module imports
	-- itself, or another module that imported it.  (Necessarily,
	-- this invoves a loop.)
169 170 171 172 173 174 175 176 177 178
	--
	-- Tiresome consequence: if you say
	--	module A where
	--	   import B( AType )
	--	   type AType = ...
	--
	--	module B( AType ) where
	--	   import {-# SOURCE #-} A( AType )
	--
	-- then you'll get a 'B does not export AType' message.  Oh well.
179 180 181 182

	qual_mod_name = case as_mod of
			  Nothing  	    -> imp_mod_name
			  Just another_name -> another_name
183 184
	imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
		  		  is_dloc = loc, is_as = qual_mod_name }
185 186 187 188 189 190
    -- in

	-- Get the total exports from this module
    total_avails <- ifaceExportNames filtered_exports

        -- filter the imports according to the import declaration
191
    (new_imp_details, gbl_env) <- 
192
        filterImports iface imp_spec imp_details total_avails
193

194
    dflags <- getDOpts
195

196
    let
197
	-- Compute new transitive dependencies
198

199 200 201
 	orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
			       imp_mod : dep_orphs deps
		| otherwise  = dep_orphs deps
202

203 204 205 206
 	finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
			      imp_mod : dep_finsts deps
		| otherwise = dep_finsts deps

Simon Marlow's avatar
Simon Marlow committed
207 208
	pkg = modulePackageId (mi_module iface)

209
	(dependent_mods, dependent_pkgs) 
Simon Marlow's avatar
Simon Marlow committed
210
	   | pkg == thisPackage dflags =
211
	    	-- Imported module is from the home package
212
		-- Take its dependent modules and add imp_mod itself
213
		-- Take its dependent packages unchanged
214 215 216 217 218 219 220 221 222 223
		--
		-- NB: (dep_mods deps) might include a hi-boot file
		-- for the module being compiled, CM. Do *not* filter
		-- this out (as we used to), because when we've
		-- finished dealing with the direct imports we want to
		-- know if any of them depended on CM.hi-boot, in
		-- which case we should do the hi-boot consistency
		-- check.  See LoadIface.loadHiBootInterface
		  ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)

Simon Marlow's avatar
Simon Marlow committed
224
	   | otherwise =
225
 	   	-- Imported module is from another package
226
		-- Dump the dependent modules
227
		-- Add the package imp_mod comes from to the dependent packages
228 229
	         ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
	         ([], pkg : dep_pkgs deps)
230

231
	-- True <=> import M ()
232
	import_all = case imp_details of
233
			Just (is_hiding, ls) -> not is_hiding && null ls	
Ian Lynagh's avatar
Ian Lynagh committed
234
			_ 		     -> False
235

236
	imports   = ImportAvails { 
237
			imp_mods     = unitModuleEnv imp_mod [(qual_mod_name, import_all, loc)],
238
			imp_orphs    = orphans,
239
			imp_finsts   = finsts,
240
			imp_dep_mods = mkModDeps dependent_mods,
241
			imp_dep_pkgs = dependent_pkgs
242 243
                   }

244
	-- Complain if we import a deprecated module
Ian Lynagh's avatar
Ian Lynagh committed
245 246 247 248
    ifOptM Opt_WarnWarningsDeprecations	(
       case warns of	
	  WarnAll txt -> addWarn (moduleWarn imp_mod_name txt)
	  _    	      -> return ()
249 250
     )

251
    let new_imp_decl = L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
252
                                         qual_only as_mod new_imp_details)
253

254
    return (new_imp_decl, gbl_env, imports, mi_hpc iface)
255
    )
256

Ian Lynagh's avatar
Ian Lynagh committed
257
warnRedundantSourceImport :: ModuleName -> SDoc
258
warnRedundantSourceImport mod_name
Ian Lynagh's avatar
Ian Lynagh committed
259
  = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
260
          <+> quotes (ppr mod_name)
261 262 263
\end{code}


264 265 266 267 268 269 270 271 272 273 274
%************************************************************************
%*									*
		importsFromLocalDecls
%*									*
%************************************************************************

From the top-level declarations of this module produce
  	* the lexical environment
	* the ImportAvails
created by its bindings.  
	
275 276 277 278
Note [Top-level Names in Template Haskell decl quotes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a Template Haskell declaration quotation like this:
      module M where
279
	f x = h [d| f = 3 |]
280 281
When renaming the declarations inside [d| ...|], we treat the
top level binders specially in two ways
282

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
1.  We give them an Internal name, not (as usual) an External one.
    Otherwise the NameCache gets confused by a second allocation of
    M.f.  (We used to invent a fake module ThFake to avoid this, but
    that had other problems, notably in getting the correct answer for
    nameIsLocalOrFrom in lookupFixity. So we now leave tcg_module 
    unaffected.)

2.  We make them *shadow* the outer bindings. If we don't do that,
    we'll get a complaint when extending the GlobalRdrEnv, saying that
    there are two bindings for 'f'.

    This shadowing applies even if the binding for 'f' is in a
    where-clause, and hence is in the *local* RdrEnv not the *global*
    RdrEnv.

We find out whether we are inside a [d| ... |] by testing the TH
stage. This is a slight hack, because the stage field was really meant for
the type checker, and here we are not interested in the fields of Brack,
hence the error thunks in thRnBrack.
302

303
\begin{code}
304
extendGlobalRdrEnvRn :: [AvailInfo]
305 306 307 308
	       	     -> MiniFixityEnv
	       	     -> RnM (TcGblEnv, TcLclEnv)
  -- Updates both the GlobalRdrEnv and the FixityEnv
  -- We return a new TcLclEnv only becuase we might have to
309 310
  -- delete some bindings from it; 
  -- see Note [Top-level Names in Template Haskell decl quotes]
311

312
extendGlobalRdrEnvRn avails new_fixities
313
  = do	{ (gbl_env, lcl_env) <- getEnvs
314
        ; stage <- getStage
315 316 317 318
	; let rdr_env = tcg_rdr_env gbl_env
	      fix_env = tcg_fix_env gbl_env

		-- Delete new_occs from global and local envs
319 320 321 322
		-- If we are in a TemplateHaskell decl bracket, 
		--    we are going to shadow them
		-- See Note [Top-level Names in Template Haskell decl quotes]
	      shadowP  = isBrackStage stage
323 324 325 326 327
	      new_occs = map (nameOccName . gre_name) gres
	      rdr_env1 = hideSomeUnquals rdr_env new_occs
	      lcl_env1 = lcl_env { tcl_rdr = delListFromOccEnv (tcl_rdr lcl_env) new_occs }
	      (rdr_env2, lcl_env2) | shadowP   = (rdr_env1, lcl_env1)
				   | otherwise = (rdr_env,  lcl_env)
328

329 330 331 332 333 334 335
	      rdr_env3 = foldl extendGlobalRdrEnv rdr_env2 gres
	      fix_env' = foldl extend_fix_env     fix_env  gres
	      (rdr_env', dups) = findLocalDupsRdrEnv rdr_env3 new_occs

	      gbl_env' = gbl_env { tcg_rdr_env = rdr_env', tcg_fix_env = fix_env' }
	      
	; mapM_ addDupDeclErr dups
336
	
337
	; traceRn (text "extendGlobalRdrEnvRn" <+> (ppr new_fixities $$ ppr fix_env $$ ppr fix_env'))
338 339 340
	; return (gbl_env', lcl_env2) }
  where
    gres = gresFromAvails LocalDef avails
341

342
     	--  If there is a fixity decl for the gre, add it to the fixity env
343 344 345 346 347 348
    extend_fix_env fix_env gre 
      | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
      = extendNameEnv fix_env name (FixItem occ fi)
      | otherwise
      = fix_env
      where
349
	name = gre_name gre
350
        occ  = nameOccName name
351
\end{code}
352

353 354
@getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
used for source code.
355

356 357
	*** See "THE NAMING STORY" in HsDecls ****

358
Instances of type families
359
~~~~~~~~~~~~~~~~~~~~~~~~~~
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
360 361 362 363 364
Family instances contain data constructors that we need to collect and we also
need to descend into the type instances of associated families in class
instances. The type constructor of a family instance is a usage occurence.
Hence, we don't return it as a subname in 'AvailInfo'; otherwise, we would get
a duplicate declaration error.
365

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
Note [Looking up family names in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider

  module M where
    type family T a :: *
    type instance M.T Int = Bool

We might think that we can simply use 'lookupOccRn' when processing the type
instance to look up 'M.T'.  Alas, we can't!  The type family declaration is in
the *same* HsGroup as the type instance declaration.  Hence, as we are
currently collecting the binders declared in that HsGroup, these binders will
not have been added to the global environment yet. 

In the case of type classes, this problem does not arise, as a class instance
does not define any binders of it's own.  So, we simply don't attempt to look
up the class names of class instances in 'get_local_binders' below.

If we don't look up class instances, can't we get away without looking up type
instances, too?  No, we can't.  Data type instances define data constructors
and we need to

  (1) collect those in 'get_local_binders' and
  (2) we need to get their parent name in 'get_local_binders', too, to
      produce an appropriate 'AvailTC'.

This parent name is exactly the family name of the type instance that is so
difficult to look up.

We solve this problem as follows:

  (a) We process all type declarations other than type instances first.
  (b) Then, we compute a 'GlobalRdrEnv' from the result of the first step.
  (c) Finally, we process all type instances (both those on the toplevel and 
      those nested in class instances) and check for the family names in the
      'GlobalRdrEnv' produced in the previous step before using 'lookupOccRn'.
402

403
\begin{code}
404 405 406 407 408 409 410 411 412 413 414 415 416 417
getLocalNonValBinders :: HsGroup RdrName -> RnM [AvailInfo]
-- Get all the top-level binders bound the group *except* 
-- for value bindings, which are treated separately
-- Specificaly we return AvailInfo for
--	type decls
--	class decls
--	associated types
--	foreign imports
--	(in hs-boot files) value signatures

getLocalNonValBinders group
  = do 	{ gbl_env <- getGblEnv
	; get_local_binders gbl_env group }

Ian Lynagh's avatar
Ian Lynagh committed
418
get_local_binders :: TcGblEnv -> HsGroup RdrName -> RnM [GenAvailInfo Name]
419 420 421 422
get_local_binders gbl_env (HsGroup {hs_valds  = ValBindsIn _ val_sigs,
				    hs_tyclds = tycl_decls, 
				    hs_instds = inst_decls,
				    hs_fords  = foreign_decls })
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
  = do	{   -- separate out the family instance declarations
          let (tyinst_decls1, tycl_decls_noinsts) 
                           = partition (isFamInstDecl . unLoc) tycl_decls
              tyinst_decls = tyinst_decls1 ++ 
                             concatMap (instDeclATs . unLoc) inst_decls 

            -- process all type/class decls except family instances
        ; tc_names  <- mapM new_tc tycl_decls_noinsts

            -- create a temporary rdr env of the type binders
        ; let tc_gres     = gresFromAvails LocalDef tc_names
              tc_name_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv tc_gres

            -- process all family instances
	; ti_names  <- mapM (new_ti tc_name_env) tyinst_decls

            -- finish off with value binder in case of a hs-boot file
	; val_names <- mapM new_simple val_bndrs
	; return (val_names ++ tc_names ++ ti_names) }
442 443 444
  where
    mod        = tcg_mod gbl_env
    is_hs_boot = isHsBoot (tcg_src gbl_env) ;
445

446
    for_hs_bndrs :: [Located RdrName]
447 448 449 450
    for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]

    -- In a hs-boot file, the value binders come from the
    --  *signatures*, and there should be no foreign binders 
451
    val_bndrs :: [Located RdrName]
452 453
    val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
              | otherwise  = for_hs_bndrs
454

455
    new_simple :: Located RdrName -> RnM (GenAvailInfo Name)
456 457 458
    new_simple rdr_name = do
        nm <- newTopSrcBinder mod rdr_name
        return (Avail nm)
459

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
460
    new_tc tc_decl              -- NOT for type/data instances
461
	= do { main_name <- newTopSrcBinder mod main_rdr
462
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
463
	     ; return (AvailTC main_name (main_name : sub_names)) }
464 465
      where
	(main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
466

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
467 468 469 470 471 472 473
    new_ti tc_name_env ti_decl  -- ONLY for type/data instances
	= do { main_name <- lookupFamInstDeclBndr tc_name_env main_rdr
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
	     ; return (AvailTC main_name sub_names) }
                	-- main_name is not bound here!
      where
	(main_rdr : sub_rdrs) = tyClDeclNames (unLoc ti_decl)
474

Ian Lynagh's avatar
Ian Lynagh committed
475
get_local_binders _ g = pprPanic "get_local_binders" (ppr g)
476 477
\end{code}

478

479 480 481 482 483 484 485 486 487 488
%************************************************************************
%*									*
\subsection{Filtering imports}
%*									*
%************************************************************************

@filterImports@ takes the @ExportEnv@ telling what the imported module makes
available, and filters it through the import spec (if any).

\begin{code}
489
filterImports :: ModIface
490
	      -> ImpDeclSpec			-- The span for the entire import decl
491 492 493
	      -> Maybe (Bool, [LIE RdrName])	-- Import spec; True => hiding
	      -> [AvailInfo]    		-- What's available
	      -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
494
		      GlobalRdrEnv)		-- Same again, but in GRE form
Ian Lynagh's avatar
Ian Lynagh committed
495
filterImports _ decl_spec Nothing all_avails
496 497 498 499
  = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
  where
    prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]

500 501

filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
502
  = do   -- check for errors, convert RdrNames to Names
503 504
        opt_typeFamilies <- doptM Opt_TypeFamilies
        items1 <- mapM (lookup_lie opt_typeFamilies) import_items
505 506 507 508 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 540 541 542 543 544 545 546 547 548

        let items2 :: [(LIE Name, AvailInfo)]
            items2 = concat items1
		-- NB the AvailInfo may have duplicates, and several items
		--    for the same parent; e.g N(x) and N(y)

            names  = availsToNameSet (map snd items2)
	    keep n = not (n `elemNameSet` names)
	    pruned_avails = filterAvails keep all_avails
	    hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]

	    gres | want_hiding = gresFromAvails hiding_prov pruned_avails
		 | otherwise   = concatMap (gresFromIE decl_spec) items2

        return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
  where
	-- This environment is how we map names mentioned in the import
        -- list to the actual Name they correspond to, and the name family
        -- that the Name belongs to (the AvailInfo).  The situation is
        -- complicated by associated families, which introduce a three-level
        -- hierachy, where class = grand parent, assoc family = parent, and
        -- data constructors = children.  The occ_env entries for associated
        -- families needs to capture all this information; hence, we have the
        -- third component of the environment that gives the class name (=
        -- grand parent) in case of associated families.
        --
	-- This env will have entries for data constructors too,
	-- they won't make any difference because naked entities like T
	-- in an import list map to TcOccs, not VarOccs.
    occ_env :: OccEnv (Name,	    -- the name
		       AvailInfo,   -- the export item providing the name
		       Maybe Name)  -- the parent of associated types
    occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing)) 
			         | a <- all_avails, n <- availNames a]
      where
        -- we know that (1) there are at most entries for one name, (2) their
        -- first component is identical, (3) they are for tys/cls, and (4) one
        -- entry has the name in its parent position (the other doesn't)
        combine (name, AvailTC p1 subs1, Nothing)
		(_   , AvailTC p2 subs2, Nothing)
          = let
	      (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
	    in
	    (name, AvailTC name subs, Just parent)
Ian Lynagh's avatar
Ian Lynagh committed
549
        combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
550 551

    lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
552
    lookup_lie opt_typeFamilies (L loc ieRdr)
553 554
        = do 
             stuff <- setSrcSpan loc $ 
555
                      case lookup_ie opt_typeFamilies ieRdr of
556 557 558 559 560 561 562
                            Failed err  -> addErr err >> return []
                            Succeeded a -> return a
             checkDodgyImport stuff
             return [ (L loc ie, avail) | (ie,avail) <- stuff ]
        where
                -- Warn when importing T(..) if T was exported abstractly
            checkDodgyImport stuff
Ian Lynagh's avatar
Ian Lynagh committed
563
                | IEThingAll n <- ieRdr, (_, AvailTC _ [_]):_ <- stuff
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
                = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
                -- NB. use the RdrName for reporting the warning
            checkDodgyImport _
                = return ()

        -- For each import item, we convert its RdrNames to Names,
        -- and at the same time construct an AvailInfo corresponding
        -- to what is actually imported by this item.
        -- Returns Nothing on error.
        -- We return a list here, because in the case of an import
        -- item like C, if we are hiding, then C refers to *both* a
        -- type/class and a data constructor.  Moreover, when we import
	-- data constructors of an associated family, we need separate
	-- AvailInfos for the data constructors and the family (as they have
	-- different parents).  See the discussion at occ_env.
    lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
580
    lookup_ie opt_typeFamilies ie 
581 582 583 584 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 611 612 613 614 615 616 617
      = let bad_ie = Failed (badImportItemErr iface decl_spec ie)

            lookup_name rdrName = 
                case lookupOccEnv occ_env (rdrNameOcc rdrName) of
                   Nothing -> bad_ie
                   Just n  -> return n
        in
        case ie of
         IEVar n -> do
             (name, avail, _) <- lookup_name n
             return [(IEVar name, trimAvail avail name)]

         IEThingAll tc -> do
             (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
             case mb_parent of
	       -- non-associated ty/cls
	       Nothing     -> return [(IEThingAll name, avail)]
	       -- associated ty
	       Just parent -> return [(IEThingAll name, 
				       AvailTC name2 (subs \\ [name])),
				      (IEThingAll name, AvailTC parent [name])]

         IEThingAbs tc
             | want_hiding   -- hiding ( C )
                        -- Here the 'C' can be a data constructor 
                        --  *or* a type/class, or even both
             -> let tc_name = lookup_name tc
                    dc_name = lookup_name (setRdrNameSpace tc srcDataName)
                in
                case catMaybeErr [ tc_name, dc_name ] of
                  []    -> bad_ie
                  names -> return [mkIEThingAbs name | name <- names]
             | otherwise
             -> do nameAvail <- lookup_name tc
                   return [mkIEThingAbs nameAvail]

         IEThingWith tc ns -> do
Ian Lynagh's avatar
Ian Lynagh committed
618
            (name, AvailTC _ subnames, mb_parent) <- lookup_name tc
619 620 621 622 623 624
	    let 
	      env         = mkOccEnv [(nameOccName s, s) | s <- subnames]
	      mb_children = map (lookupOccEnv env . rdrNameOcc) ns
	    children <- if any isNothing mb_children
                        then bad_ie
                        else return (catMaybes mb_children)
625 626
              -- check for proper import of type families
	    when (not opt_typeFamilies && any isTyConName children) $
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
              Failed (typeItemErr (head . filter isTyConName $ children)
				  (text "in import list"))
            case mb_parent of
	       -- non-associated ty/cls
	      Nothing     -> return [(IEThingWith name children, 
				      AvailTC name (name:children))]
	       -- associated ty
	      Just parent -> return [(IEThingWith name children, 
				      AvailTC name children),
				     (IEThingWith name children, 
				      AvailTC parent [name])]

         _other -> Failed illegalImportItemErr
         -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
         -- all errors.

      where
        mkIEThingAbs (n, av, Nothing    ) = (IEThingAbs n, trimAvail av n) 
Ian Lynagh's avatar
Ian Lynagh committed
645
        mkIEThingAbs (n, _,  Just parent) = (IEThingAbs n, AvailTC parent [n]) 
646 647 648 649 650 651


catMaybeErr :: [MaybeErr err a] -> [a]
catMaybeErr ms =  [ a | Succeeded a <- ms ]
\end{code}

652 653 654 655 656 657 658 659 660 661
%************************************************************************
%*									*
        Import/Export Utils
%*									*
%************************************************************************

\begin{code}
-- | make a 'GlobalRdrEnv' where all the elements point to the same
-- import declaration (useful for "hiding" imports, or imports with
-- no details).
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
gresFromAvails prov avails
  = concatMap (gresFromAvail (const prov)) avails

gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
gresFromAvail prov_fn avail
  = [ GRE {gre_name = n, 
	   gre_par = availParent n avail, 
	   gre_prov = prov_fn n}
    | n <- availNames avail ]
  
greAvail :: GlobalRdrElt -> AvailInfo
greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)

mkUnitAvail :: Name -> Parent -> AvailInfo
mkUnitAvail me (ParentIs p) 		 = AvailTC p  [me]
mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
			| otherwise	 = Avail me

Ian Lynagh's avatar
Ian Lynagh committed
681 682 683
plusAvail :: GenAvailInfo Name -> GenAvailInfo Name -> GenAvailInfo Name
plusAvail (Avail n1)      (Avail _)        = Avail n1
plusAvail (AvailTC _ ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
684 685 686
plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])

availParent :: Name -> AvailInfo -> Parent
Ian Lynagh's avatar
Ian Lynagh committed
687 688 689
availParent _ (Avail _)                 = NoParent
availParent n (AvailTC m _) | n == m    = NoParent
                            | otherwise = ParentIs m
690 691

trimAvail :: AvailInfo -> Name -> AvailInfo
Ian Lynagh's avatar
Ian Lynagh committed
692
trimAvail (Avail n)      _ = Avail n
693
trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

-- | filters 'AvailInfo's by the given predicate
filterAvails  :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
filterAvails keep avails = foldr (filterAvail keep) [] avails

-- | filters an 'AvailInfo' by the given predicate
filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
filterAvail keep ie rest =
  case ie of
    Avail n | keep n    -> ie : rest
            | otherwise -> rest
    AvailTC tc ns ->
        let left = filter keep ns in
        if null left then rest else AvailTC tc left : rest

Ian Lynagh's avatar
Ian Lynagh committed
709
-- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
710 711 712
gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
gresFromIE decl_spec (L loc ie, avail)
  = gresFromAvail prov_fn avail
713
  where
714
    is_explicit = case ie of
Ian Lynagh's avatar
Ian Lynagh committed
715 716
		    IEThingAll name -> \n -> n == name
		    _    	    -> \_ -> True
717 718 719 720 721 722 723 724 725
    prov_fn name = Imported [imp_spec]
	where
	  imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
	  item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }

mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
mkChildEnv gres = foldr add emptyNameEnv gres
    where
	add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
Ian Lynagh's avatar
Ian Lynagh committed
726
	add _                                            env = env
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

findChildren :: NameEnv [Name] -> Name -> [Name]
findChildren env n = lookupNameEnv env n `orElse` []
\end{code}

---------------------------------------
	AvailEnv and friends

All this AvailEnv stuff is hardly used; only in a very small
part of RnNames.  Todo: remove?
---------------------------------------

\begin{code}
type AvailEnv = NameEnv AvailInfo	-- Maps a Name to the AvailInfo that contains it

emptyAvailEnv :: AvailEnv
emptyAvailEnv = emptyNameEnv

745
{- Dead code
746 747 748 749 750 751 752 753
unitAvailEnv :: AvailInfo -> AvailEnv
unitAvailEnv a = unitNameEnv (availName a) a

plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
plusAvailEnv = plusNameEnv_C plusAvail

availEnvElts :: AvailEnv -> [AvailInfo]
availEnvElts = nameEnvElts
754
-}
755 756 757 758 759 760 761 762 763 764 765

addAvail :: AvailEnv -> AvailInfo -> AvailEnv
addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail

mkAvailEnv :: [AvailInfo] -> AvailEnv
	-- 'avails' may have several items with the same availName
	-- E.g  import Ix( Ix(..), index )
	-- will give Ix(Ix,index,range) and Ix(index)
	-- We want to combine these; addAvail does that
mkAvailEnv avails = foldl addAvail emptyAvailEnv avails

766 767 768 769 770 771 772 773 774
-- After combining the avails, we need to ensure that the parent name is the
-- first entry in the list of subnames, if it is included at all.  (Subsequent
-- functions rely on that.)
normaliseAvail :: AvailInfo -> AvailInfo
normaliseAvail avail@(Avail _)     = avail
normaliseAvail (AvailTC name subs) = AvailTC name subs'
  where
    subs' = if name `elem` subs then name : (delete name subs) else subs

775 776
-- | combines 'AvailInfo's from the same family
nubAvails :: [AvailInfo] -> [AvailInfo]
777
nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
778 779 780 781 782
\end{code}


%************************************************************************
%*									*
783
\subsection{Export list processing}
784 785 786 787 788
%*									*
%************************************************************************

Processing the export list.

789 790 791 792 793
You might think that we should record things that appear in the export
list as ``occurrences'' (using @addOccurrenceName@), but you'd be
wrong.  We do check (here) that they are in scope, but there is no
need to slurp in their actual declaration (which is what
@addOccurrenceName@ forces).
794

795 796 797
Indeed, doing so would big trouble when compiling @PrelBase@, because
it re-exports @GHC@, which includes @takeMVar#@, whose type includes
@ConcBase.StateAndSynchVar#@, and so on...
798 799 800

\begin{code}
type ExportAccum	-- The type of the accumulating parameter of
801
			-- the main worker function in rnExports
802
     = ([LIE Name],             -- Export items with Names
803
	ExportOccMap,		-- Tracks exported occurrence names
804
	[AvailInfo])	        -- The accumulated exported stuff
805 806
				--   Not nub'd!

Ian Lynagh's avatar
Ian Lynagh committed
807
emptyExportAccum :: ExportAccum
808
emptyExportAccum = ([], emptyOccEnv, []) 
809

810
type ExportOccMap = OccEnv (Name, IE RdrName)
811 812 813 814 815
	-- Tracks what a particular exported OccName
	--   in an export list refers to, and which item
	--   it came from.  It's illegal to export two distinct things
	--   that have the same occurrence name

816
rnExports :: Bool	-- False => no 'module M(..) where' header at all
817
          -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
818 819
	  -> TcGblEnv
          -> RnM TcGblEnv
820

821 822 823
	-- Complains if two distinct exports have same OccName
        -- Warns about identical exports.
	-- Complains about exports items not in scope
824

825 826 827 828 829
rnExports explicit_mod exports 
	  tcg_env@(TcGblEnv { tcg_mod     = this_mod,
          	      	      tcg_rdr_env = rdr_env, 
                     	      tcg_imports = imports })
 = do 	{  
830 831 832 833 834 835
	-- If the module header is omitted altogether, then behave
	-- as if the user had written "module Main(main) where..."
	-- EXCEPT in interactive mode, when we behave as if he had
	-- written "module Main where ..."
	-- Reason: don't want to complain about 'main' not in scope
	--	   in interactive mode
836
        ; dflags <- getDOpts
837
	; let real_exports 
838 839
          	 | explicit_mod = exports
          	 | ghcLink dflags == LinkInMemory = Nothing
840 841 842 843 844 845 846 847 848 849 850 851 852 853
          	 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
	  		-- ToDo: the 'noLoc' here is unhelpful if 'main' 
	  		--       turns out to be out of scope

	; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
	; let final_avails = nubAvails avails	     -- Combine families
	
	; return (tcg_env { tcg_exports    = final_avails,
                            tcg_rn_exports = case tcg_rn_exports tcg_env of
						Nothing -> Nothing
						Just _  -> rn_exports,
			    tcg_dus = tcg_dus tcg_env `plusDU` 
				      usesOnly (availsToNameSet final_avails) }) }

854 855 856 857 858 859 860
exports_from_avail :: Maybe [LIE RdrName]
                         -- Nothing => no explicit export list
                   -> GlobalRdrEnv
                   -> ImportAvails
                   -> Module
                   -> RnM (Maybe [LIE Name], [AvailInfo])

Ian Lynagh's avatar
Ian Lynagh committed
861
exports_from_avail Nothing rdr_env _imports _this_mod
862
 = -- The same as (module M) where M is the current module name,
863 864
   -- so that's how we handle it.
   let
865
       avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
866 867 868 869 870
                                 isLocalGRE gre ]
   in
   return (Nothing, avails)

exports_from_avail (Just rdr_items) rdr_env imports this_mod
871
  = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
872

873
       return (Just ie_names, exports)
874
  where
875 876
    do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
    do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
877

878 879 880
    kids_env :: NameEnv [Name]	-- Maps a parent to its in-scope children
    kids_env = mkChildEnv (globalRdrEnvElts rdr_env)

881
    imported_modules = [ qual_name
882
                       | xs <- moduleEnvElts $ imp_mods imports,
883 884
                         (qual_name, _, _) <- xs ]

885 886
    exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
    exports_from_item acc@(ie_names, occs, exports) 
887 888 889
                      (L loc ie@(IEModuleContents mod))
	| let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
	, mod `elem` earlier_mods 	-- Duplicate export of M
890 891
	= do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
	       warnIf warn_dup_exports (dupModuleExport mod) ;
892
	       return acc }
893 894

	| otherwise
895
	= do { implicit_prelude <- doptM Opt_ImplicitPrelude
896
             ; let { exportValid = (mod `elem` imported_modules)
897
                            || (moduleName this_mod == mod)
898 899 900 901
                   ; gres = filter (isModuleExported implicit_prelude mod)
                                   (globalRdrEnvElts rdr_env)
		   ; names = map gre_name gres
                   }
902

903
             ; checkErr exportValid (moduleNotImported mod)
904
	     ; warnIf (exportValid && null gres) (nullModuleExport mod)
905

906 907 908 909 910 911
	     ; addUsedRdrNames (concat [ [mkRdrQual mod occ, mkRdrUnqual occ]
                                       | occ <- map nameOccName names ])
			-- The qualified and unqualified version of all of
			-- these names are, in effect, used by this export

	     ; occs' <- check_occs ie occs names
912 913 914 915 916 917
                      -- This check_occs not only finds conflicts
                      -- between this item and others, but also
                      -- internally within this item.  That is, if
                      -- 'M.x' is in scope in several ways, we'll have
                      -- several members of mod_avails with the same
                      -- OccName.
918 919
	     ; return (L loc (IEModuleContents mod) : ie_names,
                       occs', map greAvail gres ++ exports) }
920 921

    exports_from_item acc@(lie_names, occs, exports) (L loc ie)
922 923 924 925 926 927 928
	| isDoc ie
	= do new_ie <- lookup_doc_ie ie
	     return (L loc new_ie : lie_names, occs, exports)

	| otherwise
        = do (new_ie, avail) <- lookup_ie ie
             if isUnboundName (ieName new_ie)
929 930 931
                  then return acc 	-- Avoid error cascade
                  else do

932
             occs' <- check_occs ie occs (availNames avail)
933

934 935 936 937
             return (L loc new_ie : lie_names, occs', avail : exports)

    -------------
    lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
938
    lookup_ie (IEVar rdr) 
939 940
        = do gre <- lookupGreRn rdr
             return (IEVar (gre_name gre), greAvail gre)
941 942

    lookup_ie (IEThingAbs rdr) 
943 944 945 946 947 948 949
        = do gre <- lookupGreRn rdr
	     let name = gre_name gre
	     case gre_par gre of
		NoParent   -> return (IEThingAbs name, 
				      AvailTC name [name])
		ParentIs p -> return (IEThingAbs name, 
				      AvailTC p [name])
950

951
    lookup_ie ie@(IEThingAll rdr) 
952
        = do name <- lookupGlobalOccRn rdr
953
	     let kids = findChildren kids_env name
954 955 956 957
                 mkKidRdrName = case isQual_maybe rdr of
                                Nothing -> mkRdrUnqual
                                Just (modName, _) -> mkRdrQual modName
             addUsedRdrNames $ map (mkKidRdrName . nameOccName) kids
958 959 960 961 962 963 964
	     when (null kids)
		  (if (isTyConName name) then addWarn (dodgyExportWarn name)
				-- This occurs when you export T(..), but
				-- only import T abstractly, or T is a synonym.  
		   else addErr (exportItemErr ie))
			
             return (IEThingAll name, AvailTC name (name:kids))
965 966 967 968

    lookup_ie ie@(IEThingWith rdr sub_rdrs)
        = do name <- lookupGlobalOccRn rdr
             if isUnboundName name
969
                then return (IEThingWith name [], AvailTC name [name])
970
                else do
971 972 973
             let env = mkOccEnv [ (nameOccName s, s) 
                                | s <- findChildren kids_env name ]
                 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
974 975
             if any isNothing mb_names
                then do addErr (exportItemErr ie)
976
                        return (IEThingWith name [], AvailTC name [name])
977
                else do let names = catMaybes mb_names
978 979
                        optTyFam <- doptM Opt_TypeFamilies
                        when (not optTyFam && any isTyConName names) $
980 981 982 983
                          addErr (typeItemErr ( head
                                              . filter isTyConName 
                                              $ names )
                                              (text "in export list"))
984
                        return (IEThingWith name names, AvailTC name (name:names))
985

Ian Lynagh's avatar
Ian Lynagh committed
986
    lookup_ie _ = panic "lookup_ie"	-- Other cases covered earlier
987

988 989 990 991 992 993 994
    -------------
    lookup_doc_ie :: IE RdrName -> RnM (IE Name)
    lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
					 return (IEGroup lev rn_doc)
    lookup_doc_ie (IEDoc doc)       = do rn_doc <- rnHsDoc doc
				         return (IEDoc rn_doc)
    lookup_doc_ie (IEDocNamed str)  = return (IEDocNamed str)
Ian Lynagh's avatar
Ian Lynagh committed
995
    lookup_doc_ie _ = panic "lookup_doc_ie"	-- Other cases covered earlier
996 997


Ian Lynagh's avatar
Ian Lynagh committed
998
isDoc :: IE RdrName -> Bool
999 1000 1001 1002
isDoc (IEDoc _)      = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _)  = True
isDoc _ = False
1003

1004
-------------------------------
1005 1006 1007 1008 1009 1010 1011 1012
isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
-- True if the thing is in scope *both* unqualified, *and* with qualifier M
isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
  | implicit_prelude && isBuiltInSyntax name = False
	-- Optimisation: filter out names for built-in syntax
	-- They just clutter up the environment (esp tuples), and the parser
	-- will generate Exact RdrNames for them, so the cluttered
	-- envt is no use.  To avoid doing this filter all the time,
1013
	-- we use -XNoImplicitPrelude as a clue that the filter is
1014 1015 1016 1017 1018 1019
	-- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
	--
	-- It's worth doing because it makes the environment smaller for
	-- every module that imports the Prelude
  | otherwise
  = case prov of
1020 1021 1022
	LocalDef | Just name_mod <- nameModule_maybe name
		 -> moduleName name_mod == mod
		 | otherwise -> False
1023
	Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1024

1025
-------------------------------
1026
check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1027 1028
check_occs ie occs names
  = foldlM check occs names
1029
  where
1030
    check occs name
1031
      = case lookupOccEnv occs name_occ of
1032
	  Nothing -> return (extendOccEnv occs name_occ (name, ie))
1033

1034
	  Just (name', ie') 
1035 1036 1037
	    | name == name'  	-- Duplicate export
	    ->	do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
		     warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
1038
		     return occs }
1039 1040 1041

	    | otherwise		-- Same occ name but different names: an error
	    ->	do { global_env <- getGlobalRdrEnv ;
1042
  		     addErr (exportClashErr global_env name' name ie' ie) ;
1043
		     return occs }
1044 1045 1046 1047
      where
	name_occ = nameOccName name
\end{code}

1048 1049
%*********************************************************
%*						 	 *
1050 1051 1052 1053 1054
		Deprecations
%*							 *
%*********************************************************

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
1055 1056 1057 1058 1059 1060
finishWarnings :: DynFlags -> Maybe WarningTxt 
               -> TcGblEnv -> RnM TcGblEnv
-- (a) Report usage of imports that are deprecated or have other warnings
-- (b) If the whole module is warned about or deprecated, update tcg_warns
--     All this happens only once per module
finishWarnings dflags mod_warn tcg_env
1061
  = do	{ (eps,hpt) <- getEpsAndHpt
Ian Lynagh's avatar
Ian Lynagh committed
1062
	; ifOptM Opt_WarnWarningsDeprecations $
1063
	  mapM_ (check hpt (eps_PIT eps)) all_gres
1064 1065
		-- By this time, typechecking is complete, 
		-- so the PIT is fully populated
1066

Ian Lynagh's avatar
Ian Lynagh committed
1067 1068 1069 1070 1071
	-- Deal with a module deprecation; it overrides all existing warns
	; let new_warns = case mod_warn of
				Just txt -> WarnAll txt
				Nothing  -> tcg_warns tcg_env
	; return (tcg_env { tcg_warns = new_warns }) }
1072
  where
1073 1074
    used_names = allUses (tcg_dus tcg_env) 
	-- Report on all deprecated uses; hence allUses
1075 1076
    all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)

1077
    check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1078
      | name `elemNameSet` used_names
1079
      ,	Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1080
      = addWarnAt (importSpecLoc imp_spec)
Ian Lynagh's avatar
Ian Lynagh committed
1081
		  (sep [ptext (sLit "In the use of") <+> 
1082
			pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
1083
		 	quotes (ppr name),
1084
		      (parens imp_msg) <> colon,
1085 1086
		      (ppr deprec_txt) ])
	where
1087
	  name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1088
	  imp_mod  = importSpecModule imp_spec
Ian Lynagh's avatar
Ian Lynagh committed
1089
	  imp_msg  = ptext (sLit "imported from") <+> ppr imp_mod <> extra
Simon Marlow's avatar
Simon Marlow committed
1090
	  extra | imp_mod == moduleName name_mod = empty
Ian Lynagh's avatar
Ian Lynagh committed
1091
		| otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1092

Ian Lynagh's avatar
Ian Lynagh committed
1093
    check _ _ _ = return ()	-- Local, or not used, or not deprectated
1094 1095 1096 1097 1098 1099 1100
	    -- The Imported pattern-match: don't deprecate locally defined names
	    -- For a start, we may be exporting a deprecated thing
	    -- Also we may use a deprecated thing in the defn of another
	    -- deprecated things.  We may even use a deprecated thing in
	    -- the defn of a non-deprecated thing, when changing a module's 
	    -- interface