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

\begin{code}
7
{-# OPTIONS -w #-}
8 9 10
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
Ian Lynagh's avatar
Ian Lynagh committed
11
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 13
-- for details

14
module RnNames (
15 16
	rnImports, getLocalNonValBinders,
	rnExports, extendGlobalRdrEnvRn,
17
	reportUnusedNames, finishDeprecations,
18 19 20 21
    ) where

#include "HsVersions.h"

22
import DynFlags
23
import HsSyn		( IE(..), ieName, ImportDecl(..), LImportDecl,
24
			  ForeignDecl(..), HsGroup(..), HsValBindsLR(..),
25
			  Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
26
			  instDeclATs, isFamInstDecl,
27
			  LIE )
28
import RnEnv
29
import RnHsDoc          ( rnHsDoc )
30
import IfaceEnv		( ifaceExportNames )
31
import LoadIface	( loadSrcInterface, loadSysInterface )
32
import TcRnMonad hiding (LIE)
33

Simon Marlow's avatar
Simon Marlow committed
34 35
import PrelNames
import Module
36
import Name
37
import NameEnv
38
import LazyUniqFM
39
import NameSet
40 41 42
import OccName
import HscTypes
import RdrName
43
import Outputable
44
import Maybes
45
import SrcLoc
46 47
import FiniteMap
import ErrUtils
48
import BasicTypes	( DeprecTxt, Fixity )
49
import DriverPhases	( isHsBoot )
50
import Util
51
import FastString
52
import ListSetOps
53
import Data.List        ( partition, concatMap, (\\), delete )
54
import IO		( openFile, IOMode(..) )
55
import Monad		( when, mplus )
56 57 58 59 60 61
\end{code}



%************************************************************************
%*									*
62
		rnImports
63 64 65 66
%*									*
%************************************************************************

\begin{code}
67
rnImports :: [LImportDecl RdrName]
68
           -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
69

70
rnImports imports
71 72 73 74 75
         -- 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
76 77
         let prel_imports	= mkPrelImports this_mod implicit_prelude imports
             (source, ordinary) = partition is_source_import imports
78 79
             is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot

80 81 82 83
         ifOptM Opt_WarnImplicitPrelude (
            when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
          )

84
         stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
85
         stuff2 <- mapM (rnImportDecl this_mod) source
86 87
         let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
         return (decls, rdr_env, imp_avails,hpc_usage) 
88

89
    where
90 91 92 93 94
   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)
95 96
                = (decl:decls, 
                   gbl_env1 `plusGlobalRdrEnv` gbl_env2,
97 98
                   imp_avails1 `plusImportAvails` imp_avails2,
		   hpc_usage1 || hpc_usage2)
99

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
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
       = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls, 
	           unLoc mod == pRELUDE_NAME ]

      preludeImportDecl :: LImportDecl RdrName
      preludeImportDecl
        = L loc $
	  ImportDecl (L loc pRELUDE_NAME)
121 122 123 124
	       False {- Not a boot interface -}
	       False	{- Not qualified -}
	       Nothing	{- No "as" -}
	       Nothing	{- No import list -}
125

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
126 127
      loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")         

128

129 130
rnImportDecl  :: Module
	      -> LImportDecl RdrName
131
	      -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
132 133 134

rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
                                         qual_only as_mod imp_details))
135
  = 
136
    setSrcSpan loc $ do
137 138 139

	-- If there's an error in loadInterface, (e.g. interface
	-- file not found) we get lots of spurious errors from 'filterImports'
140
    let
141
	imp_mod_name = unLoc loc_imp_mod_name
142
	doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
143 144

    iface <- loadSrcInterface doc imp_mod_name want_boot
145

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

150 151 152 153
	-- Issue a user warning for a redundant {- SOURCE -} import
	-- NB that we arrange to read all the ordinary imports before 
	-- any of the {- SOURCE -} imports
    warnIf (want_boot && not (mi_boot iface))
154
	   (warnRedundantSourceImport imp_mod_name)
155

156
    let
157 158
	imp_mod	   = mi_module iface
	deprecs	   = mi_deprecs iface
159
	orph_iface = mi_orphan iface 
160 161
	has_finsts = mi_finsts iface 
	deps 	   = mi_deps iface
162 163

	filtered_exports = filter not_this_mod (mi_exports iface)
164
	not_this_mod (mod,_) = mod /= this_mod
165 166 167 168 169 170 171
	-- 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.)
172 173 174 175 176 177 178 179 180 181
	--
	-- 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.
182 183 184 185

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

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

        -- filter the imports according to the import declaration
194
    (new_imp_details, gbl_env) <- 
195
        filterImports iface imp_spec imp_details total_avails
196

197
    dflags <- getDOpts
198

199
    let
200
	-- Compute new transitive dependencies
201

202 203 204
 	orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
			       imp_mod : dep_orphs deps
		| otherwise  = dep_orphs deps
205

206 207 208 209
 	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
210 211
	pkg = modulePackageId (mi_module iface)

212
	(dependent_mods, dependent_pkgs) 
Simon Marlow's avatar
Simon Marlow committed
213
	   | pkg == thisPackage dflags =
214
	    	-- Imported module is from the home package
215
		-- Take its dependent modules and add imp_mod itself
216
		-- Take its dependent packages unchanged
217 218 219 220 221 222 223 224 225 226
		--
		-- 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
227
	   | otherwise =
228
 	   	-- Imported module is from another package
229
		-- Dump the dependent modules
230
		-- Add the package imp_mod comes from to the dependent packages
231 232
	         ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
	         ([], pkg : dep_pkgs deps)
233

234
	-- True <=> import M ()
235
	import_all = case imp_details of
236 237
			Just (is_hiding, ls) -> not is_hiding && null ls	
			other 		     -> False
238

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

247
	-- Complain if we import a deprecated module
248
    ifOptM Opt_WarnDeprecations	(
249
       case deprecs of	
250
	  DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
251
	  other	        -> return ()
252 253 254 255
     )

    let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
                                         qual_only as_mod new_imp_details)
256

257
    return (new_imp_decl, gbl_env, imports, mi_hpc iface)
258
    )
259

260
warnRedundantSourceImport mod_name
261
  = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
262
          <+> quotes (ppr mod_name)
263 264 265
\end{code}


266 267 268 269 270 271 272 273 274 275 276
%************************************************************************
%*									*
		importsFromLocalDecls
%*									*
%************************************************************************

From the top-level declarations of this module produce
  	* the lexical environment
	* the ImportAvails
created by its bindings.  
	
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
Note [Shadowing in extendRdrEnvRn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usually when etending the GlobalRdrEnv we complain if a new binding
duplicates an existing one.  By adding the bindings one at a time, 
this check also complains if we add two new bindings for the same name.
(Remember that in Template Haskell the duplicates might *already be* 
in the GlobalRdrEnv from higher up the module.)

But with a Template Haskell quotation we want to *shadow*:
	f x = h [d| f = 3 |]
Here the inner binding for 'f' simply shadows the outer one.
And that applies even if the binding for 'f' is in a where-clause,
and hence is in the *local* RdrEnv not the *global* RdrEnv.

Hence the shadowP boolean passed in. 
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
\begin{code}
extendGlobalRdrEnvRn :: Bool	-- Note [Shadowing in extendGlobalRdrEnvRn]
               	     -> [AvailInfo]
	       	     -> MiniFixityEnv
	       	     -> RnM (TcGblEnv, TcLclEnv)
  -- Updates both the GlobalRdrEnv and the FixityEnv
  -- We return a new TcLclEnv only becuase we might have to
  -- delete some bindings from it; see Note [Shadowing in extendGlobalRdrEnvRn]

extendGlobalRdrEnvRn shadowP avails new_fixities
  = do	{ (gbl_env, lcl_env) <- getEnvs
	; let rdr_env = tcg_rdr_env gbl_env
	      fix_env = tcg_fix_env gbl_env

		-- Delete new_occs from global and local envs
		-- We are going to shadow them
	      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 }
	
 		-- Note [Shadowing in extendGlobalRdrEnvRn]
	      (rdr_env2, lcl_env2) | shadowP   = (rdr_env1, lcl_env1)
				   | otherwise = (rdr_env,  lcl_env)
316

317 318 319 320 321 322
	; (rdr_env', fix_env') <- foldlM extend (rdr_env2, fix_env) gres
	
	; let gbl_env' = gbl_env { tcg_rdr_env = rdr_env', tcg_fix_env = fix_env' }
	; return (gbl_env', lcl_env2) }
  where
    gres = gresFromAvails LocalDef avails
323

324 325 326 327 328 329
    extend envs@(cur_rdr_env, cur_fix_env) gre
	= let gres = lookupGlobalRdrEnv cur_rdr_env (nameOccName (gre_name gre)) 
          in case filter isLocalGRE gres of -- Check for existing *local* defns 
                  dup_gre:_ -> do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
	                          ; return envs }
                  [] -> return (simple_extend envs gre)
330

331 332 333 334
    simple_extend (rdr_env, fix_env) gre 
      = (extendGlobalRdrEnv rdr_env gre, fix_env')
      where
     	--  If there is a fixity decl for the gre,
335
        --  add it to the fixity env
336 337 338 339 340
	name = gre_name gre
        occ = nameOccName name
        fix_env' = case lookupOccEnv new_fixities occ of
                     Nothing       -> fix_env
                     Just (L _ fi) -> extendNameEnv fix_env name (FixItem occ fi)
341
\end{code}
342

343 344
@getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
used for source code.
345

346 347
	*** See "THE NAMING STORY" in HsDecls ****

348
Instances of type families
349 350 351 352 353 354 355 356 357
~~~~~~~~~~~~~~~~~~~~~~~~~~
Indexed data/newtype instances contain data constructors that we need to
collect, too.  Moreover, we need to descend into the data/newtypes instances
of associated families.

We need to be careful with the handling of the type constructor of each type
instance as the family constructor is already defined, and we want to avoid
raising a duplicate declaration error.  So, we make a new name for it, but
don't return it in the 'AvailInfo'.
358

359
\begin{code}
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
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 }

get_local_binders gbl_env (HsGroup {hs_valds  = ValBindsIn _ val_sigs,
				    hs_tyclds = tycl_decls, 
				    hs_instds = inst_decls,
				    hs_fords  = foreign_decls })
378 379 380
  = do	{ tc_names_s <- mapM new_tc tycl_decls
	; at_names_s <- mapM inst_ats inst_decls
	; val_names  <- mapM new_simple val_bndrs
381
	; return (val_names ++ tc_names_s ++ concat at_names_s) }
382 383 384
  where
    mod        = tcg_mod gbl_env
    is_hs_boot = isHsBoot (tcg_src gbl_env) ;
385 386 387 388 389 390 391

    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 
    val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
              | otherwise  = for_hs_bndrs
392

393 394 395
    new_simple rdr_name = do
        nm <- newTopSrcBinder mod rdr_name
        return (Avail nm)
396

397
    new_tc tc_decl 
398
      | isFamInstDecl (unLoc tc_decl)
399
	= do { main_name <- lookupFamInstDeclBndr mod main_rdr
400
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
401 402
	     ; return (AvailTC main_name sub_names) }
                	-- main_name is not bound here!
403
      | otherwise
404
	= do { main_name <- newTopSrcBinder mod main_rdr
405
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
406
	     ; return (AvailTC main_name (main_name : sub_names)) }
407 408
      where
	(main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
409 410

    inst_ats inst_decl 
411
	= mapM new_tc (instDeclATs (unLoc inst_decl))
412 413

getLocalDeclBinders _ _ = panic "getLocalDeclBinders"	-- ValBindsOut can't happen
414 415
\end{code}

416

417 418 419 420 421 422 423 424 425 426
%************************************************************************
%*									*
\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}
427
filterImports :: ModIface
428
	      -> ImpDeclSpec			-- The span for the entire import decl
429 430 431
	      -> Maybe (Bool, [LIE RdrName])	-- Import spec; True => hiding
	      -> [AvailInfo]    		-- What's available
	      -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
432
		      GlobalRdrEnv)		-- Same again, but in GRE form
433
			
434
filterImports iface decl_spec Nothing all_avails
435 436 437 438
  = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
  where
    prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]

439 440

filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
441
  = do   -- check for errors, convert RdrNames to Names
442 443
        opt_typeFamilies <- doptM Opt_TypeFamilies
        items1 <- mapM (lookup_lie opt_typeFamilies) import_items
444 445 446 447 448 449 450 451 452 453 454 455 456 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 487 488 489

        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)

    lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
490
    lookup_lie opt_typeFamilies (L loc ieRdr)
491 492
        = do 
             stuff <- setSrcSpan loc $ 
493
                      case lookup_ie opt_typeFamilies ieRdr of
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
                            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
                | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
                = 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)]
518
    lookup_ie opt_typeFamilies ie 
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 549 550 551 552 553 554 555 556 557 558 559 560 561 562
      = 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
            (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
	    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)
563 564
              -- check for proper import of type families
	    when (not opt_typeFamilies && any isTyConName children) $
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
              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) 
	mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n]) 


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

590 591 592 593 594 595 596 597 598 599
%************************************************************************
%*									*
        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).
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
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

plusAvail (Avail n1)	   (Avail n2)	    = Avail n1
plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])

availParent :: Name -> AvailInfo -> Parent
availParent n (Avail _) 		 = NoParent
availParent n (AvailTC m ms) | n==m      = NoParent
			     | otherwise = ParentIs m

trimAvail :: AvailInfo -> Name -> AvailInfo
trimAvail (Avail n)      m = Avail n
trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

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

-- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
647 648 649
gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
gresFromIE decl_spec (L loc ie, avail)
  = gresFromAvail prov_fn avail
650
  where
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    is_explicit = case ie of
		    IEThingAll name -> \n -> n==name
		    other	    -> \n -> True
    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]
	add other_gre					 env = env

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

unitAvailEnv :: AvailInfo -> AvailEnv
unitAvailEnv a = unitNameEnv (availName a) a

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

availEnvElts :: AvailEnv -> [AvailInfo]
availEnvElts = nameEnvElts

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

701 702 703 704 705 706 707 708 709
-- 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

710 711
-- | combines 'AvailInfo's from the same family
nubAvails :: [AvailInfo] -> [AvailInfo]
712
nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
713 714 715 716 717
\end{code}


%************************************************************************
%*									*
718
\subsection{Export list processing}
719 720 721 722 723
%*									*
%************************************************************************

Processing the export list.

724 725 726 727 728
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).
729

730 731 732
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...
733 734 735

\begin{code}
type ExportAccum	-- The type of the accumulating parameter of
736
			-- the main worker function in rnExports
737
     = ([LIE Name],             -- Export items with Names
738
	ExportOccMap,		-- Tracks exported occurrence names
739
	[AvailInfo])	        -- The accumulated exported stuff
740 741
				--   Not nub'd!

742
emptyExportAccum = ([], emptyOccEnv, []) 
743

744
type ExportOccMap = OccEnv (Name, IE RdrName)
745 746 747 748 749
	-- 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

750
rnExports :: Bool	-- False => no 'module M(..) where' header at all
751
          -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
752 753
	  -> TcGblEnv
          -> RnM TcGblEnv
754

755 756 757
	-- Complains if two distinct exports have same OccName
        -- Warns about identical exports.
	-- Complains about exports items not in scope
758

759 760 761 762 763
rnExports explicit_mod exports 
	  tcg_env@(TcGblEnv { tcg_mod     = this_mod,
          	      	      tcg_rdr_env = rdr_env, 
                     	      tcg_imports = imports })
 = do 	{  
764 765 766 767 768 769
	-- 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
770
        ; dflags <- getDOpts
771
	; let real_exports 
772 773
          	 | explicit_mod = exports
          	 | ghcLink dflags == LinkInMemory = Nothing
774 775 776 777 778 779 780 781 782 783 784 785 786 787
          	 | 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) }) }

788 789 790 791 792 793 794 795 796

exports_from_avail :: Maybe [LIE RdrName]
                         -- Nothing => no explicit export list
                   -> GlobalRdrEnv
                   -> ImportAvails
                   -> Module
                   -> RnM (Maybe [LIE Name], [AvailInfo])

exports_from_avail Nothing rdr_env imports this_mod
797
 = -- The same as (module M) where M is the current module name,
798 799
   -- so that's how we handle it.
   let
800
       avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
801 802 803 804 805
                                 isLocalGRE gre ]
   in
   return (Nothing, avails)

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

808
       return (Just ie_names, exports)
809
  where
810 811
    do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
    do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
812

813 814 815
    kids_env :: NameEnv [Name]	-- Maps a parent to its in-scope children
    kids_env = mkChildEnv (globalRdrEnvElts rdr_env)

816 817 818 819
    imported_modules = [ qual_name
                       | (_, xs) <- moduleEnvElts $ imp_mods imports,
                         (qual_name, _, _) <- xs ]

820 821
    exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
    exports_from_item acc@(ie_names, occs, exports) 
822 823 824
                      (L loc ie@(IEModuleContents mod))
	| let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
	, mod `elem` earlier_mods 	-- Duplicate export of M
825 826
	= do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
	       warnIf warn_dup_exports (dupModuleExport mod) ;
827
	       return acc }
828 829

	| otherwise
830
	= do { implicit_prelude <- doptM Opt_ImplicitPrelude
831 832 833 834 835
         ; let { exportValid = (mod `elem` imported_modules)
                            || (moduleName this_mod == mod)
               ; gres = filter (isModuleExported implicit_prelude mod)
                               (globalRdrEnvElts rdr_env)
               }
836

837 838
         ; checkErr exportValid (moduleNotImported mod)
	     ; warnIf (exportValid && null gres) (nullModuleExport mod)
839 840

	     ; occs' <- check_occs ie occs (map gre_name gres)
841 842 843 844 845 846
                      -- 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.
847 848
	     ; return (L loc (IEModuleContents mod) : ie_names,
                       occs', map greAvail gres ++ exports) }
849 850

    exports_from_item acc@(lie_names, occs, exports) (L loc ie)
851 852 853 854 855 856 857
	| 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)
858 859 860
                  then return acc 	-- Avoid error cascade
                  else do

861
             occs' <- check_occs ie occs (availNames avail)
862

863 864 865 866
             return (L loc new_ie : lie_names, occs', avail : exports)

    -------------
    lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
867
    lookup_ie (IEVar rdr) 
868 869
        = do gre <- lookupGreRn rdr
             return (IEVar (gre_name gre), greAvail gre)
870 871

    lookup_ie (IEThingAbs rdr) 
872 873 874 875 876 877 878
        = 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])
879

880
    lookup_ie ie@(IEThingAll rdr) 
881
        = do name <- lookupGlobalOccRn rdr
882 883 884 885 886 887 888 889
	     let kids = findChildren kids_env name
	     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))
890 891 892 893

    lookup_ie ie@(IEThingWith rdr sub_rdrs)
        = do name <- lookupGlobalOccRn rdr
             if isUnboundName name
894
                then return (IEThingWith name [], AvailTC name [name])
895
                else do
896 897 898
             let env = mkOccEnv [ (nameOccName s, s) 
                                | s <- findChildren kids_env name ]
                 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
899 900
             if any isNothing mb_names
                then do addErr (exportItemErr ie)
901
                        return (IEThingWith name [], AvailTC name [name])
902
                else do let names = catMaybes mb_names
903 904
                        optTyFam <- doptM Opt_TypeFamilies
                        when (not optTyFam && any isTyConName names) $
905 906 907 908
                          addErr (typeItemErr ( head
                                              . filter isTyConName 
                                              $ names )
                                              (text "in export list"))
909
                        return (IEThingWith name names, AvailTC name (name:names))
910

911
    lookup_ie ie = panic "lookup_ie"	-- Other cases covered earlier
912

913 914 915 916 917 918 919 920
    -------------
    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)
    lookup_doc_ie ie = panic "lookup_doc_ie"	-- Other cases covered earlier
921 922 923 924 925 926


isDoc (IEDoc _)      = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _)  = True
isDoc _ = False
927

928
-------------------------------
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
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,
	-- we use -fno-implicit-prelude as a clue that the filter is
	-- 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
	LocalDef    -> moduleName (nameModule name) == mod
	Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
946

947
-------------------------------
948
check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
949 950
check_occs ie occs names
  = foldlM check occs names
951
  where
952
    check occs name
953
      = case lookupOccEnv occs name_occ of
954
	  Nothing -> return (extendOccEnv occs name_occ (name, ie))
955

956
	  Just (name', ie') 
957 958 959
	    | name == name'  	-- Duplicate export
	    ->	do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
		     warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
960
		     return occs }
961 962 963

	    | otherwise		-- Same occ name but different names: an error
	    ->	do { global_env <- getGlobalRdrEnv ;
964
  		     addErr (exportClashErr global_env name' name ie' ie) ;
965
		     return occs }
966 967 968 969
      where
	name_occ = nameOccName name
\end{code}

970 971
%*********************************************************
%*						 	 *
972 973 974 975 976
		Deprecations
%*							 *
%*********************************************************

\begin{code}
977 978 979 980 981 982 983 984 985
finishDeprecations :: DynFlags -> Maybe DeprecTxt 
		   -> TcGblEnv -> RnM TcGblEnv
-- (a) Report usasge of deprecated imports
-- (b) If the whole module is deprecated, update tcg_deprecs
-- 		All this happens only once per module
finishDeprecations dflags mod_deprec tcg_env
  = do	{ (eps,hpt) <- getEpsAndHpt
	; ifOptM Opt_WarnDeprecations	$
	  mapM_ (check hpt (eps_PIT eps)) all_gres
986 987
		-- By this time, typechecking is complete, 
		-- so the PIT is fully populated
988 989 990 991 992 993

	-- Deal with a module deprecation; it overrides all existing deprecs
	; let new_deprecs = case mod_deprec of
				Just txt -> DeprecAll txt
				Nothing  -> tcg_deprecs tcg_env
	; return (tcg_env { tcg_deprecs = new_deprecs }) }
994
  where
995 996
    used_names = allUses (tcg_dus tcg_env) 
	-- Report on all deprecated uses; hence allUses
997 998
    all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)

999
    check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1000
      | name `elemNameSet` used_names
1001
      ,	Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1002 1003
      = addWarnAt (importSpecLoc imp_spec)
		  (sep [ptext SLIT("Deprecated use of") <+> 
1004
			pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
1005
		 	quotes (ppr name),
1006
		      (parens imp_msg) <> colon,
1007 1008
		      (ppr deprec_txt) ])
	where
1009
	  name_mod = nameModule name
1010
	  imp_mod  = importSpecModule imp_spec
1011
	  imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
Simon Marlow's avatar
Simon Marlow committed
1012
	  extra | imp_mod == moduleName name_mod = empty
1013 1014
		| otherwise = ptext SLIT(", but defined in") <+> ppr name_mod

1015
    check hpt pit ok_gre = return ()	-- Local, or not used, or not deprectated
1016 1017 1018 1019 1020 1021 1022
	    -- 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

1023 1024 1025 1026
lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable 
	        -> GlobalRdrElt -> Maybe DeprecTxt
-- The name is definitely imported, so look in HPT, PIT
lookupImpDeprec dflags hpt pit gre
1027
  = case lookupIfaceByModule dflags hpt pit (nameModule name) of
1028
	Just iface -> mi_dep_fn iface name `mplus` 	-- Bleat if the thing, *or
1029 1030 1031
		      case gre_par gre of	
			ParentIs p -> mi_dep_fn iface p	-- its parent*, is deprec'd
			NoParent   -> Nothing
1032 1033

	Nothing -> Nothing	-- See Note [Used names with interface not loaded]
1034
  where
1035
	name = gre_name gre
1036 1037
\end{code}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
Note [Used names with interface not loaded]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By now all the interfaces should have been loaded,
because reportDeprecations happens after typechecking.
However, it's still (just) possible to to find a used 
Name whose interface hasn't been loaded:

a) It might be a WiredInName; in that case we may not load 
   its interface (although we could).

b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
   These are seen as "used" by the renamer (if -fno-implicit-prelude) 
   is on), but the typechecker may discard their uses 
   if in fact the in-scope fromRational is GHC.Read.fromRational,
   (see tcPat.tcOverloadedLit), and the typechecker sees that the type 
   is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
   In that obscure case it won't force the interface in.

In both cases we simply don't permit deprecations; 
this is, after all, wired-in stuff.


1060 1061 1062
%*********************************************************
%*						 	 *
		Unused names
1063 1064 1065 1066
%*							 *
%*********************************************************

\begin{code}
1067
reportUnusedNames :: Maybe [LIE RdrName] 	-- Export list
1068 1069
		  -> TcGblEnv -> RnM ()
reportUnusedNames export_decls gbl_env 
1070 1071
  = do	{ traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
	; warnUnusedTopBinds   unused_locals
1072 1073
	; warnUnusedModules    unused_imp_mods
	; warnUnusedImports    unused_imports	
1074
	; warnDuplicateImports defined_and_used
1075
	; printMinimalImports  minimal_imports }
1076
  where
1077
    used_names :: NameSet
1078
    used_names = findUses (tcg_dus gbl_env) emptyNameSet
1079 1080 1081
	-- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
	-- Hence findUses

1082 1083
	-- Collect the defined names from the in-scope environment
    defined_names :: [GlobalRdrElt]
1084
    defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1085

1086 1087
	-- Note that defined_and_used, defined_but_not_used
	-- are both [GRE]; that's why we need defined_and_used
1088
	-- rather than just used_names
1089
    defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1090
    (defined_and_used, defined_but_not_used) 
1091
	= partition (gre_is_used used_names) defined_names
1092
    
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    kids_env = mkChildEnv defined_names
	-- This is done in mkExports too; duplicated work

    gre_is_used :: NameSet -> GlobalRdrElt -> Bool
    gre_is_used used_names (GRE {gre_name = name})
	= name `elemNameSet` used_names
	  || any (`elemNameSet` used_names) (findChildren kids_env name)
		-- A use of C implies a use of T,
		-- if C was brought into scope by T(..) or T(C)

1103 1104 1105 1106 1107 1108 1109 1110
	-- Filter out the ones that are 
	--  (a) defined in this module, and
	--  (b) not defined by a 'deriving' clause 
	-- The latter have an Internal Name, so we can filter them out easily
    unused_locals :: [GlobalRdrElt]
    unused_locals = filter is_unused_local defined_but_not_used
    is_unused_local :: GlobalRdrElt -> Bool
    is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1111