RnNames.lhs 55.1 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 RnEnv
18
import RnHsDoc          ( rnHsDoc )
19
import IfaceEnv		( ifaceExportNames )
20
import LoadIface	( loadSrcInterface, loadSysInterface )
21
import TcRnMonad hiding (LIE)
22

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



%************************************************************************
%*									*
50
		rnImports
51
52
53
54
%*									*
%************************************************************************

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

58
rnImports imports
59
60
61
62
63
         -- 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
64
65
         let prel_imports	= mkPrelImports this_mod implicit_prelude imports
             (source, ordinary) = partition is_source_import imports
66
67
             is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot

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

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

77
    where
78
79
80
81
82
   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)
83
84
                = (decl:decls, 
                   gbl_env1 `plusGlobalRdrEnv` gbl_env2,
85
86
                   imp_avails1 `plusImportAvails` imp_avails2,
		   hpc_usage1 || hpc_usage2)
87

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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)
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
122

rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
                                         qual_only as_mod imp_details))
123
  = 
124
    setSrcSpan loc $ do
125
126
127

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

    iface <- loadSrcInterface doc imp_mod_name want_boot
133

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

138
139
140
141
	-- 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))
142
	   (warnRedundantSourceImport imp_mod_name)
143

144
    let
145
	imp_mod	   = mi_module iface
Ian Lynagh's avatar
Ian Lynagh committed
146
	warns	   = mi_warns iface
147
	orph_iface = mi_orphan iface 
148
149
	has_finsts = mi_finsts iface 
	deps 	   = mi_deps iface
150
151

	filtered_exports = filter not_this_mod (mi_exports iface)
152
	not_this_mod (mod,_) = mod /= this_mod
153
154
155
156
157
158
159
	-- 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.)
160
161
162
163
164
165
166
167
168
169
	--
	-- 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.
170
171
172
173

	qual_mod_name = case as_mod of
			  Nothing  	    -> imp_mod_name
			  Just another_name -> another_name
174
175
	imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
		  		  is_dloc = loc, is_as = qual_mod_name }
176
177
178
179
180
181
    -- in

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

        -- filter the imports according to the import declaration
182
    (new_imp_details, gbl_env) <- 
183
        filterImports iface imp_spec imp_details total_avails
184

185
    dflags <- getDOpts
186

187
    let
188
	-- Compute new transitive dependencies
189

190
191
192
 	orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
			       imp_mod : dep_orphs deps
		| otherwise  = dep_orphs deps
193

194
195
196
197
 	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
198
199
	pkg = modulePackageId (mi_module iface)

200
	(dependent_mods, dependent_pkgs) 
Simon Marlow's avatar
Simon Marlow committed
201
	   | pkg == thisPackage dflags =
202
	    	-- Imported module is from the home package
203
		-- Take its dependent modules and add imp_mod itself
204
		-- Take its dependent packages unchanged
205
206
207
208
209
210
211
212
213
214
		--
		-- 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
215
	   | otherwise =
216
 	   	-- Imported module is from another package
217
		-- Dump the dependent modules
218
		-- Add the package imp_mod comes from to the dependent packages
219
220
	         ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
	         ([], pkg : dep_pkgs deps)
221

222
	-- True <=> import M ()
223
	import_all = case imp_details of
224
			Just (is_hiding, ls) -> not is_hiding && null ls	
Ian Lynagh's avatar
Ian Lynagh committed
225
			_ 		     -> False
226

227
	imports   = ImportAvails { 
228
			imp_mods     = unitModuleEnv imp_mod [(qual_mod_name, import_all, loc)],
229
			imp_orphs    = orphans,
230
			imp_finsts   = finsts,
231
			imp_dep_mods = mkModDeps dependent_mods,
232
			imp_dep_pkgs = dependent_pkgs
233
234
                   }

235
	-- Complain if we import a deprecated module
Ian Lynagh's avatar
Ian Lynagh committed
236
237
238
239
    ifOptM Opt_WarnWarningsDeprecations	(
       case warns of	
	  WarnAll txt -> addWarn (moduleWarn imp_mod_name txt)
	  _    	      -> return ()
240
241
242
243
     )

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

245
    return (new_imp_decl, gbl_env, imports, mi_hpc iface)
246
    )
247

Ian Lynagh's avatar
Ian Lynagh committed
248
warnRedundantSourceImport :: ModuleName -> SDoc
249
warnRedundantSourceImport mod_name
Ian Lynagh's avatar
Ian Lynagh committed
250
  = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
251
          <+> quotes (ppr mod_name)
252
253
254
\end{code}


255
256
257
258
259
260
261
262
263
264
265
%************************************************************************
%*									*
		importsFromLocalDecls
%*									*
%************************************************************************

From the top-level declarations of this module produce
  	* the lexical environment
	* the ImportAvails
created by its bindings.  
	
266
267
Note [Shadowing in extendGlobalRdrEnvRn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
268
269
270
271
272
273
274
275
276
277
278
279
280
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. 
281

282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
\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
298
		-- See Note [Shadowing in extendGlobalRdrEnvRn]
299
300
301
302
303
304
305
	      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)
306

307
308
309
310
311
312
313
	      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
314
	
315
	; traceRn (text "extendGlobalRdrEnvRn" <+> (ppr new_fixities $$ ppr fix_env $$ ppr fix_env'))
316
317
318
	; return (gbl_env', lcl_env2) }
  where
    gres = gresFromAvails LocalDef avails
319

320
     	--  If there is a fixity decl for the gre, add it to the fixity env
321
322
323
324
325
326
    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
327
	name = gre_name gre
328
        occ  = nameOccName name
329
\end{code}
330

331
332
@getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
used for source code.
333

334
335
	*** See "THE NAMING STORY" in HsDecls ****

336
Instances of type families
337
338
339
340
341
342
343
344
345
~~~~~~~~~~~~~~~~~~~~~~~~~~
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'.
346

347
\begin{code}
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
362
get_local_binders :: TcGblEnv -> HsGroup RdrName -> RnM [GenAvailInfo Name]
363
364
365
366
get_local_binders gbl_env (HsGroup {hs_valds  = ValBindsIn _ val_sigs,
				    hs_tyclds = tycl_decls, 
				    hs_instds = inst_decls,
				    hs_fords  = foreign_decls })
367
368
369
  = do	{ tc_names_s <- mapM new_tc tycl_decls
	; at_names_s <- mapM inst_ats inst_decls
	; val_names  <- mapM new_simple val_bndrs
370
	; return (val_names ++ tc_names_s ++ concat at_names_s) }
371
372
373
  where
    mod        = tcg_mod gbl_env
    is_hs_boot = isHsBoot (tcg_src gbl_env) ;
374

375
    for_hs_bndrs :: [Located RdrName]
376
377
378
379
    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 
380
    val_bndrs :: [Located RdrName]
381
382
    val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
              | otherwise  = for_hs_bndrs
383

384
    new_simple :: Located RdrName -> RnM (GenAvailInfo Name)
385
386
387
    new_simple rdr_name = do
        nm <- newTopSrcBinder mod rdr_name
        return (Avail nm)
388

389
    new_tc tc_decl 
390
      | isFamInstDecl (unLoc tc_decl)
391
	= do { main_name <- lookupFamInstDeclBndr mod main_rdr
392
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
393
394
	     ; return (AvailTC main_name sub_names) }
                	-- main_name is not bound here!
395
      | otherwise
396
	= do { main_name <- newTopSrcBinder mod main_rdr
397
	     ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
398
	     ; return (AvailTC main_name (main_name : sub_names)) }
399
400
      where
	(main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
401
402

    inst_ats inst_decl 
403
	= mapM new_tc (instDeclATs (unLoc inst_decl))
404

Ian Lynagh's avatar
Ian Lynagh committed
405
get_local_binders _ g = pprPanic "get_local_binders" (ppr g)
406
407
\end{code}

408

409
410
411
412
413
414
415
416
417
418
%************************************************************************
%*									*
\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}
419
filterImports :: ModIface
420
	      -> ImpDeclSpec			-- The span for the entire import decl
421
422
423
	      -> Maybe (Bool, [LIE RdrName])	-- Import spec; True => hiding
	      -> [AvailInfo]    		-- What's available
	      -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
424
		      GlobalRdrEnv)		-- Same again, but in GRE form
Ian Lynagh's avatar
Ian Lynagh committed
425
filterImports _ decl_spec Nothing all_avails
426
427
428
429
  = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
  where
    prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]

430
431

filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
432
  = do   -- check for errors, convert RdrNames to Names
433
434
        opt_typeFamilies <- doptM Opt_TypeFamilies
        items1 <- mapM (lookup_lie opt_typeFamilies) import_items
435
436
437
438
439
440
441
442
443
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

        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
479
        combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
480
481

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


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

582
583
584
585
586
587
588
589
590
591
%************************************************************************
%*									*
        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).
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
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
611
612
613
plusAvail :: GenAvailInfo Name -> GenAvailInfo Name -> GenAvailInfo Name
plusAvail (Avail n1)      (Avail _)        = Avail n1
plusAvail (AvailTC _ ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
614
615
616
plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])

availParent :: Name -> AvailInfo -> Parent
Ian Lynagh's avatar
Ian Lynagh committed
617
618
619
availParent _ (Avail _)                 = NoParent
availParent n (AvailTC m _) | n == m    = NoParent
                            | otherwise = ParentIs m
620
621

trimAvail :: AvailInfo -> Name -> AvailInfo
Ian Lynagh's avatar
Ian Lynagh committed
622
trimAvail (Avail n)      _ = Avail n
623
trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

-- | 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
639
-- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
640
641
642
gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
gresFromIE decl_spec (L loc ie, avail)
  = gresFromAvail prov_fn avail
643
  where
644
    is_explicit = case ie of
Ian Lynagh's avatar
Ian Lynagh committed
645
646
		    IEThingAll name -> \n -> n == name
		    _    	    -> \_ -> True
647
648
649
650
651
652
653
654
655
    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
656
	add _                                            env = env
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

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

694
695
696
697
698
699
700
701
702
-- 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

703
704
-- | combines 'AvailInfo's from the same family
nubAvails :: [AvailInfo] -> [AvailInfo]
705
nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
706
707
708
709
710
\end{code}


%************************************************************************
%*									*
711
\subsection{Export list processing}
712
713
714
715
716
%*									*
%************************************************************************

Processing the export list.

717
718
719
720
721
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).
722

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

\begin{code}
type ExportAccum	-- The type of the accumulating parameter of
729
			-- the main worker function in rnExports
730
     = ([LIE Name],             -- Export items with Names
731
	ExportOccMap,		-- Tracks exported occurrence names
732
	[AvailInfo])	        -- The accumulated exported stuff
733
734
				--   Not nub'd!

Ian Lynagh's avatar
Ian Lynagh committed
735
emptyExportAccum :: ExportAccum
736
emptyExportAccum = ([], emptyOccEnv, []) 
737

738
type ExportOccMap = OccEnv (Name, IE RdrName)
739
740
741
742
743
	-- 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

744
rnExports :: Bool	-- False => no 'module M(..) where' header at all
745
          -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
746
747
	  -> TcGblEnv
          -> RnM TcGblEnv
748

749
750
751
	-- Complains if two distinct exports have same OccName
        -- Warns about identical exports.
	-- Complains about exports items not in scope
752

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

782
783
784
785
786
787
788
789

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
790
exports_from_avail Nothing rdr_env _imports _this_mod
791
 = -- The same as (module M) where M is the current module name,
792
793
   -- so that's how we handle it.
   let
794
       avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
795
796
797
798
799
                                 isLocalGRE gre ]
   in
   return (Nothing, avails)

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

802
       return (Just ie_names, exports)
803
  where
804
805
    do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
    do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
806

807
808
809
    kids_env :: NameEnv [Name]	-- Maps a parent to its in-scope children
    kids_env = mkChildEnv (globalRdrEnvElts rdr_env)

810
    imported_modules = [ qual_name
811
                       | xs <- moduleEnvElts $ imp_mods imports,
812
813
                         (qual_name, _, _) <- xs ]

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

	| otherwise
824
	= do { implicit_prelude <- doptM Opt_ImplicitPrelude
825
826
827
828
829
         ; let { exportValid = (mod `elem` imported_modules)
                            || (moduleName this_mod == mod)
               ; gres = filter (isModuleExported implicit_prelude mod)
                               (globalRdrEnvElts rdr_env)
               }
830

831
832
         ; checkErr exportValid (moduleNotImported mod)
	     ; warnIf (exportValid && null gres) (nullModuleExport mod)
833
834

	     ; occs' <- check_occs ie occs (map gre_name gres)
835
836
837
838
839
840
                      -- 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.
841
842
	     ; return (L loc (IEModuleContents mod) : ie_names,
                       occs', map greAvail gres ++ exports) }
843
844

    exports_from_item acc@(lie_names, occs, exports) (L loc ie)
845
846
847
848
849
850
851
	| 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)
852
853
854
                  then return acc 	-- Avoid error cascade
                  else do

855
             occs' <- check_occs ie occs (availNames avail)
856

857
858
859
860
             return (L loc new_ie : lie_names, occs', avail : exports)

    -------------
    lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
861
    lookup_ie (IEVar rdr) 
862
863
        = do gre <- lookupGreRn rdr
             return (IEVar (gre_name gre), greAvail gre)
864
865

    lookup_ie (IEThingAbs rdr) 
866
867
868
869
870
871
872
        = 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])
873

874
    lookup_ie ie@(IEThingAll rdr) 
875
        = do name <- lookupGlobalOccRn rdr
876
877
878
879
880
881
882
883
	     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))
884
885
886
887

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

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

907
908
909
910
911
912
913
    -------------
    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
914
    lookup_doc_ie _ = panic "lookup_doc_ie"	-- Other cases covered earlier
915
916


Ian Lynagh's avatar
Ian Lynagh committed
917
isDoc :: IE RdrName -> Bool
918
919
920
921
isDoc (IEDoc _)      = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _)  = True
isDoc _ = False
922

923
-------------------------------
924
925
926
927
928
929
930
931
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,
932
	-- we use -XNoImplicitPrelude as a clue that the filter is
933
934
935
936
937
938
939
940
	-- 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
941

942
-------------------------------
943
check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
944
945
check_occs ie occs names
  = foldlM check occs names
946
  where
947
    check occs name
948
      = case lookupOccEnv occs name_occ of
949
	  Nothing -> return (extendOccEnv occs name_occ (name, ie))
950

951
	  Just (name', ie') 
952
953
954
	    | name == name'  	-- Duplicate export
	    ->	do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
		     warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
955
		     return occs }
956
957
958

	    | otherwise		-- Same occ name but different names: an error
	    ->	do { global_env <- getGlobalRdrEnv ;
959
  		     addErr (exportClashErr global_env name' name ie' ie) ;
960
		     return occs }
961
962
963
964
      where
	name_occ = nameOccName name
\end{code}

965
966
%*********************************************************
%*						 	 *
967
968
969
970
971
		Deprecations
%*							 *
%*********************************************************

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
972
973
974
975
976
977
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
978
  = do	{ (eps,hpt) <- getEpsAndHpt
Ian Lynagh's avatar
Ian Lynagh committed
979
	; ifOptM Opt_WarnWarningsDeprecations $
980
	  mapM_ (check hpt (eps_PIT eps)) all_gres
981
982
		-- By this time, typechecking is complete, 
		-- so the PIT is fully populated
983

Ian Lynagh's avatar
Ian Lynagh committed
984
985
986
987
988
	-- 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 }) }
989
  where
990
991
    used_names = allUses (tcg_dus tcg_env) 
	-- Report on all deprecated uses; hence allUses
992
993
    all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)

994
    check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
995
      | name `elemNameSet` used_names
996
      ,	Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
997
      = addWarnAt (importSpecLoc imp_spec)
Ian Lynagh's avatar
Ian Lynagh committed
998
		  (sep [ptext (sLit "In the use of") <+> 
999
			pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
1000
		 	quotes (ppr name),
For faster browsing, not all history is shown. View entire blame