Fix Trac #4240: -ddump-minimal-imports
[ghc-hetmet.git] / compiler / rename / RnNames.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnNames]{Extracting imported and top-level names in scope}
5
6 \begin{code}
7 module RnNames (
8         rnImports, getLocalNonValBinders,
9         rnExports, extendGlobalRdrEnvRn, 
10         gresFromAvails,
11         reportUnusedNames, finishWarnings,
12     ) where
13
14 #include "HsVersions.h"
15
16 import DynFlags
17 import HsSyn
18 import TcEnv            ( isBrackStage )
19 import RnEnv
20 import RnHsDoc          ( rnHsDoc )
21 import IfaceEnv         ( ifaceExportNames )
22 import LoadIface        ( loadSrcInterface )
23 import TcRnMonad
24
25 import HeaderInfo       ( mkPrelImports )
26 import PrelNames
27 import Module
28 import Name
29 import NameEnv
30 import NameSet
31 import HscTypes
32 import RdrName
33 import Outputable
34 import Maybes
35 import SrcLoc
36 import ErrUtils
37 import Util
38 import FastString
39 import ListSetOps
40 import Data.List        ( partition, (\\), delete )
41 import qualified Data.Set as Set
42 import System.IO
43 import Control.Monad
44 import Data.Map (Map)
45 import qualified Data.Map as Map
46 \end{code}
47
48
49
50 %************************************************************************
51 %*                                                                      *
52                 rnImports
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 rnImports :: [LImportDecl RdrName]
58            -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
59
60 rnImports imports
61          -- PROCESS IMPORT DECLS
62          -- Do the non {- SOURCE -} ones first, so that we get a helpful
63          -- warning for {- SOURCE -} ones that are unnecessary
64     = do this_mod <- getModule
65          implicit_prelude <- doptM Opt_ImplicitPrelude
66          let prel_imports       = mkPrelImports (moduleName this_mod) implicit_prelude imports
67              (source, ordinary) = partition is_source_import imports
68              is_source_import (L _ (ImportDecl _ _ is_boot _ _ _)) = is_boot
69
70          ifOptM Opt_WarnImplicitPrelude (
71             when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
72           )
73
74          stuff1 <- mapM (rnImportDecl this_mod True)  prel_imports
75          stuff2 <- mapM (rnImportDecl this_mod False) ordinary
76          stuff3 <- mapM (rnImportDecl this_mod False) source
77          let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2 ++ stuff3)
78          return (decls, rdr_env, imp_avails, hpc_usage)
79
80     where
81    combine :: [(LImportDecl Name,  GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
82            -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
83    combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
84         where plus (decl,  gbl_env1, imp_avails1,hpc_usage1)
85                    (decls, gbl_env2, imp_avails2,hpc_usage2)
86                 = (decl:decls, 
87                    gbl_env1 `plusGlobalRdrEnv` gbl_env2,
88                    imp_avails1 `plusImportAvails` imp_avails2,
89                    hpc_usage1 || hpc_usage2)
90
91 rnImportDecl  :: Module -> Bool
92               -> LImportDecl RdrName
93               -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
94
95 rnImportDecl this_mod implicit_prelude 
96              (L loc (ImportDecl { ideclName = loc_imp_mod_name, ideclPkgQual = mb_pkg
97                                 , ideclSource = want_boot, ideclQualified = qual_only
98                                 , ideclAs = as_mod, ideclHiding = imp_details }))
99   = setSrcSpan loc $ do
100
101     when (isJust mb_pkg) $ do
102         pkg_imports <- doptM Opt_PackageImports
103         when (not pkg_imports) $ addErr packageImportErr
104
105         -- If there's an error in loadInterface, (e.g. interface
106         -- file not found) we get lots of spurious errors from 'filterImports'
107     let
108         imp_mod_name = unLoc loc_imp_mod_name
109         doc = ppr imp_mod_name <+> ptext (sLit "is directly imported")
110
111     let isExplicit lie = case unLoc lie of
112                          IEThingAll _ -> False
113                          _ -> True
114     case imp_details of
115         Just (False, lies)
116          | all isExplicit lies ->
117             return ()
118         _ ->
119             unless implicit_prelude $
120             ifOptM Opt_WarnMissingImportList (addWarn (missingImportListWarn imp_mod_name))
121
122     iface <- loadSrcInterface doc imp_mod_name want_boot mb_pkg
123
124         -- Compiler sanity check: if the import didn't say
125         -- {-# SOURCE #-} we should not get a hi-boot file
126     WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
127
128         -- Issue a user warning for a redundant {- SOURCE -} import
129         -- NB that we arrange to read all the ordinary imports before 
130         -- any of the {- SOURCE -} imports.
131         --
132         -- in --make and GHCi, the compilation manager checks for this,
133         -- and indeed we shouldn't do it here because the existence of
134         -- the non-boot module depends on the compilation order, which
135         -- is not deterministic.  The hs-boot test can show this up.
136     dflags <- getDOpts
137     warnIf (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags))
138            (warnRedundantSourceImport imp_mod_name)
139
140     let
141         imp_mod    = mi_module iface
142         warns      = mi_warns iface
143         orph_iface = mi_orphan iface 
144         has_finsts = mi_finsts iface 
145         deps       = mi_deps iface
146
147         filtered_exports = filter not_this_mod (mi_exports iface)
148         not_this_mod (mod,_) = mod /= this_mod
149         -- If the module exports anything defined in this module, just
150         -- ignore it.  Reason: otherwise it looks as if there are two
151         -- local definition sites for the thing, and an error gets
152         -- reported.  Easiest thing is just to filter them out up
153         -- front. This situation only arises if a module imports
154         -- itself, or another module that imported it.  (Necessarily,
155         -- this invoves a loop.)
156         --
157         -- Tiresome consequence: if you say
158         --      module A where
159         --         import B( AType )
160         --         type AType = ...
161         --
162         --      module B( AType ) where
163         --         import {-# SOURCE #-} A( AType )
164         --
165         -- then you'll get a 'B does not export AType' message.  Oh well.
166
167         qual_mod_name = case as_mod of
168                           Nothing           -> imp_mod_name
169                           Just another_name -> another_name
170         imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
171                                   is_dloc = loc, is_as = qual_mod_name }
172     -- in
173
174         -- Get the total exports from this module
175     total_avails <- ifaceExportNames filtered_exports
176
177         -- filter the imports according to the import declaration
178     (new_imp_details, gbl_env) <- 
179         filterImports iface imp_spec imp_details total_avails
180
181     dflags <- getDOpts
182
183     let
184         -- Compute new transitive dependencies
185
186         orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
187                                imp_mod : dep_orphs deps
188                 | otherwise  = dep_orphs deps
189
190         finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
191                               imp_mod : dep_finsts deps
192                 | otherwise = dep_finsts deps
193
194         pkg = modulePackageId (mi_module iface)
195
196         (dependent_mods, dependent_pkgs) 
197            | pkg == thisPackage dflags =
198                 -- Imported module is from the home package
199                 -- Take its dependent modules and add imp_mod itself
200                 -- Take its dependent packages unchanged
201                 --
202                 -- NB: (dep_mods deps) might include a hi-boot file
203                 -- for the module being compiled, CM. Do *not* filter
204                 -- this out (as we used to), because when we've
205                 -- finished dealing with the direct imports we want to
206                 -- know if any of them depended on CM.hi-boot, in
207                 -- which case we should do the hi-boot consistency
208                 -- check.  See LoadIface.loadHiBootInterface
209                   ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
210
211            | otherwise =
212                 -- Imported module is from another package
213                 -- Dump the dependent modules
214                 -- Add the package imp_mod comes from to the dependent packages
215                  ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
216                  ([], pkg : dep_pkgs deps)
217
218         -- True <=> import M ()
219         import_all = case imp_details of
220                         Just (is_hiding, ls) -> not is_hiding && null ls        
221                         _                    -> False
222
223         imports   = ImportAvails { 
224                         imp_mods     = unitModuleEnv imp_mod [(qual_mod_name, import_all, loc)],
225                         imp_orphs    = orphans,
226                         imp_finsts   = finsts,
227                         imp_dep_mods = mkModDeps dependent_mods,
228                         imp_dep_pkgs = dependent_pkgs
229                    }
230
231         -- Complain if we import a deprecated module
232     ifOptM Opt_WarnWarningsDeprecations (
233        case warns of    
234           WarnAll txt -> addWarn (moduleWarn imp_mod_name txt)
235           _           -> return ()
236      )
237
238     let new_imp_decl = L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
239                                          qual_only as_mod new_imp_details)
240
241     return (new_imp_decl, gbl_env, imports, mi_hpc iface)
242     )
243
244 warnRedundantSourceImport :: ModuleName -> SDoc
245 warnRedundantSourceImport mod_name
246   = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
247           <+> quotes (ppr mod_name)
248 \end{code}
249
250
251 %************************************************************************
252 %*                                                                      *
253                 importsFromLocalDecls
254 %*                                                                      *
255 %************************************************************************
256
257 From the top-level declarations of this module produce
258         * the lexical environment
259         * the ImportAvails
260 created by its bindings.  
261         
262 Note [Top-level Names in Template Haskell decl quotes]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 Consider a Template Haskell declaration quotation like this:
265       module M where
266         f x = h [d| f = 3 |]
267 When renaming the declarations inside [d| ...|], we treat the
268 top level binders specially in two ways
269
270 1.  We give them an Internal name, not (as usual) an External one.
271     Otherwise the NameCache gets confused by a second allocation of
272     M.f.  (We used to invent a fake module ThFake to avoid this, but
273     that had other problems, notably in getting the correct answer for
274     nameIsLocalOrFrom in lookupFixity. So we now leave tcg_module 
275     unaffected.)
276
277 2.  We make them *shadow* the outer bindings. If we don't do that,
278     we'll get a complaint when extending the GlobalRdrEnv, saying that
279     there are two bindings for 'f'.  There are several tricky points:
280
281     * This shadowing applies even if the binding for 'f' is in a
282       where-clause, and hence is in the *local* RdrEnv not the *global*
283       RdrEnv.
284
285     * The *qualified* name M.f from the enclosing module must certainly 
286       still be available.  So we don't nuke it entirely; we just make 
287       it seem like qualified import.
288  
289     * We only shadow *External* names (which come from the main module)
290       Do not shadow *Inernal* names because in the bracket
291           [d| class C a where f :: a
292               f = 4 |]
293       rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
294       class decl, and *separately* extend the envt with the value binding.
295
296 3. We find out whether we are inside a [d| ... |] by testing the TH
297    stage. This is a slight hack, because the stage field was really
298    meant for the type checker, and here we are not interested in the
299    fields of Brack, hence the error thunks in thRnBrack.
300
301 \begin{code}
302 extendGlobalRdrEnvRn :: [AvailInfo]
303                      -> MiniFixityEnv
304                      -> RnM (TcGblEnv, TcLclEnv)
305   -- Updates both the GlobalRdrEnv and the FixityEnv
306   -- We return a new TcLclEnv only because we might have to
307   -- delete some bindings from it; 
308   -- see Note [Top-level Names in Template Haskell decl quotes]
309
310 extendGlobalRdrEnvRn avails new_fixities
311   = do  { (gbl_env, lcl_env) <- getEnvs
312         ; stage <- getStage
313         ; let rdr_env = tcg_rdr_env gbl_env
314               fix_env = tcg_fix_env gbl_env
315
316                 -- Delete new_occs from global and local envs
317                 -- If we are in a TemplateHaskell decl bracket, 
318                 --    we are going to shadow them
319                 -- See Note [Top-level Names in Template Haskell decl quotes]
320               shadowP  = isBrackStage stage
321               new_occs = map (nameOccName . gre_name) gres
322               rdr_env1 = transformGREs qual_gre new_occs rdr_env 
323               lcl_env1 = lcl_env { tcl_rdr = delListFromOccEnv (tcl_rdr lcl_env) new_occs }
324               (rdr_env2, lcl_env2) | shadowP   = (rdr_env1, lcl_env1)
325                                    | otherwise = (rdr_env,  lcl_env)
326
327               rdr_env3 = foldl extendGlobalRdrEnv rdr_env2 gres
328               fix_env' = foldl extend_fix_env     fix_env  gres
329               (rdr_env', dups) = findLocalDupsRdrEnv rdr_env3 new_occs
330
331               gbl_env' = gbl_env { tcg_rdr_env = rdr_env', tcg_fix_env = fix_env' }
332               
333         ; mapM_ addDupDeclErr dups
334         
335         ; traceRn (text "extendGlobalRdrEnvRn" <+> (ppr new_fixities $$ ppr fix_env $$ ppr fix_env'))
336         ; return (gbl_env', lcl_env2) }
337   where
338     gres = gresFromAvails LocalDef avails
339
340         --  If there is a fixity decl for the gre, add it to the fixity env
341     extend_fix_env fix_env gre 
342       | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
343       = extendNameEnv fix_env name (FixItem occ fi)
344       | otherwise
345       = fix_env
346       where
347         name = gre_name gre
348         occ  = nameOccName name
349
350     qual_gre :: GlobalRdrElt -> GlobalRdrElt
351     -- Transform top-level GREs from the module being compiled
352     -- so that they are out of the way of new definitions in a Template 
353     -- Haskell bracket
354     -- See Note [Top-level Names in Template Haskell decl quotes]
355     -- Seems like 5 times as much work as it deserves!
356     --
357     -- For a LocalDef we make a (fake) qualified imported GRE for a
358     -- local GRE so that the original *qualified* name is still in scope
359     -- but the *unqualified* one no longer is.  What a hack!
360
361     qual_gre gre@(GRE { gre_prov = LocalDef, gre_name = name })
362         | isExternalName name = gre { gre_prov = Imported [imp_spec] }
363         | otherwise           = gre                                 
364            -- Do not shadow Internal (ie Template Haskell) Names
365            -- See Note [Top-level Names in Template Haskell decl quotes]
366         where   
367           mod = ASSERT2( isExternalName name, ppr name) moduleName (nameModule name)
368           imp_spec = ImpSpec { is_item = ImpAll, is_decl = decl_spec }
369           decl_spec = ImpDeclSpec { is_mod = mod, is_as = mod, 
370                                     is_qual = True,     -- Qualified only!
371                                     is_dloc = srcLocSpan (nameSrcLoc name) }
372
373     qual_gre gre@(GRE { gre_prov = Imported specs })
374         = gre { gre_prov = Imported (map qual_spec specs) }
375
376     qual_spec spec@(ImpSpec { is_decl = decl_spec })
377         = spec { is_decl = decl_spec { is_qual = True } }
378 \end{code}
379
380 @getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
381 used for source code.
382
383         *** See "THE NAMING STORY" in HsDecls ****
384
385 Instances of type families
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~
387 Family instances contain data constructors that we need to collect and we also
388 need to descend into the type instances of associated families in class
389 instances. The type constructor of a family instance is a usage occurence.
390 Hence, we don't return it as a subname in 'AvailInfo'; otherwise, we would get
391 a duplicate declaration error.
392
393 Note [Looking up family names in family instances]
394 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
395 Consider
396
397   module M where
398     type family T a :: *
399     type instance M.T Int = Bool
400
401 We might think that we can simply use 'lookupOccRn' when processing the type
402 instance to look up 'M.T'.  Alas, we can't!  The type family declaration is in
403 the *same* HsGroup as the type instance declaration.  Hence, as we are
404 currently collecting the binders declared in that HsGroup, these binders will
405 not have been added to the global environment yet. 
406
407 In the case of type classes, this problem does not arise, as a class instance
408 does not define any binders of it's own.  So, we simply don't attempt to look
409 up the class names of class instances in 'get_local_binders' below.
410
411 If we don't look up class instances, can't we get away without looking up type
412 instances, too?  No, we can't.  Data type instances define data constructors
413 and we need to
414
415   (1) collect those in 'get_local_binders' and
416   (2) we need to get their parent name in 'get_local_binders', too, to
417       produce an appropriate 'AvailTC'.
418
419 This parent name is exactly the family name of the type instance that is so
420 difficult to look up.
421
422 We solve this problem as follows:
423
424   (a) We process all type declarations other than type instances first.
425   (b) Then, we compute a 'GlobalRdrEnv' from the result of the first step.
426   (c) Finally, we process all type instances (both those on the toplevel and 
427       those nested in class instances) and check for the family names in the
428       'GlobalRdrEnv' produced in the previous step before using 'lookupOccRn'.
429
430 \begin{code}
431 getLocalNonValBinders :: HsGroup RdrName -> RnM [AvailInfo]
432 -- Get all the top-level binders bound the group *except* 
433 -- for value bindings, which are treated separately
434 -- Specificaly we return AvailInfo for
435 --      type decls (incl constructors and record selectors)
436 --      class decls (including class ops)
437 --      associated types
438 --      foreign imports
439 --      (in hs-boot files) value signatures
440
441 getLocalNonValBinders group
442   = do  { gbl_env <- getGblEnv
443         ; get_local_binders gbl_env group }
444
445 get_local_binders :: TcGblEnv -> HsGroup RdrName -> RnM [GenAvailInfo Name]
446 get_local_binders gbl_env (HsGroup {hs_valds  = ValBindsIn _ val_sigs,
447                                     hs_tyclds = tycl_decls, 
448                                     hs_instds = inst_decls,
449                                     hs_fords  = foreign_decls })
450   = do  {   -- separate out the family instance declarations
451           let (tyinst_decls1, tycl_decls_noinsts) 
452                            = partition (isFamInstDecl . unLoc) tycl_decls
453               tyinst_decls = tyinst_decls1 ++ instDeclATs inst_decls
454
455             -- process all type/class decls except family instances
456         ; tc_names  <- mapM new_tc tycl_decls_noinsts
457
458             -- create a temporary rdr env of the type binders
459         ; let tc_gres     = gresFromAvails LocalDef tc_names
460               tc_name_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv tc_gres
461
462             -- process all family instances
463         ; ti_names  <- mapM (new_ti tc_name_env) tyinst_decls
464
465             -- finish off with value binder in case of a hs-boot file
466         ; val_names <- mapM new_simple val_bndrs
467         ; return (val_names ++ tc_names ++ ti_names) }
468   where
469     is_hs_boot = isHsBoot (tcg_src gbl_env) ;
470
471     for_hs_bndrs :: [Located RdrName]
472     for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
473
474     -- In a hs-boot file, the value binders come from the
475     --  *signatures*, and there should be no foreign binders 
476     val_bndrs :: [Located RdrName]
477     val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
478               | otherwise  = for_hs_bndrs
479
480     new_simple :: Located RdrName -> RnM (GenAvailInfo Name)
481     new_simple rdr_name = do
482         nm <- newTopSrcBinder rdr_name
483         return (Avail nm)
484
485     new_tc tc_decl              -- NOT for type/data instances
486         = do { main_name <- newTopSrcBinder main_rdr
487              ; sub_names <- mapM newTopSrcBinder sub_rdrs
488              ; return (AvailTC main_name (main_name : sub_names)) }
489       where
490         (main_rdr : sub_rdrs) = hsTyClDeclBinders tc_decl
491
492     new_ti tc_name_env ti_decl  -- ONLY for type/data instances
493         = do { main_name <- lookupFamInstDeclBndr tc_name_env main_rdr
494              ; sub_names <- mapM newTopSrcBinder sub_rdrs
495              ; return (AvailTC main_name sub_names) }
496                         -- main_name is not bound here!
497       where
498         (main_rdr : sub_rdrs) = hsTyClDeclBinders ti_decl
499
500 get_local_binders _ g = pprPanic "get_local_binders" (ppr g)
501 \end{code}
502
503
504 %************************************************************************
505 %*                                                                      *
506 \subsection{Filtering imports}
507 %*                                                                      *
508 %************************************************************************
509
510 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
511 available, and filters it through the import spec (if any).
512
513 \begin{code}
514 filterImports :: ModIface
515               -> ImpDeclSpec                    -- The span for the entire import decl
516               -> Maybe (Bool, [LIE RdrName])    -- Import spec; True => hiding
517               -> [AvailInfo]                    -- What's available
518               -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
519                       GlobalRdrEnv)             -- Same again, but in GRE form
520 filterImports _ decl_spec Nothing all_avails
521   = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
522   where
523     prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
524
525
526 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
527   = do   -- check for errors, convert RdrNames to Names
528         opt_typeFamilies <- doptM Opt_TypeFamilies
529         items1 <- mapM (lookup_lie opt_typeFamilies) import_items
530
531         let items2 :: [(LIE Name, AvailInfo)]
532             items2 = concat items1
533                 -- NB the AvailInfo may have duplicates, and several items
534                 --    for the same parent; e.g N(x) and N(y)
535
536             names  = availsToNameSet (map snd items2)
537             keep n = not (n `elemNameSet` names)
538             pruned_avails = filterAvails keep all_avails
539             hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
540
541             gres | want_hiding = gresFromAvails hiding_prov pruned_avails
542                  | otherwise   = concatMap (gresFromIE decl_spec) items2
543
544         return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
545   where
546         -- This environment is how we map names mentioned in the import
547         -- list to the actual Name they correspond to, and the name family
548         -- that the Name belongs to (the AvailInfo).  The situation is
549         -- complicated by associated families, which introduce a three-level
550         -- hierachy, where class = grand parent, assoc family = parent, and
551         -- data constructors = children.  The occ_env entries for associated
552         -- families needs to capture all this information; hence, we have the
553         -- third component of the environment that gives the class name (=
554         -- grand parent) in case of associated families.
555         --
556         -- This env will have entries for data constructors too,
557         -- they won't make any difference because naked entities like T
558         -- in an import list map to TcOccs, not VarOccs.
559     occ_env :: OccEnv (Name,        -- the name
560                        AvailInfo,   -- the export item providing the name
561                        Maybe Name)  -- the parent of associated types
562     occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing)) 
563                                  | a <- all_avails, n <- availNames a]
564       where
565         -- we know that (1) there are at most entries for one name, (2) their
566         -- first component is identical, (3) they are for tys/cls, and (4) one
567         -- entry has the name in its parent position (the other doesn't)
568         combine (name, AvailTC p1 subs1, Nothing)
569                 (_   , AvailTC p2 subs2, Nothing)
570           = let
571               (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
572             in
573             (name, AvailTC name subs, Just parent)
574         combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
575
576     lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
577     lookup_lie opt_typeFamilies (L loc ieRdr)
578         = do 
579              stuff <- setSrcSpan loc $ 
580                       case lookup_ie opt_typeFamilies ieRdr of
581                             Failed err  -> addErr err >> return []
582                             Succeeded a -> return a
583              checkDodgyImport stuff
584              return [ (L loc ie, avail) | (ie,avail) <- stuff ]
585         where
586                 -- Warn when importing T(..) if T was exported abstractly
587             checkDodgyImport stuff
588                 | IEThingAll n <- ieRdr, (_, AvailTC _ [_]):_ <- stuff
589                 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
590                 -- NB. use the RdrName for reporting the warning
591             checkDodgyImport _
592                 = return ()
593
594         -- For each import item, we convert its RdrNames to Names,
595         -- and at the same time construct an AvailInfo corresponding
596         -- to what is actually imported by this item.
597         -- Returns Nothing on error.
598         -- We return a list here, because in the case of an import
599         -- item like C, if we are hiding, then C refers to *both* a
600         -- type/class and a data constructor.  Moreover, when we import
601         -- data constructors of an associated family, we need separate
602         -- AvailInfos for the data constructors and the family (as they have
603         -- different parents).  See the discussion at occ_env.
604     lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
605     lookup_ie opt_typeFamilies ie 
606       = let bad_ie :: MaybeErr Message a
607             bad_ie = Failed (badImportItemErr iface decl_spec ie)
608
609             lookup_name rdr 
610               | isQual rdr = Failed (qualImportItemErr rdr)
611               | Just nm <- lookupOccEnv occ_env (rdrNameOcc rdr) = return nm
612               | otherwise                                        = bad_ie
613         in
614         case ie of
615          IEVar n -> do
616              (name, avail, _) <- lookup_name n
617              return [(IEVar name, trimAvail avail name)]
618
619          IEThingAll tc -> do
620              (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
621              case mb_parent of
622                -- non-associated ty/cls
623                Nothing     -> return [(IEThingAll name, avail)]
624                -- associated ty
625                Just parent -> return [(IEThingAll name, 
626                                        AvailTC name2 (subs \\ [name])),
627                                       (IEThingAll name, AvailTC parent [name])]
628
629          IEThingAbs tc
630              | want_hiding   -- hiding ( C )
631                         -- Here the 'C' can be a data constructor 
632                         --  *or* a type/class, or even both
633              -> let tc_name = lookup_name tc
634                     dc_name = lookup_name (setRdrNameSpace tc srcDataName)
635                 in
636                 case catMaybeErr [ tc_name, dc_name ] of
637                   []    -> bad_ie
638                   names -> return [mkIEThingAbs name | name <- names]
639              | otherwise
640              -> do nameAvail <- lookup_name tc
641                    return [mkIEThingAbs nameAvail]
642
643          IEThingWith tc ns -> do
644             (name, AvailTC _ subnames, mb_parent) <- lookup_name tc
645             let 
646               env         = mkOccEnv [(nameOccName s, s) | s <- subnames]
647               mb_children = map (lookupOccEnv env . rdrNameOcc) ns
648             children <- if any isNothing mb_children
649                         then bad_ie
650                         else return (catMaybes mb_children)
651               -- check for proper import of type families
652             when (not opt_typeFamilies && any isTyConName children) $
653               Failed (typeItemErr (head . filter isTyConName $ children)
654                                   (text "in import list"))
655             case mb_parent of
656                -- non-associated ty/cls
657               Nothing     -> return [(IEThingWith name children, 
658                                       AvailTC name (name:children))]
659                -- associated ty
660               Just parent -> return [(IEThingWith name children, 
661                                       AvailTC name children),
662                                      (IEThingWith name children, 
663                                       AvailTC parent [name])]
664
665          _other -> Failed illegalImportItemErr
666          -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
667          -- all errors.
668
669       where
670         mkIEThingAbs (n, av, Nothing    ) = (IEThingAbs n, trimAvail av n) 
671         mkIEThingAbs (n, _,  Just parent) = (IEThingAbs n, AvailTC parent [n]) 
672
673
674 catMaybeErr :: [MaybeErr err a] -> [a]
675 catMaybeErr ms =  [ a | Succeeded a <- ms ]
676 \end{code}
677
678 %************************************************************************
679 %*                                                                      *
680         Import/Export Utils
681 %*                                                                      *
682 %************************************************************************
683
684 \begin{code}
685 -- | make a 'GlobalRdrEnv' where all the elements point to the same
686 -- import declaration (useful for "hiding" imports, or imports with
687 -- no details).
688 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
689 gresFromAvails prov avails
690   = concatMap (gresFromAvail (const prov)) avails
691
692 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
693 gresFromAvail prov_fn avail
694   = [ GRE {gre_name = n, 
695            gre_par = availParent n avail, 
696            gre_prov = prov_fn n}
697     | n <- availNames avail ]
698   
699 greAvail :: GlobalRdrElt -> AvailInfo
700 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
701
702 mkUnitAvail :: Name -> Parent -> AvailInfo
703 mkUnitAvail me (ParentIs p)              = AvailTC p  [me]
704 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
705                         | otherwise      = Avail me
706
707 plusAvail :: GenAvailInfo Name -> GenAvailInfo Name -> GenAvailInfo Name
708 plusAvail (Avail n1)      (Avail _)        = Avail n1
709 plusAvail (AvailTC _ ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
710 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
711
712 availParent :: Name -> AvailInfo -> Parent
713 availParent _ (Avail _)                 = NoParent
714 availParent n (AvailTC m _) | n == m    = NoParent
715                             | otherwise = ParentIs m
716
717 trimAvail :: AvailInfo -> Name -> AvailInfo
718 trimAvail (Avail n)      _ = Avail n
719 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
720
721 -- | filters 'AvailInfo's by the given predicate
722 filterAvails  :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
723 filterAvails keep avails = foldr (filterAvail keep) [] avails
724
725 -- | filters an 'AvailInfo' by the given predicate
726 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
727 filterAvail keep ie rest =
728   case ie of
729     Avail n | keep n    -> ie : rest
730             | otherwise -> rest
731     AvailTC tc ns ->
732         let left = filter keep ns in
733         if null left then rest else AvailTC tc left : rest
734
735 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
736 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
737 gresFromIE decl_spec (L loc ie, avail)
738   = gresFromAvail prov_fn avail
739   where
740     is_explicit = case ie of
741                     IEThingAll name -> \n -> n == name
742                     _               -> \_ -> True
743     prov_fn name = Imported [imp_spec]
744         where
745           imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
746           item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
747
748 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
749 mkChildEnv gres = foldr add emptyNameEnv gres
750     where
751         add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_Acc (:) singleton env p n
752         add _                                            env = env
753
754 findChildren :: NameEnv [Name] -> Name -> [Name]
755 findChildren env n = lookupNameEnv env n `orElse` []
756 \end{code}
757
758 ---------------------------------------
759         AvailEnv and friends
760
761 All this AvailEnv stuff is hardly used; only in a very small
762 part of RnNames.  Todo: remove?
763 ---------------------------------------
764
765 \begin{code}
766 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
767
768 emptyAvailEnv :: AvailEnv
769 emptyAvailEnv = emptyNameEnv
770
771 {- Dead code
772 unitAvailEnv :: AvailInfo -> AvailEnv
773 unitAvailEnv a = unitNameEnv (availName a) a
774
775 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
776 plusAvailEnv = plusNameEnv_C plusAvail
777
778 availEnvElts :: AvailEnv -> [AvailInfo]
779 availEnvElts = nameEnvElts
780 -}
781
782 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
783 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
784
785 mkAvailEnv :: [AvailInfo] -> AvailEnv
786         -- 'avails' may have several items with the same availName
787         -- E.g  import Ix( Ix(..), index )
788         -- will give Ix(Ix,index,range) and Ix(index)
789         -- We want to combine these; addAvail does that
790 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
791
792 -- After combining the avails, we need to ensure that the parent name is the
793 -- first entry in the list of subnames, if it is included at all.  (Subsequent
794 -- functions rely on that.)
795 normaliseAvail :: AvailInfo -> AvailInfo
796 normaliseAvail avail@(Avail _)     = avail
797 normaliseAvail (AvailTC name subs) = AvailTC name subs'
798   where
799     subs' = if name `elem` subs then name : (delete name subs) else subs
800
801 -- | combines 'AvailInfo's from the same family
802 nubAvails :: [AvailInfo] -> [AvailInfo]
803 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
804 \end{code}
805
806
807 %************************************************************************
808 %*                                                                      *
809 \subsection{Export list processing}
810 %*                                                                      *
811 %************************************************************************
812
813 Processing the export list.
814
815 You might think that we should record things that appear in the export
816 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
817 wrong.  We do check (here) that they are in scope, but there is no
818 need to slurp in their actual declaration (which is what
819 @addOccurrenceName@ forces).
820
821 Indeed, doing so would big trouble when compiling @PrelBase@, because
822 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
823 @ConcBase.StateAndSynchVar#@, and so on...
824
825 \begin{code}
826 type ExportAccum        -- The type of the accumulating parameter of
827                         -- the main worker function in rnExports
828      = ([LIE Name],             -- Export items with Names
829         ExportOccMap,           -- Tracks exported occurrence names
830         [AvailInfo])            -- The accumulated exported stuff
831                                 --   Not nub'd!
832
833 emptyExportAccum :: ExportAccum
834 emptyExportAccum = ([], emptyOccEnv, []) 
835
836 type ExportOccMap = OccEnv (Name, IE RdrName)
837         -- Tracks what a particular exported OccName
838         --   in an export list refers to, and which item
839         --   it came from.  It's illegal to export two distinct things
840         --   that have the same occurrence name
841
842 rnExports :: Bool       -- False => no 'module M(..) where' header at all
843           -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
844           -> TcGblEnv
845           -> RnM TcGblEnv
846
847         -- Complains if two distinct exports have same OccName
848         -- Warns about identical exports.
849         -- Complains about exports items not in scope
850
851 rnExports explicit_mod exports 
852           tcg_env@(TcGblEnv { tcg_mod     = this_mod,
853                               tcg_rdr_env = rdr_env, 
854                               tcg_imports = imports })
855  = do   {  
856         -- If the module header is omitted altogether, then behave
857         -- as if the user had written "module Main(main) where..."
858         -- EXCEPT in interactive mode, when we behave as if he had
859         -- written "module Main where ..."
860         -- Reason: don't want to complain about 'main' not in scope
861         --         in interactive mode
862         ; dflags <- getDOpts
863         ; let real_exports 
864                  | explicit_mod = exports
865                  | ghcLink dflags == LinkInMemory = Nothing
866                  | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
867                         -- ToDo: the 'noLoc' here is unhelpful if 'main' 
868                         --       turns out to be out of scope
869
870         ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
871         ; let final_avails = nubAvails avails        -- Combine families
872         
873         ; return (tcg_env { tcg_exports    = final_avails,
874                             tcg_rn_exports = case tcg_rn_exports tcg_env of
875                                                 Nothing -> Nothing
876                                                 Just _  -> rn_exports,
877                             tcg_dus = tcg_dus tcg_env `plusDU` 
878                                       usesOnly (availsToNameSet final_avails) }) }
879
880 exports_from_avail :: Maybe [LIE RdrName]
881                          -- Nothing => no explicit export list
882                    -> GlobalRdrEnv
883                    -> ImportAvails
884                    -> Module
885                    -> RnM (Maybe [LIE Name], [AvailInfo])
886
887 exports_from_avail Nothing rdr_env _imports _this_mod
888  = -- The same as (module M) where M is the current module name,
889    -- so that's how we handle it.
890    let
891        avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
892                                  isLocalGRE gre ]
893    in
894    return (Nothing, avails)
895
896 exports_from_avail (Just rdr_items) rdr_env imports this_mod
897   = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
898
899        return (Just ie_names, exports)
900   where
901     do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
902     do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
903
904     kids_env :: NameEnv [Name]  -- Maps a parent to its in-scope children
905     kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
906
907     imported_modules = [ qual_name
908                        | xs <- moduleEnvElts $ imp_mods imports,
909                          (qual_name, _, _) <- xs ]
910
911     exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
912     exports_from_item acc@(ie_names, occs, exports) 
913                       (L loc ie@(IEModuleContents mod))
914         | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
915         , mod `elem` earlier_mods       -- Duplicate export of M
916         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
917                warnIf warn_dup_exports (dupModuleExport mod) ;
918                return acc }
919
920         | otherwise
921         = do { implicit_prelude <- doptM Opt_ImplicitPrelude
922              ; warnDodgyExports <- doptM Opt_WarnDodgyExports
923              ; let { exportValid = (mod `elem` imported_modules)
924                             || (moduleName this_mod == mod)
925                    ; gres = filter (isModuleExported implicit_prelude mod)
926                                    (globalRdrEnvElts rdr_env)
927                    ; names = map gre_name gres
928                    }
929
930              ; checkErr exportValid (moduleNotImported mod)
931              ; warnIf (warnDodgyExports && exportValid && null gres) (nullModuleExport mod)
932
933              ; addUsedRdrNames (concat [ [mkRdrQual mod occ, mkRdrUnqual occ]
934                                        | occ <- map nameOccName names ])
935                         -- The qualified and unqualified version of all of
936                         -- these names are, in effect, used by this export
937
938              ; occs' <- check_occs ie occs names
939                       -- This check_occs not only finds conflicts
940                       -- between this item and others, but also
941                       -- internally within this item.  That is, if
942                       -- 'M.x' is in scope in several ways, we'll have
943                       -- several members of mod_avails with the same
944                       -- OccName.
945              ; return (L loc (IEModuleContents mod) : ie_names,
946                        occs', map greAvail gres ++ exports) }
947
948     exports_from_item acc@(lie_names, occs, exports) (L loc ie)
949         | isDoc ie
950         = do new_ie <- lookup_doc_ie ie
951              return (L loc new_ie : lie_names, occs, exports)
952
953         | otherwise
954         = do (new_ie, avail) <- lookup_ie ie
955              if isUnboundName (ieName new_ie)
956                   then return acc       -- Avoid error cascade
957                   else do
958
959              occs' <- check_occs ie occs (availNames avail)
960
961              return (L loc new_ie : lie_names, occs', avail : exports)
962
963     -------------
964     lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
965     lookup_ie (IEVar rdr) 
966         = do gre <- lookupGreRn rdr
967              return (IEVar (gre_name gre), greAvail gre)
968
969     lookup_ie (IEThingAbs rdr) 
970         = do gre <- lookupGreRn rdr
971              let name = gre_name gre
972              case gre_par gre of
973                 NoParent   -> return (IEThingAbs name, 
974                                       AvailTC name [name])
975                 ParentIs p -> return (IEThingAbs name, 
976                                       AvailTC p [name])
977
978     lookup_ie ie@(IEThingAll rdr) 
979         = do name <- lookupGlobalOccRn rdr
980              let kids = findChildren kids_env name
981                  mkKidRdrName = case isQual_maybe rdr of
982                                 Nothing -> mkRdrUnqual
983                                 Just (modName, _) -> mkRdrQual modName
984              addUsedRdrNames $ map (mkKidRdrName . nameOccName) kids
985              warnDodgyExports <- doptM Opt_WarnDodgyExports
986              when (null kids) $
987                   if isTyConName name
988                   then when warnDodgyExports $ addWarn (dodgyExportWarn name)
989                   else -- This occurs when you export T(..), but
990                        -- only import T abstractly, or T is a synonym.  
991                        addErr (exportItemErr ie)
992
993              return (IEThingAll name, AvailTC name (name:kids))
994
995     lookup_ie ie@(IEThingWith rdr sub_rdrs)
996         = do name <- lookupGlobalOccRn rdr
997              if isUnboundName name
998                 then return (IEThingWith name [], AvailTC name [name])
999                 else do
1000              let env = mkOccEnv [ (nameOccName s, s) 
1001                                 | s <- findChildren kids_env name ]
1002                  mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
1003              if any isNothing mb_names
1004                 then do addErr (exportItemErr ie)
1005                         return (IEThingWith name [], AvailTC name [name])
1006                 else do let names = catMaybes mb_names
1007                         optTyFam <- doptM Opt_TypeFamilies
1008                         when (not optTyFam && any isTyConName names) $
1009                           addErr (typeItemErr ( head
1010                                               . filter isTyConName 
1011                                               $ names )
1012                                               (text "in export list"))
1013                         return (IEThingWith name names, AvailTC name (name:names))
1014
1015     lookup_ie _ = panic "lookup_ie"     -- Other cases covered earlier
1016
1017     -------------
1018     lookup_doc_ie :: IE RdrName -> RnM (IE Name)
1019     lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
1020                                          return (IEGroup lev rn_doc)
1021     lookup_doc_ie (IEDoc doc)       = do rn_doc <- rnHsDoc doc
1022                                          return (IEDoc rn_doc)
1023     lookup_doc_ie (IEDocNamed str)  = return (IEDocNamed str)
1024     lookup_doc_ie _ = panic "lookup_doc_ie"     -- Other cases covered earlier
1025
1026
1027 isDoc :: IE RdrName -> Bool
1028 isDoc (IEDoc _)      = True
1029 isDoc (IEDocNamed _) = True
1030 isDoc (IEGroup _ _)  = True
1031 isDoc _ = False
1032
1033 -------------------------------
1034 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
1035 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
1036 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
1037   | implicit_prelude && isBuiltInSyntax name = False
1038         -- Optimisation: filter out names for built-in syntax
1039         -- They just clutter up the environment (esp tuples), and the parser
1040         -- will generate Exact RdrNames for them, so the cluttered
1041         -- envt is no use.  To avoid doing this filter all the time,
1042         -- we use -XNoImplicitPrelude as a clue that the filter is
1043         -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
1044         --
1045         -- It's worth doing because it makes the environment smaller for
1046         -- every module that imports the Prelude
1047   | otherwise
1048   = case prov of
1049         LocalDef | Just name_mod <- nameModule_maybe name
1050                  -> moduleName name_mod == mod
1051                  | otherwise -> False
1052         Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1053
1054 -------------------------------
1055 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1056 check_occs ie occs names
1057   = foldlM check occs names
1058   where
1059     check occs name
1060       = case lookupOccEnv occs name_occ of
1061           Nothing -> return (extendOccEnv occs name_occ (name, ie))
1062
1063           Just (name', ie') 
1064             | name == name'     -- Duplicate export
1065             ->  do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
1066                      warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
1067                      return occs }
1068
1069             | otherwise         -- Same occ name but different names: an error
1070             ->  do { global_env <- getGlobalRdrEnv ;
1071                      addErr (exportClashErr global_env name' name ie' ie) ;
1072                      return occs }
1073       where
1074         name_occ = nameOccName name
1075 \end{code}
1076
1077 %*********************************************************
1078 %*                                                       *
1079                 Deprecations
1080 %*                                                       *
1081 %*********************************************************
1082
1083 \begin{code}
1084 finishWarnings :: DynFlags -> Maybe WarningTxt 
1085                -> TcGblEnv -> RnM TcGblEnv
1086 -- (a) Report usage of imports that are deprecated or have other warnings
1087 -- (b) If the whole module is warned about or deprecated, update tcg_warns
1088 --     All this happens only once per module
1089 finishWarnings dflags mod_warn tcg_env
1090   = do  { (eps,hpt) <- getEpsAndHpt
1091         ; ifOptM Opt_WarnWarningsDeprecations $
1092           mapM_ (check hpt (eps_PIT eps)) all_gres
1093                 -- By this time, typechecking is complete, 
1094                 -- so the PIT is fully populated
1095
1096         -- Deal with a module deprecation; it overrides all existing warns
1097         ; let new_warns = case mod_warn of
1098                                 Just txt -> WarnAll txt
1099                                 Nothing  -> tcg_warns tcg_env
1100         ; return (tcg_env { tcg_warns = new_warns }) }
1101   where
1102     used_names = allUses (tcg_dus tcg_env) 
1103         -- Report on all deprecated uses; hence allUses
1104     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
1105
1106     check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1107       | name `elemNameSet` used_names
1108       , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1109       = addWarnAt (importSpecLoc imp_spec)
1110                   (sep [ptext (sLit "In the use of") <+> 
1111                         pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
1112                         quotes (ppr name),
1113                       (parens imp_msg) <> colon,
1114                       (ppr deprec_txt) ])
1115         where
1116           name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1117           imp_mod  = importSpecModule imp_spec
1118           imp_msg  = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1119           extra | imp_mod == moduleName name_mod = empty
1120                 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1121
1122     check _ _ _ = return ()     -- Local, or not used, or not deprectated
1123             -- The Imported pattern-match: don't deprecate locally defined names
1124             -- For a start, we may be exporting a deprecated thing
1125             -- Also we may use a deprecated thing in the defn of another
1126             -- deprecated things.  We may even use a deprecated thing in
1127             -- the defn of a non-deprecated thing, when changing a module's 
1128             -- interface
1129
1130 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable 
1131                 -> GlobalRdrElt -> Maybe WarningTxt
1132 -- The name is definitely imported, so look in HPT, PIT
1133 lookupImpDeprec dflags hpt pit gre
1134   = case lookupIfaceByModule dflags hpt pit mod of
1135         Just iface -> mi_warn_fn iface name `mplus`     -- Bleat if the thing, *or
1136                       case gre_par gre of       
1137                         ParentIs p -> mi_warn_fn iface p        -- its parent*, is warn'd
1138                         NoParent   -> Nothing
1139
1140         Nothing -> Nothing      -- See Note [Used names with interface not loaded]
1141   where
1142     name = gre_name gre
1143     mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1144 \end{code}
1145
1146 Note [Used names with interface not loaded]
1147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1148 By now all the interfaces should have been loaded,
1149 because reportDeprecations happens after typechecking.
1150 However, it's still (just) possible to to find a used 
1151 Name whose interface hasn't been loaded:
1152
1153 a) It might be a WiredInName; in that case we may not load 
1154    its interface (although we could).
1155
1156 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1157    These are seen as "used" by the renamer (if -XNoImplicitPrelude) 
1158    is on), but the typechecker may discard their uses 
1159    if in fact the in-scope fromRational is GHC.Read.fromRational,
1160    (see tcPat.tcOverloadedLit), and the typechecker sees that the type 
1161    is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1162    In that obscure case it won't force the interface in.
1163
1164 In both cases we simply don't permit deprecations; 
1165 this is, after all, wired-in stuff.
1166
1167
1168 %*********************************************************
1169 %*                                                       *
1170                 Unused names
1171 %*                                                       *
1172 %*********************************************************
1173
1174 \begin{code}
1175 reportUnusedNames :: Maybe [LIE RdrName]        -- Export list
1176                   -> TcGblEnv -> RnM ()
1177 reportUnusedNames _export_decls gbl_env 
1178   = do  { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1179         ; warnUnusedImportDecls gbl_env
1180         ; warnUnusedTopBinds   unused_locals }
1181   where
1182     used_names :: NameSet
1183     used_names = findUses (tcg_dus gbl_env) emptyNameSet
1184         -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1185         -- Hence findUses
1186
1187         -- Collect the defined names from the in-scope environment
1188     defined_names :: [GlobalRdrElt]
1189     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1190
1191         -- Note that defined_and_used, defined_but_not_used
1192         -- are both [GRE]; that's why we need defined_and_used
1193         -- rather than just used_names
1194     _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1195     (_defined_and_used, defined_but_not_used) 
1196         = partition (gre_is_used used_names) defined_names
1197     
1198     kids_env = mkChildEnv defined_names
1199         -- This is done in mkExports too; duplicated work
1200
1201     gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1202     gre_is_used used_names (GRE {gre_name = name})
1203         = name `elemNameSet` used_names
1204           || any (`elemNameSet` used_names) (findChildren kids_env name)
1205                 -- A use of C implies a use of T,
1206                 -- if C was brought into scope by T(..) or T(C)
1207
1208         -- Filter out the ones that are 
1209         --  (a) defined in this module, and
1210         --  (b) not defined by a 'deriving' clause 
1211         -- The latter have an Internal Name, so we can filter them out easily
1212     unused_locals :: [GlobalRdrElt]
1213     unused_locals = filter is_unused_local defined_but_not_used
1214     is_unused_local :: GlobalRdrElt -> Bool
1215     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1216 \end{code}
1217
1218 %*********************************************************
1219 %*                                                       *
1220                 Unused imports
1221 %*                                                       *
1222 %*********************************************************
1223
1224 This code finds which import declarations are unused.  The 
1225 specification and implementation notes are here:
1226   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1227
1228 \begin{code}
1229 type ImportDeclUsage 
1230    = ( LImportDecl Name   -- The import declaration
1231      , [AvailInfo]        -- What *is* used (normalised)
1232      , [Name] )           -- What is imported but *not* used
1233 \end{code}
1234
1235 \begin{code}
1236 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1237 warnUnusedImportDecls gbl_env
1238   = do { uses <- readMutVar (tcg_used_rdrnames gbl_env)
1239        ; let imports = filter explicit_import (tcg_rn_imports gbl_env)
1240              rdr_env = tcg_rdr_env gbl_env
1241
1242        ; let usage :: [ImportDeclUsage]
1243              usage = findImportUsage imports rdr_env (Set.elems uses)
1244
1245        ; ifOptM Opt_WarnUnusedImports $
1246          mapM_ warnUnusedImport usage
1247
1248        ; ifOptM Opt_D_dump_minimal_imports $
1249          printMinimalImports usage }
1250   where
1251     explicit_import (L loc _) = isGoodSrcSpan loc
1252         -- Filter out the implicit Prelude import
1253         -- which we do not want to bleat about
1254 \end{code}
1255
1256 \begin{code}
1257 findImportUsage :: [LImportDecl Name]
1258                 -> GlobalRdrEnv
1259                 -> [RdrName]
1260                 -> [ImportDeclUsage]
1261
1262 type ImportMap = Map SrcLoc [AvailInfo]
1263   -- The intermediate data struture records, for each import 
1264   -- declaration, what stuff brought into scope by that 
1265   -- declaration is actually used in the module.
1266   --
1267   -- The SrcLoc is the location of the start 
1268   -- of a particular 'import' declaration
1269   -- 
1270   -- The AvailInfos are the things imported from that decl
1271   -- (just a list, not normalised)
1272
1273 findImportUsage imports rdr_env rdrs
1274   = map unused_decl imports
1275   where
1276     import_usage :: ImportMap
1277     import_usage = foldr (addUsedRdrName rdr_env) Map.empty rdrs
1278
1279     unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1280       = (decl, nubAvails used_avails, unused_imps)
1281       where
1282         used_avails = Map.lookup (srcSpanStart loc) import_usage `orElse` []
1283         dont_report_as_unused = foldr add emptyNameSet used_avails
1284         add (Avail n) s = s `addOneToNameSet` n
1285         add (AvailTC n ns) s = s `addListToNameSet` (n:ns)
1286                 -- If you use 'signum' from Num, then the user may well have
1287                 -- imported Num(signum).  We don't want to complain that
1288                 -- Num is not itself mentioned.  Hence adding 'n' as
1289                 -- well to the list of of "don't report if unused" names
1290                                       
1291         unused_imps = case imps of
1292                         Just (False, imp_ies) -> nameSetToList unused_imps
1293                           where
1294                             imp_names = mkNameSet (concatMap (ieNames . unLoc) imp_ies)
1295                             unused_imps = imp_names `minusNameSet` dont_report_as_unused
1296                             
1297                         _other -> []    -- No explicit import list => no unused-name list
1298                         
1299 addUsedRdrName :: GlobalRdrEnv -> RdrName -> ImportMap -> ImportMap
1300 -- For a used RdrName, find all the import decls that brought
1301 -- it into scope; choose one of them (bestImport), and record
1302 -- the RdrName in that import decl's entry in the ImportMap
1303 addUsedRdrName rdr_env rdr imp_map
1304   | [gre] <- lookupGRE_RdrName rdr rdr_env
1305   , Imported imps <- gre_prov gre
1306   = add_imp gre (bestImport imps) imp_map
1307   | otherwise
1308   = imp_map
1309   where
1310     add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1311     add_imp gre (ImpSpec { is_decl = imp_decl_spec }) imp_map
1312       = Map.insertWith add decl_loc [avail] imp_map
1313       where
1314         add _ avails = avail : avails -- add is really just a specialised (++)
1315         decl_loc = srcSpanStart (is_dloc imp_decl_spec)
1316         name     = gre_name gre
1317         avail    = case gre_par gre of
1318                       ParentIs p                  -> AvailTC p [name]
1319                       NoParent | isTyConName name -> AvailTC name [name]
1320                                | otherwise        -> Avail name
1321
1322     bestImport :: [ImportSpec] -> ImportSpec
1323     bestImport iss
1324       = case partition isImpAll iss of
1325           ([], imp_somes) -> textuallyFirst imp_somes
1326           (imp_alls, _)   -> textuallyFirst imp_alls
1327
1328     textuallyFirst :: [ImportSpec] -> ImportSpec
1329     textuallyFirst iss = case sortWith (is_dloc . is_decl) iss of
1330                         []     -> pprPanic "textuallyFirst" (ppr iss)
1331                         (is:_) -> is
1332
1333     isImpAll :: ImportSpec -> Bool
1334     isImpAll (ImpSpec { is_item = ImpAll }) = True
1335     isImpAll _other                         = False
1336 \end{code}
1337
1338 \begin{code}
1339 warnUnusedImport :: ImportDeclUsage -> RnM ()
1340 warnUnusedImport (L loc decl, used, unused)
1341   | Just (False,[]) <- ideclHiding decl
1342                 = return ()            -- Do not warn for 'import M()'
1343   | null used   = addWarnAt loc msg1   -- Nothing used; drop entire decl
1344   | null unused = return ()            -- Everything imported is used; nop
1345   | otherwise   = addWarnAt loc msg2   -- Some imports are unused
1346   where
1347     msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1348                  nest 2 (ptext (sLit "except perhaps to import instances from")
1349                                    <+> quotes pp_mod),
1350                  ptext (sLit "To import instances alone, use:")
1351                                    <+> ptext (sLit "import") <+> pp_mod <> parens empty ]
1352     msg2 = sep [pp_herald <+> quotes (pprWithCommas ppr unused),
1353                     text "from module" <+> quotes pp_mod <+> pp_not_used]
1354     pp_herald   = text "The import of"
1355     pp_mod      = ppr (unLoc (ideclName decl))
1356     pp_not_used = text "is redundant"
1357 \end{code}
1358
1359 To print the minimal imports we walk over the user-supplied import
1360 decls, and simply trim their import lists.  NB that
1361
1362   * We do *not* change the 'qualified' or 'as' parts!
1363
1364   * We do not disard a decl altogether; we might need instances
1365     from it.  Instead we just trim to an empty import list
1366
1367 \begin{code}
1368 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1369 printMinimalImports imports_w_usage
1370   = do { imports' <- mapM mk_minimal imports_w_usage
1371        ; this_mod <- getModule
1372        ; liftIO $ 
1373          do { h <- openFile (mkFilename this_mod) WriteMode
1374             ; printForUser h neverQualify (vcat (map ppr imports')) }
1375                 -- The neverQualify is important.  We are printing Names
1376                 -- but they are in the context of an 'import' decl, and
1377                 -- we never qualify things inside there
1378                 -- E.g.   import Blag( f, b )
1379                 -- not    import Blag( Blag.f, Blag.g )!
1380        }
1381   where
1382     mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1383
1384     mk_minimal (L l decl, used, unused)
1385       | null unused
1386       , Just (False, _) <- ideclHiding decl
1387       = return (L l decl)
1388       | otherwise
1389       = do { let ImportDecl { ideclName    = L _ mod_name
1390                             , ideclSource  = is_boot
1391                             , ideclPkgQual = mb_pkg } = decl
1392            ; iface <- loadSrcInterface doc mod_name is_boot mb_pkg
1393            ; let lies = map (L l) (concatMap (to_ie iface) used)
1394            ; return (L l (decl { ideclHiding = Just (False, lies) })) }
1395       where
1396         doc = text "Compute minimal imports for" <+> ppr decl
1397
1398     to_ie :: ModIface -> AvailInfo -> [IE Name]
1399         -- The main trick here is that if we're importing all the constructors
1400         -- we want to say "T(..)", but if we're importing only a subset we want
1401         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1402     to_ie _ (Avail n) 
1403        = [IEVar n]
1404     to_ie _ (AvailTC n [m]) 
1405        | n==m = [IEThingAbs n]
1406     to_ie iface (AvailTC n ns)  
1407       = case [xs | (m,as) <- mi_exports iface
1408                  , m == n_mod
1409                  , AvailTC x xs <- as
1410                  , x == nameOccName n
1411                  , x `elem` xs  -- Note [Partial export]
1412                  ] of
1413            [xs] | all_used xs -> [IEThingAll n]
1414                 | otherwise   -> [IEThingWith n (filter (/= n) ns)]
1415            _other             -> (map IEVar ns)
1416         where
1417           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1418           n_mod = ASSERT( isExternalName n ) nameModule n
1419 \end{code}
1420
1421 Note [Partial export]
1422 ~~~~~~~~~~~~~~~~~~~~~
1423 Suppose we have 
1424
1425    module A( op ) where
1426      class C a where
1427        op :: a -> a
1428
1429    module B where
1430    import A
1431    f = ..op...
1432
1433 Then the minimal import for module B is
1434    import A( op )
1435 not
1436    import A( C( op ) )
1437 which we would usually generate if C was exported from B.  Hence
1438 the (x `elem` xs) test when deciding what to generate.
1439
1440
1441 %************************************************************************
1442 %*                                                                      *
1443 \subsection{Errors}
1444 %*                                                                      *
1445 %************************************************************************
1446
1447 \begin{code}
1448 qualImportItemErr :: RdrName -> SDoc
1449 qualImportItemErr rdr
1450   = hang (ptext (sLit "Illegal qualified name in import item:"))
1451        2 (ppr rdr)
1452
1453 badImportItemErr :: ModIface -> ImpDeclSpec -> IE RdrName -> SDoc
1454 badImportItemErr iface decl_spec ie
1455   = sep [ptext (sLit "Module"), quotes (ppr (is_mod decl_spec)), source_import,
1456          ptext (sLit "does not export"), quotes (ppr ie)]
1457   where
1458     source_import | mi_boot iface = ptext (sLit "(hi-boot interface)")
1459                   | otherwise     = empty
1460
1461 illegalImportItemErr :: SDoc
1462 illegalImportItemErr = ptext (sLit "Illegal import item")
1463
1464 dodgyImportWarn :: RdrName -> SDoc
1465 dodgyImportWarn item = dodgyMsg (ptext (sLit "import")) item
1466 dodgyExportWarn :: Name -> SDoc
1467 dodgyExportWarn item = dodgyMsg (ptext (sLit "export")) item
1468
1469 dodgyMsg :: OutputableBndr n => SDoc -> n -> SDoc
1470 dodgyMsg kind tc
1471   = sep [ ptext (sLit "The") <+> kind <+> ptext (sLit "item") <+> quotes (ppr (IEThingAll tc))
1472                 <+> ptext (sLit "suggests that"),
1473           quotes (ppr tc) <+> ptext (sLit "has (in-scope) constructors or class methods,"),
1474           ptext (sLit "but it has none") ]
1475
1476 exportItemErr :: IE RdrName -> SDoc
1477 exportItemErr export_item
1478   = sep [ ptext (sLit "The export item") <+> quotes (ppr export_item),
1479           ptext (sLit "attempts to export constructors or class methods that are not visible here") ]
1480
1481 typeItemErr :: Name -> SDoc -> SDoc
1482 typeItemErr name wherestr
1483   = sep [ ptext (sLit "Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1484           ptext (sLit "Use -XTypeFamilies to enable this extension") ]
1485
1486 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1487                -> Message
1488 exportClashErr global_env name1 name2 ie1 ie2
1489   = vcat [ ptext (sLit "Conflicting exports for") <+> quotes (ppr occ) <> colon
1490          , ppr_export ie1' name1'
1491          , ppr_export ie2' name2' ]
1492   where
1493     occ = nameOccName name1
1494     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext (sLit "exports") <+> 
1495                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1496
1497         -- get_gre finds a GRE for the Name, so that we can show its provenance
1498     get_gre name
1499         = case lookupGRE_Name global_env name of
1500              (gre:_) -> gre
1501              []      -> pprPanic "exportClashErr" (ppr name)
1502     get_loc name = nameSrcLoc $ gre_name $ get_gre name
1503     (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1504                                    then (name1, ie1, name2, ie2)
1505                                    else (name2, ie2, name1, ie1)
1506
1507 addDupDeclErr :: [Name] -> TcRn ()
1508 addDupDeclErr []
1509   = panic "addDupDeclErr: empty list"
1510 addDupDeclErr names@(name : _)
1511   = addErrAt (getSrcSpan (last sorted_names)) $
1512         -- Report the error at the later location
1513     vcat [ptext (sLit "Multiple declarations of") <+> quotes (ppr name),
1514           ptext (sLit "Declared at:") <+> vcat (map (ppr . nameSrcLoc) sorted_names)]
1515   where
1516     sorted_names = sortWith nameSrcLoc names
1517
1518 dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
1519 dupExportWarn occ_name ie1 ie2
1520   = hsep [quotes (ppr occ_name), 
1521           ptext (sLit "is exported by"), quotes (ppr ie1),
1522           ptext (sLit "and"),            quotes (ppr ie2)]
1523
1524 dupModuleExport :: ModuleName -> SDoc
1525 dupModuleExport mod
1526   = hsep [ptext (sLit "Duplicate"),
1527           quotes (ptext (sLit "Module") <+> ppr mod), 
1528           ptext (sLit "in export list")]
1529
1530 moduleNotImported :: ModuleName -> SDoc
1531 moduleNotImported mod
1532   = ptext (sLit "The export item `module") <+> ppr mod <>
1533     ptext (sLit "' is not imported")
1534
1535 nullModuleExport :: ModuleName -> SDoc
1536 nullModuleExport mod
1537   = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' exports nothing")
1538
1539 missingImportListWarn :: ModuleName -> SDoc
1540 missingImportListWarn mod
1541   = ptext (sLit "The module") <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1542
1543 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1544 moduleWarn mod (WarningTxt txt)
1545   = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <> ptext (sLit ":"), 
1546           nest 2 (vcat (map ppr txt)) ]
1547 moduleWarn mod (DeprecatedTxt txt)
1548   = sep [ ptext (sLit "Module") <+> quotes (ppr mod)
1549                                 <+> ptext (sLit "is deprecated:"), 
1550           nest 2 (vcat (map ppr txt)) ]
1551
1552 implicitPreludeWarn :: SDoc
1553 implicitPreludeWarn
1554   = ptext (sLit "Module `Prelude' implicitly imported")
1555
1556 packageImportErr :: SDoc
1557 packageImportErr
1558   = ptext (sLit "Package-qualified imports are not enabled; use -XPackageImports")
1559 \end{code}