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