Fix export of associated families with new name parent story
[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, importsFromLocalDecls,
9         rnExports,
10         getLocalDeclBinders, extendRdrEnvRn,
11         reportUnusedNames, reportDeprecations
12     ) where
13
14 #include "HsVersions.h"
15
16 import DynFlags         ( DynFlag(..), GhcMode(..), DynFlags(..) )
17 import HsSyn            ( IE(..), ieName, ImportDecl(..), LImportDecl,
18                           ForeignDecl(..), HsGroup(..), HsValBinds(..),
19                           Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
20                           instDeclATs, isIdxTyDecl,
21                           LIE )
22 import RnEnv
23 import RnHsDoc          ( rnHsDoc )
24 import IfaceEnv         ( ifaceExportNames )
25 import LoadIface        ( loadSrcInterface )
26 import TcRnMonad hiding (LIE)
27
28 import PrelNames
29 import Module
30 import Name
31 import NameEnv
32 import NameSet
33 import OccName          ( srcDataName, pprNonVarNameSpace,
34                           occNameSpace,
35                           OccEnv, mkOccEnv, mkOccEnv_C, lookupOccEnv,
36                           emptyOccEnv, extendOccEnv )
37 import HscTypes         ( GenAvailInfo(..), AvailInfo, availNames, availName,
38                           HomePackageTable, PackageIfaceTable, 
39                           mkPrintUnqualified, availsToNameSet,
40                           Deprecs(..), ModIface(..), Dependencies(..), 
41                           lookupIfaceByModule, ExternalPackageState(..)
42                         )
43 import RdrName          ( RdrName, rdrNameOcc, setRdrNameSpace, Parent(..),
44                           GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..), 
45                           emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
46                           extendGlobalRdrEnv, lookupGlobalRdrEnv,
47                           lookupGRE_RdrName, lookupGRE_Name, 
48                           Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), 
49                           importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance,
50                           unQualSpecOK, qualSpecOK )
51 import Outputable
52 import Maybes
53 import SrcLoc           ( Located(..), mkGeneralSrcSpan, getLoc,
54                           unLoc, noLoc, srcLocSpan, SrcSpan )
55 import FiniteMap
56 import ErrUtils
57 import BasicTypes       ( DeprecTxt )
58 import DriverPhases     ( isHsBoot )
59 import Util
60 import ListSetOps
61 import Data.List        ( partition, concatMap, (\\) )
62 import IO               ( openFile, IOMode(..) )
63 import Monad            ( when )
64 \end{code}
65
66
67
68 %************************************************************************
69 %*                                                                      *
70                 rnImports
71 %*                                                                      *
72 %************************************************************************
73
74 \begin{code}
75 rnImports :: [LImportDecl RdrName]
76            -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails)
77
78 rnImports imports
79          -- PROCESS IMPORT DECLS
80          -- Do the non {- SOURCE -} ones first, so that we get a helpful
81          -- warning for {- SOURCE -} ones that are unnecessary
82     = do this_mod <- getModule
83          implicit_prelude <- doptM Opt_ImplicitPrelude
84          let all_imports               = mk_prel_imports this_mod implicit_prelude ++ imports
85              (source, ordinary) = partition is_source_import all_imports
86              is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
87
88          stuff1 <- mapM (rnImportDecl this_mod) ordinary
89          stuff2 <- mapM (rnImportDecl this_mod) source
90          let (decls, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)
91          return (decls, rdr_env, imp_avails) 
92
93     where
94 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
95 -- because the former doesn't even look at Prelude.hi for instance 
96 -- declarations, whereas the latter does.
97    mk_prel_imports this_mod implicit_prelude
98        |  this_mod == pRELUDE
99           || explicit_prelude_import
100           || not implicit_prelude
101            = []
102        | otherwise = [preludeImportDecl]
103    explicit_prelude_import
104        = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports, 
105                    unLoc mod == pRELUDE_NAME ]
106
107    combine :: [(LImportDecl Name,  GlobalRdrEnv, ImportAvails)]
108            -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails)
109    combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails)
110         where plus (decl,  gbl_env1, imp_avails1)
111                    (decls, gbl_env2, imp_avails2)
112                 = (decl:decls, 
113                    gbl_env1 `plusGlobalRdrEnv` gbl_env2,
114                    imp_avails1 `plusImportAvails` imp_avails2)
115
116 preludeImportDecl :: LImportDecl RdrName
117 preludeImportDecl
118   = L loc $
119         ImportDecl (L loc pRELUDE_NAME)
120                False {- Not a boot interface -}
121                False    {- Not qualified -}
122                Nothing  {- No "as" -}
123                Nothing  {- No import list -}
124   where
125     loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")         
126
127         
128
129 rnImportDecl  :: Module
130               -> LImportDecl RdrName
131               -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails)
132
133 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
134                                          qual_only as_mod imp_details))
135   = 
136     setSrcSpan loc $ do
137
138         -- If there's an error in loadInterface, (e.g. interface
139         -- file not found) we get lots of spurious errors from 'filterImports'
140     let
141         imp_mod_name = unLoc loc_imp_mod_name
142         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
143
144     iface <- loadSrcInterface doc imp_mod_name want_boot
145
146         -- Compiler sanity check: if the import didn't say
147         -- {-# SOURCE #-} we should not get a hi-boot file
148     WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
149
150         -- Issue a user warning for a redundant {- SOURCE -} import
151         -- NB that we arrange to read all the ordinary imports before 
152         -- any of the {- SOURCE -} imports
153     warnIf (want_boot && not (mi_boot iface))
154            (warnRedundantSourceImport imp_mod_name)
155
156     let
157         imp_mod    = mi_module iface
158         deprecs    = mi_deprecs iface
159         is_orph    = mi_orphan iface 
160         has_finsts = mi_finsts iface 
161         deps       = mi_deps iface
162
163         filtered_exports = filter not_this_mod (mi_exports iface)
164         not_this_mod (mod,_) = mod /= this_mod
165         -- If the module exports anything defined in this module, just
166         -- ignore it.  Reason: otherwise it looks as if there are two
167         -- local definition sites for the thing, and an error gets
168         -- reported.  Easiest thing is just to filter them out up
169         -- front. This situation only arises if a module imports
170         -- itself, or another module that imported it.  (Necessarily,
171         -- this invoves a loop.)
172         --
173         -- Tiresome consequence: if you say
174         --      module A where
175         --         import B( AType )
176         --         type AType = ...
177         --
178         --      module B( AType ) where
179         --         import {-# SOURCE #-} A( AType )
180         --
181         -- then you'll get a 'B does not export AType' message.  Oh well.
182
183         qual_mod_name = case as_mod of
184                           Nothing           -> imp_mod_name
185                           Just another_name -> another_name
186         imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
187                                   is_dloc = loc, is_as = qual_mod_name }
188     -- in
189
190         -- Get the total exports from this module
191     total_avails <- ifaceExportNames filtered_exports
192
193         -- filter the imports according to the import declaration
194     (new_imp_details, gbl_env) <- 
195         filterImports2 iface imp_spec imp_details total_avails
196
197     dflags <- getDOpts
198
199     let
200         -- Compute new transitive dependencies
201
202         orphans | is_orph   = ASSERT( not (imp_mod `elem` dep_orphs deps) )
203                               imp_mod : dep_orphs deps
204                 | otherwise = dep_orphs deps
205
206         finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
207                               imp_mod : dep_finsts deps
208                 | otherwise = dep_finsts deps
209
210         pkg = modulePackageId (mi_module iface)
211
212         (dependent_mods, dependent_pkgs) 
213            | pkg == thisPackage dflags =
214                 -- Imported module is from the home package
215                 -- Take its dependent modules and add imp_mod itself
216                 -- Take its dependent packages unchanged
217                 --
218                 -- NB: (dep_mods deps) might include a hi-boot file
219                 -- for the module being compiled, CM. Do *not* filter
220                 -- this out (as we used to), because when we've
221                 -- finished dealing with the direct imports we want to
222                 -- know if any of them depended on CM.hi-boot, in
223                 -- which case we should do the hi-boot consistency
224                 -- check.  See LoadIface.loadHiBootInterface
225                   ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
226
227            | otherwise =
228                 -- Imported module is from another package
229                 -- Dump the dependent modules
230                 -- Add the package imp_mod comes from to the dependent packages
231                  ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
232                  ([], pkg : dep_pkgs deps)
233
234         -- True <=> import M ()
235         import_all = case imp_details of
236                         Just (is_hiding, ls) -> not is_hiding && null ls        
237                         other                -> False
238
239         imports   = ImportAvails { 
240                         imp_mods     = unitModuleEnv imp_mod (imp_mod, import_all, loc),
241                         imp_orphs    = orphans,
242                         imp_finsts   = finsts,
243                         imp_dep_mods = mkModDeps dependent_mods,
244                         imp_dep_pkgs = dependent_pkgs
245                    }
246
247         -- Complain if we import a deprecated module
248     ifOptM Opt_WarnDeprecations (
249        case deprecs of  
250           DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
251           other         -> returnM ()
252      )
253
254     let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
255                                          qual_only as_mod new_imp_details)
256
257     returnM (new_imp_decl, gbl_env, imports)
258     )
259
260 warnRedundantSourceImport mod_name
261   = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
262           <+> quotes (ppr mod_name)
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268                 importsFromLocalDecls
269 %*                                                                      *
270 %************************************************************************
271
272 From the top-level declarations of this module produce
273         * the lexical environment
274         * the ImportAvails
275 created by its bindings.  
276         
277 Complain about duplicate bindings
278
279 \begin{code}
280 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
281 importsFromLocalDecls group
282   = do  { gbl_env  <- getGblEnv
283
284         ; avails <- getLocalDeclBinders gbl_env group
285
286         ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) avails
287
288         ; traceRn (text "local avails: " <> ppr avails)
289
290         ; returnM (gbl_env { tcg_rdr_env = rdr_env' })
291         }
292
293 extendRdrEnvRn :: GlobalRdrEnv -> [AvailInfo] -> RnM GlobalRdrEnv
294 -- Add the new locally-bound names one by one, checking for duplicates as
295 -- we do so.  Remember that in Template Haskell the duplicates
296 -- might *already be* in the GlobalRdrEnv from higher up the module
297 extendRdrEnvRn rdr_env avails
298   = foldlM add_local rdr_env (gresFromAvails LocalDef avails)
299   where
300     add_local rdr_env gre
301         | gres <- lookupGlobalRdrEnv rdr_env (nameOccName (gre_name gre))
302         , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
303         = do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
304              ; return rdr_env }
305         | otherwise
306         = return (extendGlobalRdrEnv rdr_env gre)
307 \end{code}
308
309 @getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
310 used for source code.
311
312         *** See "THE NAMING STORY" in HsDecls ****
313
314 Instances of indexed types
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~
316 Indexed data/newtype instances contain data constructors that we need to
317 collect, too.  Moreover, we need to descend into the data/newtypes instances
318 of associated families.
319
320 We need to be careful with the handling of the type constructor of each type
321 instance as the family constructor is already defined, and we want to avoid
322 raising a duplicate declaration error.  So, we make a new name for it, but
323 don't return it in the 'AvailInfo'.
324
325 \begin{code}
326 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
327 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
328                                       hs_tyclds = tycl_decls, 
329                                       hs_instds = inst_decls,
330                                       hs_fords = foreign_decls })
331   = do  { tc_names_s <- mappM new_tc tycl_decls
332         ; at_names_s <- mappM inst_ats inst_decls
333         ; val_names  <- mappM new_simple val_bndrs
334         ; return (val_names ++ tc_names_s ++ concat at_names_s) }
335   where
336     mod        = tcg_mod gbl_env
337     is_hs_boot = isHsBoot (tcg_src gbl_env) ;
338     val_bndrs | is_hs_boot = sig_hs_bndrs
339               | otherwise  = for_hs_bndrs ++ val_hs_bndrs
340         -- In a hs-boot file, the value binders come from the
341         --  *signatures*, and there should be no foreign binders 
342
343     new_simple rdr_name = do
344         nm <- newTopSrcBinder mod rdr_name
345         return (Avail nm)
346
347     sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
348     val_hs_bndrs = collectHsBindLocatedBinders val_decls
349     for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
350
351     new_tc tc_decl 
352       | isIdxTyDecl (unLoc tc_decl)
353         = do { main_name <- lookupFamInstDeclBndr mod main_rdr
354              ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
355              ; return (AvailTC main_name sub_names) }
356                         -- main_name is not bound here!
357       | otherwise
358         = do { main_name <- newTopSrcBinder mod main_rdr
359              ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
360              ; return (AvailTC main_name (main_name : sub_names)) }
361       where
362         (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
363
364     inst_ats inst_decl 
365         = mappM new_tc (instDeclATs (unLoc inst_decl))
366
367 getLocalDeclBinders _ _ = panic "getLocalDeclBinders"   -- ValBindsOut can't happen
368 \end{code}
369
370
371 %************************************************************************
372 %*                                                                      *
373 \subsection{Filtering imports}
374 %*                                                                      *
375 %************************************************************************
376
377 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
378 available, and filters it through the import spec (if any).
379
380 \begin{code}
381 filterImports :: ModIface
382               -> ImpDeclSpec                    -- The span for the entire import decl
383               -> Maybe (Bool, [LIE RdrName])    -- Import spec; True => hiding
384               -> [AvailInfo]                    -- What's available
385               -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
386                       GlobalRdrEnv)             -- Same again, but in GRE form
387                         
388 filterImports iface decl_spec Nothing all_avails
389   = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
390   where
391     prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
392
393
394 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
395   = do   -- check for errors, convert RdrNames to Names
396         opt_indexedtypes <- doptM Opt_IndexedTypes
397         items1 <- mapM (lookup_lie opt_indexedtypes) import_items
398
399         let items2 :: [(LIE Name, AvailInfo)]
400             items2 = concat items1
401                 -- NB the AvailInfo may have duplicates, and several items
402                 --    for the same parent; e.g N(x) and N(y)
403
404             names  = availsToNameSet (map snd items2)
405             keep n = not (n `elemNameSet` names)
406             pruned_avails = filterAvails keep all_avails
407             hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
408
409             gres | want_hiding = gresFromAvails hiding_prov pruned_avails
410                  | otherwise   = concatMap (gresFromIE decl_spec) items2
411
412         return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
413   where
414         -- This environment is how we map names mentioned in the import
415         -- list to the actual Name they correspond to, and the name family
416         -- that the Name belongs to (the AvailInfo).  The situation is
417         -- complicated by associated families, which introduce a three-level
418         -- hierachy, where class = grand parent, assoc family = parent, and
419         -- data constructors = children.  The occ_env entries for associated
420         -- families needs to capture all this information; hence, we have the
421         -- third component of the environment that gives the class name (=
422         -- grand parent) in case of associated families.
423         --
424         -- This env will have entries for data constructors too,
425         -- they won't make any difference because naked entities like T
426         -- in an import list map to TcOccs, not VarOccs.
427     occ_env :: OccEnv (Name,        -- the name
428                        AvailInfo,   -- the export item providing the name
429                        Maybe Name)  -- the parent of associated types
430     occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing)) 
431                                  | a <- all_avails, n <- availNames a]
432       where
433         -- we know that (1) there are at most entries for one name, (2) their
434         -- first component is identical, (3) they are for tys/cls, and (4) one
435         -- entry has the name in its parent position (the other doesn't)
436         combine (name, AvailTC p1 subs1, Nothing)
437                 (_   , AvailTC p2 subs2, Nothing)
438           = let
439               (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
440             in
441             (name, AvailTC name subs, Just parent)
442
443     lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
444     lookup_lie opt_indexedtypes (L loc ieRdr)
445         = do 
446              stuff <- setSrcSpan loc $ 
447                       case lookup_ie opt_indexedtypes ieRdr of
448                             Failed err  -> addErr err >> return []
449                             Succeeded a -> return a
450              checkDodgyImport stuff
451              return [ (L loc ie, avail) | (ie,avail) <- stuff ]
452         where
453                 -- Warn when importing T(..) if T was exported abstractly
454             checkDodgyImport stuff
455                 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
456                 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
457                 -- NB. use the RdrName for reporting the warning
458             checkDodgyImport _
459                 = return ()
460
461         -- For each import item, we convert its RdrNames to Names,
462         -- and at the same time construct an AvailInfo corresponding
463         -- to what is actually imported by this item.
464         -- Returns Nothing on error.
465         -- We return a list here, because in the case of an import
466         -- item like C, if we are hiding, then C refers to *both* a
467         -- type/class and a data constructor.  Moreover, when we import
468         -- data constructors of an associated family, we need separate
469         -- AvailInfos for the data constructors and the family (as they have
470         -- different parents).  See the discussion at occ_env.
471     lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
472     lookup_ie opt_indexedtypes ie 
473       = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
474
475             lookup_name rdrName = 
476                 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
477                    Nothing -> bad_ie
478                    Just n  -> return n
479         in
480         case ie of
481          IEVar n -> do
482              (name, avail, _) <- lookup_name n
483              return [(IEVar name, trimAvail avail name)]
484
485          IEThingAll tc -> do
486              (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
487              case mb_parent of
488                -- non-associated ty/cls
489                Nothing     -> return [(IEThingAll name, avail)]
490                -- associated ty
491                Just parent -> return [(IEThingAll name, 
492                                        AvailTC name2 (subs \\ [name])),
493                                       (IEThingAll name, AvailTC parent [name])]
494
495          IEThingAbs tc
496              | want_hiding   -- hiding ( C )
497                         -- Here the 'C' can be a data constructor 
498                         --  *or* a type/class, or even both
499              -> let tc_name = lookup_name tc
500                     dc_name = lookup_name (setRdrNameSpace tc srcDataName)
501                 in
502                 case catMaybeErr [ tc_name, dc_name ] of
503                   []    -> bad_ie
504                   names -> return [mkIEThingAbs name | name <- names]
505              | otherwise
506              -> do nameAvail <- lookup_name tc
507                    return [mkIEThingAbs nameAvail]
508
509          IEThingWith tc ns -> do
510             (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
511             let 
512               env         = mkOccEnv [(nameOccName s, s) | s <- subnames]
513               mb_children = map (lookupOccEnv env . rdrNameOcc) ns
514             children <- if any isNothing mb_children
515                         then bad_ie
516                         else return (catMaybes mb_children)
517               -- check for proper import of indexed types
518             when (not opt_indexedtypes && any isTyConName children) $
519               Failed (typeItemErr (head . filter isTyConName $ children)
520                                   (text "in import list"))
521             case mb_parent of
522                -- non-associated ty/cls
523               Nothing     -> return [(IEThingWith name children, 
524                                       AvailTC name (name:children))]
525                -- associated ty
526               Just parent -> return [(IEThingWith name children, 
527                                       AvailTC name children),
528                                      (IEThingWith name children, 
529                                       AvailTC parent [name])]
530
531          _other -> Failed illegalImportItemErr
532          -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
533          -- all errors.
534
535       where
536         mkIEThingAbs (n, av, Nothing    ) = (IEThingAbs n, trimAvail av n) 
537         mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n]) 
538
539
540 catMaybeErr :: [MaybeErr err a] -> [a]
541 catMaybeErr ms =  [ a | Succeeded a <- ms ]
542 \end{code}
543
544 \begin{code}
545 filterImports2 :: ModIface
546               -> ImpDeclSpec                    -- The span for the entire import decl
547               -> Maybe (Bool, [LIE RdrName])    -- Import spec; True => hiding
548               -> [AvailInfo]                    -- What's available
549               -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
550                       GlobalRdrEnv)             -- Same again, but in GRE form
551                         
552 filterImports2 iface decl_spec Nothing all_avails
553   = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
554   where
555     prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
556
557
558 filterImports2 iface decl_spec (Just (want_hiding, import_items)) all_avails
559   = do   -- check for errors, convert RdrNames to Names
560         opt_indexedtypes <- doptM Opt_IndexedTypes
561         items1 <- mapM (lookup_lie opt_indexedtypes) import_items
562
563         let items2 :: [(LIE Name, AvailInfo)]
564             items2 = concat items1
565                 -- NB the AvailInfo may have duplicates, and several items
566                 --    for the same parent; e.g N(x) and N(y)
567
568             names  = availsToNameSet (map snd items2)
569             keep n = not (n `elemNameSet` names)
570             pruned_avails = filterAvails keep all_avails
571             hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
572
573             gres | want_hiding = gresFromAvails hiding_prov pruned_avails
574                  | otherwise   = concatMap (gresFromIE decl_spec) items2
575
576         return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
577   where
578         -- This environment is how we map names mentioned in the import
579         -- list to the actual Name they correspond to, and the family
580         -- that the Name belongs to (an AvailInfo).
581         --
582         -- This env will have entries for data constructors too,
583         -- they won't make any difference because naked entities like T
584         -- in an import list map to TcOccs, not VarOccs.
585     occ_env :: OccEnv (Name,AvailInfo)
586     occ_env = mkOccEnv [ (nameOccName n, (n,a)) 
587                        | a <- all_avails, n <- availNames a ]
588
589     lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
590     lookup_lie opt_indexedtypes (L loc ieRdr)
591         = do 
592              stuff <- setSrcSpan loc $ 
593                       case lookup_ie opt_indexedtypes ieRdr of
594                             Failed err  -> addErr err >> return []
595                             Succeeded a -> return a
596              checkDodgyImport stuff
597              return [ (L loc ie, avail) | (ie,avail) <- stuff ]
598         where
599                 -- Warn when importing T(..) if T was exported abstractly
600             checkDodgyImport stuff
601                 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
602                 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
603                 -- NB. use the RdrName for reporting the warning
604             checkDodgyImport _
605                 = return ()
606
607         -- For each import item, we convert its RdrNames to Names,
608         -- and at the same time construct an AvailInfo corresponding
609         -- to what is actually imported by this item.
610         -- Returns Nothing on error.
611         -- We return a list here, because in the case of an import
612         -- item like C, if we are hiding, then C refers to *both* a
613         -- type/class and a data constructor.
614     lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
615     lookup_ie opt_indexedtypes ie 
616       = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
617
618             lookup_name rdrName = 
619                 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
620                    Nothing -> bad_ie
621                    Just n  -> return n
622         in
623         case ie of
624          IEVar n -> do
625              (name,avail) <- lookup_name n
626              return [(IEVar name, trimAvail avail name)]
627
628          IEThingAll tc -> do
629              (name,avail) <- lookup_name tc
630              return [(IEThingAll name, avail)]
631
632          IEThingAbs tc
633              | want_hiding   -- hiding ( C )
634                         -- Here the 'C' can be a data constructor 
635                         --  *or* a type/class, or even both
636              -> let tc_name = lookup_name tc
637                     dc_name = lookup_name (setRdrNameSpace tc srcDataName)
638                 in
639                 case catMaybeErr [ tc_name, dc_name ] of
640                   []    -> bad_ie
641                   names -> return [ (IEThingAbs n, trimAvail av n) 
642                                   | (n,av) <- names ]
643              | otherwise
644              -> do (name,avail) <- lookup_name tc
645                    return [(IEThingAbs name, AvailTC name [name])]
646
647          IEThingWith n ns -> do
648             (name,avail) <- lookup_name n
649             case avail of
650                 AvailTC nm subnames | nm == name -> do
651                      let env = mkOccEnv [ (nameOccName s, s) 
652                                         | s <- subnames ]
653                      let mb_children = map (lookupOccEnv env . rdrNameOcc) ns
654                      children <- 
655                         if any isNothing mb_children
656                           then bad_ie
657                           else return (catMaybes mb_children)
658                         -- check for proper import of indexed types
659                      when (not opt_indexedtypes && any isTyConName children) $
660                         Failed (typeItemErr (head . filter isTyConName 
661                                                 $ children )
662                                      (text "in import list"))
663                      return [(IEThingWith name children, AvailTC name (name:children))]
664
665                 _otherwise -> bad_ie
666
667          _other -> Failed illegalImportItemErr
668          -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
669          -- all errors.
670 \end{code}
671
672 %************************************************************************
673 %*                                                                      *
674         Import/Export Utils
675 %*                                                                      *
676 %************************************************************************
677
678 \begin{code}
679 -- | make a 'GlobalRdrEnv' where all the elements point to the same
680 -- import declaration (useful for "hiding" imports, or imports with
681 -- no details).
682 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
683 gresFromAvails prov avails
684   = concatMap (gresFromAvail (const prov)) avails
685
686 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
687 gresFromAvail prov_fn avail
688   = [ GRE {gre_name = n, 
689            gre_par = availParent n avail, 
690            gre_prov = prov_fn n}
691     | n <- availNames avail ]
692   
693 greAvail :: GlobalRdrElt -> AvailInfo
694 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
695
696 mkUnitAvail :: Name -> Parent -> AvailInfo
697 mkUnitAvail me (ParentIs p)              = AvailTC p  [me]
698 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
699                         | otherwise      = Avail me
700
701 plusAvail (Avail n1)       (Avail n2)       = Avail n1
702 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
703 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
704
705 availParent :: Name -> AvailInfo -> Parent
706 availParent n (Avail _)                  = NoParent
707 availParent n (AvailTC m ms) | n==m      = NoParent
708                              | otherwise = ParentIs m
709
710 trimAvail :: AvailInfo -> Name -> AvailInfo
711 trimAvail (Avail n)      m = Avail n
712 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
713
714 -- | filters 'AvailInfo's by the given predicate
715 filterAvails  :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
716 filterAvails keep avails = foldr (filterAvail keep) [] avails
717
718 -- | filters an 'AvailInfo' by the given predicate
719 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
720 filterAvail keep ie rest =
721   case ie of
722     Avail n | keep n    -> ie : rest
723             | otherwise -> rest
724     AvailTC tc ns ->
725         let left = filter keep ns in
726         if null left then rest else AvailTC tc left : rest
727
728 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
729 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
730 gresFromIE decl_spec (L loc ie, avail)
731   = gresFromAvail prov_fn avail
732   where
733     is_explicit = case ie of
734                     IEThingAll name -> \n -> n==name
735                     other           -> \n -> True
736     prov_fn name = Imported [imp_spec]
737         where
738           imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
739           item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
740
741 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
742 mkChildEnv gres = foldr add emptyNameEnv gres
743     where
744         add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
745         add other_gre                                    env = env
746
747 findChildren :: NameEnv [Name] -> Name -> [Name]
748 findChildren env n = lookupNameEnv env n `orElse` []
749 \end{code}
750
751 ---------------------------------------
752         AvailEnv and friends
753
754 All this AvailEnv stuff is hardly used; only in a very small
755 part of RnNames.  Todo: remove?
756 ---------------------------------------
757
758 \begin{code}
759 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
760
761 emptyAvailEnv :: AvailEnv
762 emptyAvailEnv = emptyNameEnv
763
764 unitAvailEnv :: AvailInfo -> AvailEnv
765 unitAvailEnv a = unitNameEnv (availName a) a
766
767 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
768 plusAvailEnv = plusNameEnv_C plusAvail
769
770 availEnvElts :: AvailEnv -> [AvailInfo]
771 availEnvElts = nameEnvElts
772
773 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
774 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
775
776 mkAvailEnv :: [AvailInfo] -> AvailEnv
777         -- 'avails' may have several items with the same availName
778         -- E.g  import Ix( Ix(..), index )
779         -- will give Ix(Ix,index,range) and Ix(index)
780         -- We want to combine these; addAvail does that
781 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
782
783 -- | combines 'AvailInfo's from the same family
784 nubAvails :: [AvailInfo] -> [AvailInfo]
785 nubAvails avails = nameEnvElts (mkAvailEnv avails)
786 \end{code}
787
788
789 %************************************************************************
790 %*                                                                      *
791 \subsection{Export list processing}
792 %*                                                                      *
793 %************************************************************************
794
795 Processing the export list.
796
797 You might think that we should record things that appear in the export
798 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
799 wrong.  We do check (here) that they are in scope, but there is no
800 need to slurp in their actual declaration (which is what
801 @addOccurrenceName@ forces).
802
803 Indeed, doing so would big trouble when compiling @PrelBase@, because
804 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
805 @ConcBase.StateAndSynchVar#@, and so on...
806
807 \begin{code}
808 type ExportAccum        -- The type of the accumulating parameter of
809                         -- the main worker function in rnExports
810      = ([LIE Name],             -- Export items with Names
811         ExportOccMap,           -- Tracks exported occurrence names
812         [AvailInfo])            -- The accumulated exported stuff
813                                 --   Not nub'd!
814
815 emptyExportAccum = ([], emptyOccEnv, []) 
816
817 type ExportOccMap = OccEnv (Name, IE RdrName)
818         -- Tracks what a particular exported OccName
819         --   in an export list refers to, and which item
820         --   it came from.  It's illegal to export two distinct things
821         --   that have the same occurrence name
822
823 rnExports :: Bool    -- False => no 'module M(..) where' header at all
824           -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
825           -> RnM (Maybe [LIE Name], [AvailInfo])
826
827         -- Complains if two distinct exports have same OccName
828         -- Warns about identical exports.
829         -- Complains about exports items not in scope
830
831 rnExports explicit_mod exports
832  = do TcGblEnv { tcg_mod     = this_mod,
833                  tcg_rdr_env = rdr_env, 
834                  tcg_imports = imports } <- getGblEnv
835
836         -- If the module header is omitted altogether, then behave
837         -- as if the user had written "module Main(main) where..."
838         -- EXCEPT in interactive mode, when we behave as if he had
839         -- written "module Main where ..."
840         -- Reason: don't want to complain about 'main' not in scope
841         --         in interactive mode
842       ghc_mode <- getGhcMode
843       real_exports <- 
844           case () of
845             () | explicit_mod
846                    -> return exports
847                | ghc_mode == Interactive
848                    -> return Nothing
849                | otherwise
850                    -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
851                          return (Just ([noLoc (IEVar main_RDR_Unqual)]))
852                 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns
853                 -- out to be out of scope
854
855       (exp_spec, avails) <- exports_from_avail real_exports rdr_env imports this_mod
856
857       return (exp_spec, nubAvails avails)     -- Combine families
858
859 exports_from_avail :: Maybe [LIE RdrName]
860                          -- Nothing => no explicit export list
861                    -> GlobalRdrEnv
862                    -> ImportAvails
863                    -> Module
864                    -> RnM (Maybe [LIE Name], [AvailInfo])
865
866 exports_from_avail Nothing rdr_env imports this_mod
867  = -- The same as (module M) where M is the current module name,
868    -- so that's how we handle it.
869    let
870        avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
871                                  isLocalGRE gre ]
872    in
873    return (Nothing, avails)
874
875 exports_from_avail (Just rdr_items) rdr_env imports this_mod
876   = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
877        return (Just ie_names, exports)
878   where
879     do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
880     do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
881
882     kids_env :: NameEnv [Name]  -- Maps a parent to its in-scope children
883     kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
884
885     exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
886     exports_from_item acc@(ie_names, occs, exports) 
887                       (L loc ie@(IEModuleContents mod))
888         | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
889         , mod `elem` earlier_mods       -- Duplicate export of M
890         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
891                warnIf warn_dup_exports (dupModuleExport mod) ;
892                returnM acc }
893
894         | otherwise
895         = do { implicit_prelude <- doptM Opt_ImplicitPrelude
896              ; let gres = filter (isModuleExported implicit_prelude mod) 
897                                  (globalRdrEnvElts rdr_env)
898
899              ; warnIf (null gres) (nullModuleExport mod)
900
901              ; occs' <- check_occs ie occs (map gre_name gres)
902                       -- This check_occs not only finds conflicts
903                       -- between this item and others, but also
904                       -- internally within this item.  That is, if
905                       -- 'M.x' is in scope in several ways, we'll have
906                       -- several members of mod_avails with the same
907                       -- OccName.
908              ; return (L loc (IEModuleContents mod) : ie_names,
909                        occs', map greAvail gres ++ exports) }
910
911     exports_from_item acc@(lie_names, occs, exports) (L loc ie)
912         | isDoc ie
913         = do new_ie <- lookup_doc_ie ie
914              return (L loc new_ie : lie_names, occs, exports)
915
916         | otherwise
917         = do (new_ie, avail) <- lookup_ie ie
918              if isUnboundName (ieName new_ie)
919                   then return acc       -- Avoid error cascade
920                   else do
921
922              occs' <- check_occs ie occs (availNames avail)
923
924              return (L loc new_ie : lie_names, occs', avail : exports)
925
926     -------------
927     lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
928     lookup_ie (IEVar rdr) 
929         = do gre <- lookupGreRn rdr
930              return (IEVar (gre_name gre), greAvail gre)
931
932     lookup_ie (IEThingAbs rdr) 
933         = do name <- lookupGlobalOccRn rdr
934              case lookupGRE_RdrName rdr rdr_env of
935                []    -> panic "RnNames.lookup_ie"
936                elt:_ -> case gre_par elt of
937                           NoParent   -> return (IEThingAbs name, 
938                                                 AvailTC name [name])
939                           ParentIs p -> return (IEThingAbs name, 
940                                                 AvailTC p [name])
941
942     lookup_ie ie@(IEThingAll rdr) 
943         = do name <- lookupGlobalOccRn rdr
944              let kids = findChildren kids_env name
945              when (null kids)
946                   (if (isTyConName name) then addWarn (dodgyExportWarn name)
947                                 -- This occurs when you export T(..), but
948                                 -- only import T abstractly, or T is a synonym.  
949                    else addErr (exportItemErr ie))
950                         
951              return (IEThingAll name, AvailTC name (name:kids))
952
953     lookup_ie ie@(IEThingWith rdr sub_rdrs)
954         = do name <- lookupGlobalOccRn rdr
955              if isUnboundName name
956                 then return (IEThingWith name [], AvailTC name [name])
957                 else do
958              let env = mkOccEnv [ (nameOccName s, s) 
959                                 | s <- findChildren kids_env name ]
960                  mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
961              if any isNothing mb_names
962                 then do addErr (exportItemErr ie)
963                         return (IEThingWith name [], AvailTC name [name])
964                 else do let names = catMaybes mb_names
965                         optIdxTypes <- doptM Opt_IndexedTypes
966                         when (not optIdxTypes && any isTyConName names) $
967                           addErr (typeItemErr ( head
968                                               . filter isTyConName 
969                                               $ names )
970                                               (text "in export list"))
971                         return (IEThingWith name names, AvailTC name (name:names))
972
973     lookup_ie ie = panic "lookup_ie"    -- Other cases covered earlier
974
975     -------------
976     lookup_doc_ie :: IE RdrName -> RnM (IE Name)
977     lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
978                                          return (IEGroup lev rn_doc)
979     lookup_doc_ie (IEDoc doc)       = do rn_doc <- rnHsDoc doc
980                                          return (IEDoc rn_doc)
981     lookup_doc_ie (IEDocNamed str)  = return (IEDocNamed str)
982     lookup_doc_ie ie = panic "lookup_doc_ie"    -- Other cases covered earlier
983
984
985 isDoc (IEDoc _)      = True
986 isDoc (IEDocNamed _) = True
987 isDoc (IEGroup _ _)  = True
988 isDoc _ = False
989
990 -------------------------------
991 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
992 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
993 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
994   | implicit_prelude && isBuiltInSyntax name = False
995         -- Optimisation: filter out names for built-in syntax
996         -- They just clutter up the environment (esp tuples), and the parser
997         -- will generate Exact RdrNames for them, so the cluttered
998         -- envt is no use.  To avoid doing this filter all the time,
999         -- we use -fno-implicit-prelude as a clue that the filter is
1000         -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
1001         --
1002         -- It's worth doing because it makes the environment smaller for
1003         -- every module that imports the Prelude
1004   | otherwise
1005   = case prov of
1006         LocalDef    -> moduleName (nameModule name) == mod
1007         Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1008
1009 -------------------------------
1010 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1011 check_occs ie occs names
1012   = foldlM check occs names
1013   where
1014     check occs name
1015       = case lookupOccEnv occs name_occ of
1016           Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
1017
1018           Just (name', ie') 
1019             | name == name'     -- Duplicate export
1020             ->  do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
1021                      warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
1022                      returnM occs }
1023
1024             | otherwise         -- Same occ name but different names: an error
1025             ->  do { global_env <- getGlobalRdrEnv ;
1026                      addErr (exportClashErr global_env name' name ie' ie) ;
1027                      returnM occs }
1028       where
1029         name_occ = nameOccName name
1030 \end{code}
1031
1032 %*********************************************************
1033 %*                                                       *
1034                 Deprecations
1035 %*                                                       *
1036 %*********************************************************
1037
1038 \begin{code}
1039 reportDeprecations :: DynFlags -> TcGblEnv -> RnM ()
1040 reportDeprecations dflags tcg_env
1041   = ifOptM Opt_WarnDeprecations $
1042     do  { (eps,hpt) <- getEpsAndHpt
1043                 -- By this time, typechecking is complete, 
1044                 -- so the PIT is fully populated
1045         ; mapM_ (check hpt (eps_PIT eps)) all_gres }
1046   where
1047     used_names = allUses (tcg_dus tcg_env) 
1048         -- Report on all deprecated uses; hence allUses
1049     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
1050
1051     check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1052       | name `elemNameSet` used_names
1053       , Just deprec_txt <- lookupDeprec dflags hpt pit gre
1054       = addWarnAt (importSpecLoc imp_spec)
1055                   (sep [ptext SLIT("Deprecated use of") <+> 
1056                         pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
1057                         quotes (ppr name),
1058                       (parens imp_msg) <> colon,
1059                       (ppr deprec_txt) ])
1060         where
1061           name_mod = nameModule name
1062           imp_mod  = importSpecModule imp_spec
1063           imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
1064           extra | imp_mod == moduleName name_mod = empty
1065                 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
1066
1067     check hpt pit ok_gre = returnM ()   -- Local, or not used, or not deprectated
1068             -- The Imported pattern-match: don't deprecate locally defined names
1069             -- For a start, we may be exporting a deprecated thing
1070             -- Also we may use a deprecated thing in the defn of another
1071             -- deprecated things.  We may even use a deprecated thing in
1072             -- the defn of a non-deprecated thing, when changing a module's 
1073             -- interface
1074
1075 lookupDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable 
1076              -> GlobalRdrElt -> Maybe DeprecTxt
1077 lookupDeprec dflags hpt pit gre
1078   = case lookupIfaceByModule dflags hpt pit (nameModule name) of
1079         Just iface -> mi_dep_fn iface name `seqMaybe`   -- Bleat if the thing, *or
1080                       case gre_par gre of       
1081                         ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
1082                         NoParent   -> Nothing
1083         Nothing    
1084           | isWiredInName name -> Nothing
1085                 -- We have not necessarily loaded the .hi file for a 
1086                 -- wired-in name (yet), although we *could*.
1087                 -- And we never deprecate them
1088
1089          | otherwise -> pprPanic "lookupDeprec" (ppr name)      
1090                 -- By now all the interfaces should have been loaded
1091   where
1092         name = gre_name gre
1093 \end{code}
1094
1095 %*********************************************************
1096 %*                                                       *
1097                 Unused names
1098 %*                                                       *
1099 %*********************************************************
1100
1101 \begin{code}
1102 reportUnusedNames :: Maybe [LIE RdrName]        -- Export list
1103                   -> TcGblEnv -> RnM ()
1104 reportUnusedNames export_decls gbl_env 
1105   = do  { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1106         ; warnUnusedTopBinds   unused_locals
1107         ; warnUnusedModules    unused_imp_mods
1108         ; warnUnusedImports    unused_imports   
1109         ; warnDuplicateImports defined_and_used
1110         ; printMinimalImports  minimal_imports }
1111   where
1112     used_names :: NameSet
1113     used_names = findUses (tcg_dus gbl_env) emptyNameSet
1114         -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1115         -- Hence findUses
1116
1117         -- Collect the defined names from the in-scope environment
1118     defined_names :: [GlobalRdrElt]
1119     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1120
1121         -- Note that defined_and_used, defined_but_not_used
1122         -- are both [GRE]; that's why we need defined_and_used
1123         -- rather than just used_names
1124     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1125     (defined_and_used, defined_but_not_used) 
1126         = partition (gre_is_used used_names) defined_names
1127     
1128     kids_env = mkChildEnv defined_names
1129         -- This is done in mkExports too; duplicated work
1130
1131     gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1132     gre_is_used used_names (GRE {gre_name = name})
1133         = name `elemNameSet` used_names
1134           || any (`elemNameSet` used_names) (findChildren kids_env name)
1135                 -- A use of C implies a use of T,
1136                 -- if C was brought into scope by T(..) or T(C)
1137
1138         -- Filter out the ones that are 
1139         --  (a) defined in this module, and
1140         --  (b) not defined by a 'deriving' clause 
1141         -- The latter have an Internal Name, so we can filter them out easily
1142     unused_locals :: [GlobalRdrElt]
1143     unused_locals = filter is_unused_local defined_but_not_used
1144     is_unused_local :: GlobalRdrElt -> Bool
1145     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1146     
1147     unused_imports :: [GlobalRdrElt]
1148     unused_imports = filter unused_imp defined_but_not_used
1149     unused_imp (GRE {gre_prov = Imported imp_specs}) 
1150         = not (all (module_unused . importSpecModule) imp_specs)
1151           && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
1152                 -- Don't complain about unused imports if we've already said the
1153                 -- entire import is unused
1154     unused_imp other = False
1155     
1156     -- To figure out the minimal set of imports, start with the things
1157     -- that are in scope (i.e. in gbl_env).  Then just combine them
1158     -- into a bunch of avails, so they are properly grouped
1159     --
1160     -- BUG WARNING: this does not deal properly with qualified imports!
1161     minimal_imports :: FiniteMap ModuleName AvailEnv
1162     minimal_imports0 = foldr add_expall   emptyFM          expall_mods
1163     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
1164     minimal_imports  = foldr add_inst_mod minimal_imports1 direct_import_mods
1165         -- The last line makes sure that we retain all direct imports
1166         -- even if we import nothing explicitly.
1167         -- It's not necessarily redundant to import such modules. Consider 
1168         --            module This
1169         --              import M ()
1170         --
1171         -- The import M() is not *necessarily* redundant, even if
1172         -- we suck in no instance decls from M (e.g. it contains 
1173         -- no instance decls, or This contains no code).  It may be 
1174         -- that we import M solely to ensure that M's orphan instance 
1175         -- decls (or those in its imports) are visible to people who 
1176         -- import This.  Sigh. 
1177         -- There's really no good way to detect this, so the error message 
1178         -- in RnEnv.warnUnusedModules is weakened instead
1179     
1180         -- We've carefully preserved the provenance so that we can
1181         -- construct minimal imports that import the name by (one of)
1182         -- the same route(s) as the programmer originally did.
1183     add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc 
1184         = addToFM_C plusAvailEnv acc 
1185                     (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1186     add_name gre acc = acc      -- Local
1187
1188         -- Modules mentioned as 'module M' in the export list
1189     expall_mods = case export_decls of
1190                     Nothing -> []
1191                     Just es -> [m | L _ (IEModuleContents m) <- es]
1192
1193         -- This is really bogus.  The idea is that if we see 'module M' in 
1194         -- the export list we must retain the import decls that drive it
1195         -- If we aren't careful we might see
1196         --      module A( module M ) where
1197         --        import M
1198         --        import N
1199         -- and suppose that N exports everything that M does.  Then we 
1200         -- must not drop the import of M even though N brings it all into
1201         -- scope.
1202         --
1203         -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1204         --
1205         -- The reason that add_expall is bogus is that it doesn't take
1206         -- qualified imports into account.  But it's an improvement.
1207     add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1208
1209     add_inst_mod (mod,_,_) acc 
1210       | mod_name `elemFM` acc = acc     -- We import something already
1211       | otherwise             = addToFM acc mod_name emptyAvailEnv
1212       where
1213         mod_name = moduleName mod
1214         -- Add an empty collection of imports for a module
1215         -- from which we have sucked only instance decls
1216    
1217     imports = tcg_imports gbl_env
1218
1219     direct_import_mods :: [(Module, Bool, SrcSpan)]
1220         -- See the type of the imp_mods for this triple
1221     direct_import_mods = moduleEnvElts (imp_mods imports)
1222
1223     -- unused_imp_mods are the directly-imported modules 
1224     -- that are not mentioned in minimal_imports1
1225     -- [Note: not 'minimal_imports', because that includes directly-imported
1226     --        modules even if we use nothing from them; see notes above]
1227     --
1228     -- BUG WARNING: does not deal correctly with multiple imports of the same module
1229     --              becuase direct_import_mods has only one entry per module
1230     unused_imp_mods = [(mod_name,loc) | (mod,no_imp,loc) <- direct_import_mods,
1231                        let mod_name = moduleName mod,
1232                        not (mod_name `elemFM` minimal_imports1),
1233                        mod /= pRELUDE,
1234                        not no_imp]
1235         -- The not no_imp part is not to complain about
1236         -- import M (), which is an idiom for importing
1237         -- instance declarations
1238     
1239     module_unused :: ModuleName -> Bool
1240     module_unused mod = any (((==) mod) . fst) unused_imp_mods
1241
1242 ---------------------
1243 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1244 -- Given the GREs for names that are used, figure out which imports 
1245 -- could be omitted without changing the top-level environment.
1246 --
1247 -- NB: Given import Foo( T )
1248 --           import qualified Foo
1249 -- we do not report a duplicate import, even though Foo.T is brought
1250 -- into scope by both, because there's nothing you can *omit* without
1251 -- changing the top-level environment.  So we complain only if it's
1252 -- explicitly named in both imports or neither.
1253 --
1254 -- Furthermore, we complain about Foo.T only if 
1255 -- there is no complaint about (unqualified) T
1256
1257 warnDuplicateImports gres
1258   = ifOptM Opt_WarnUnusedImports $ 
1259     sequenceM_  [ warn name pr
1260                         -- The 'head' picks the first offending group
1261                         -- for this particular name
1262                 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1263                 , pr <- redundants imps ]
1264   where
1265     warn name (red_imp, cov_imp)
1266         = addWarnAt (importSpecLoc red_imp)
1267             (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1268                    ptext SLIT("It is also") <+> ppr cov_imp])
1269         where
1270           pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1271                   | otherwise       = ppr occ
1272           occ = nameOccName name
1273           red_decl = is_decl red_imp
1274     
1275     redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1276         -- The returned pair is (redundant-import, covering-import)
1277     redundants imps 
1278         = [ (red_imp, cov_imp) 
1279           | red_imp <- imps
1280           , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1281
1282         -- "red_imp" is a putative redundant import
1283         -- "cov_imp" potentially covers it
1284         -- This test decides whether red_imp could be dropped 
1285         --
1286         -- NOTE: currently the test does not warn about
1287         --              import M( x )
1288         --              imoprt N( x )
1289         -- even if the same underlying 'x' is involved, because dropping
1290         -- either import would change the qualified names in scope (M.x, N.x)
1291         -- But if the qualified names aren't used, the import is indeed redundant
1292         -- Sadly we don't know that.  Oh well.
1293     covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item }) 
1294            cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1295         | red_loc == cov_loc
1296         = False         -- Ignore diagonal elements
1297         | not (is_as red_decl == is_as cov_decl)
1298         = False         -- They bring into scope different qualified names
1299         | not (is_qual red_decl) && is_qual cov_decl
1300         = False         -- Covering one doesn't bring unqualified name into scope
1301         | red_selective
1302         = not cov_selective     -- Redundant one is selective and covering one isn't
1303           || red_later          -- Both are explicit; tie-break using red_later
1304         | otherwise             
1305         = not cov_selective     -- Neither import is selective
1306           && (is_mod red_decl == is_mod cov_decl)       -- They import the same module
1307           && red_later          -- Tie-break
1308         where
1309           red_loc   = importSpecLoc red_imp
1310           cov_loc   = importSpecLoc cov_imp
1311           red_later = red_loc > cov_loc
1312           cov_selective = selectiveImpItem cov_item
1313           red_selective = selectiveImpItem red_item
1314
1315 selectiveImpItem :: ImpItemSpec -> Bool
1316 selectiveImpItem ImpAll       = False
1317 selectiveImpItem (ImpSome {}) = True
1318
1319 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1320 printMinimalImports :: FiniteMap ModuleName AvailEnv    -- Minimal imports
1321                     -> RnM ()
1322 printMinimalImports imps
1323  = ifOptM Opt_D_dump_minimal_imports $ do {
1324
1325    mod_ies  <-  mappM to_ies (fmToList imps) ;
1326    this_mod <- getModule ;
1327    rdr_env  <- getGlobalRdrEnv ;
1328    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1329                   printForUser h (mkPrintUnqualified rdr_env) 
1330                                  (vcat (map ppr_mod_ie mod_ies)) })
1331    }
1332   where
1333     mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1334     ppr_mod_ie (mod_name, ies) 
1335         | mod_name == moduleName pRELUDE
1336         = empty
1337         | null ies      -- Nothing except instances comes from here
1338         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
1339         | otherwise
1340         = ptext SLIT("import") <+> ppr mod_name <> 
1341                     parens (fsep (punctuate comma (map ppr ies)))
1342
1343     to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1344                                  returnM (mod, ies)
1345
1346     to_ie :: AvailInfo -> RnM (IE Name)
1347         -- The main trick here is that if we're importing all the constructors
1348         -- we want to say "T(..)", but if we're importing only a subset we want
1349         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1350     to_ie (Avail n)       = returnM (IEVar n)
1351     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
1352                             returnM (IEThingAbs n)
1353     to_ie (AvailTC n ns)  
1354         = loadSrcInterface doc n_mod False                      `thenM` \ iface ->
1355           case [xs | (m,as) <- mi_exports iface,
1356                      moduleName m == n_mod,
1357                      AvailTC x xs <- as, 
1358                      x == nameOccName n] of
1359               [xs] | all_used xs -> returnM (IEThingAll n)
1360                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
1361               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1362                                     returnM (IEVar n)
1363         where
1364           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1365           doc = text "Compute minimal imports from" <+> ppr n
1366           n_mod = moduleName (nameModule n)
1367 \end{code}
1368
1369
1370 %************************************************************************
1371 %*                                                                      *
1372 \subsection{Errors}
1373 %*                                                                      *
1374 %************************************************************************
1375
1376 \begin{code}
1377 badImportItemErr iface decl_spec ie
1378   = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1379          ptext SLIT("does not export"), quotes (ppr ie)]
1380   where
1381     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1382                   | otherwise     = empty
1383
1384 illegalImportItemErr = ptext SLIT("Illegal import item")
1385
1386 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1387 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1388
1389 dodgyMsg kind tc
1390   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1391           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1392           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1393           
1394 exportItemErr export_item
1395   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1396           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1397
1398 typeItemErr name wherestr
1399   = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1400           ptext SLIT("Use -findexed-types to enable this extension") ]
1401
1402 exportClashErr global_env name1 name2 ie1 ie2
1403   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1404          , ppr_export ie1 name1 
1405          , ppr_export ie2 name2  ]
1406   where
1407     occ = nameOccName name1
1408     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
1409                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1410
1411         -- get_gre finds a GRE for the Name, so that we can show its provenance
1412     get_gre name
1413         = case lookupGRE_Name global_env name of
1414              (gre:_) -> gre
1415              []      -> pprPanic "exportClashErr" (ppr name)
1416
1417 addDupDeclErr :: Name -> Name -> TcRn ()
1418 addDupDeclErr name_a name_b
1419   = addErrAt (srcLocSpan loc2) $
1420     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1421           ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1422   where
1423     loc2 = nameSrcLoc name2
1424     (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1425                   | otherwise                             = (name_a,name_b)
1426         -- Report the error at the later location
1427
1428 dupExportWarn occ_name ie1 ie2
1429   = hsep [quotes (ppr occ_name), 
1430           ptext SLIT("is exported by"), quotes (ppr ie1),
1431           ptext SLIT("and"),            quotes (ppr ie2)]
1432
1433 dupModuleExport mod
1434   = hsep [ptext SLIT("Duplicate"),
1435           quotes (ptext SLIT("Module") <+> ppr mod), 
1436           ptext SLIT("in export list")]
1437
1438 nullModuleExport mod
1439   = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1440
1441 moduleDeprec mod txt
1442   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
1443           nest 4 (ppr txt) ]      
1444 \end{code}