d61133b2b63fa73827629b79bb49fc6b4632bff4
[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, (\\), delete )
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         filterImports 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 %************************************************************************
545 %*                                                                      *
546         Import/Export Utils
547 %*                                                                      *
548 %************************************************************************
549
550 \begin{code}
551 -- | make a 'GlobalRdrEnv' where all the elements point to the same
552 -- import declaration (useful for "hiding" imports, or imports with
553 -- no details).
554 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
555 gresFromAvails prov avails
556   = concatMap (gresFromAvail (const prov)) avails
557
558 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
559 gresFromAvail prov_fn avail
560   = [ GRE {gre_name = n, 
561            gre_par = availParent n avail, 
562            gre_prov = prov_fn n}
563     | n <- availNames avail ]
564   
565 greAvail :: GlobalRdrElt -> AvailInfo
566 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
567
568 mkUnitAvail :: Name -> Parent -> AvailInfo
569 mkUnitAvail me (ParentIs p)              = AvailTC p  [me]
570 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
571                         | otherwise      = Avail me
572
573 plusAvail (Avail n1)       (Avail n2)       = Avail n1
574 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
575 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
576
577 availParent :: Name -> AvailInfo -> Parent
578 availParent n (Avail _)                  = NoParent
579 availParent n (AvailTC m ms) | n==m      = NoParent
580                              | otherwise = ParentIs m
581
582 trimAvail :: AvailInfo -> Name -> AvailInfo
583 trimAvail (Avail n)      m = Avail n
584 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
585
586 -- | filters 'AvailInfo's by the given predicate
587 filterAvails  :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
588 filterAvails keep avails = foldr (filterAvail keep) [] avails
589
590 -- | filters an 'AvailInfo' by the given predicate
591 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
592 filterAvail keep ie rest =
593   case ie of
594     Avail n | keep n    -> ie : rest
595             | otherwise -> rest
596     AvailTC tc ns ->
597         let left = filter keep ns in
598         if null left then rest else AvailTC tc left : rest
599
600 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
601 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
602 gresFromIE decl_spec (L loc ie, avail)
603   = gresFromAvail prov_fn avail
604   where
605     is_explicit = case ie of
606                     IEThingAll name -> \n -> n==name
607                     other           -> \n -> True
608     prov_fn name = Imported [imp_spec]
609         where
610           imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
611           item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
612
613 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
614 mkChildEnv gres = foldr add emptyNameEnv gres
615     where
616         add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
617         add other_gre                                    env = env
618
619 findChildren :: NameEnv [Name] -> Name -> [Name]
620 findChildren env n = lookupNameEnv env n `orElse` []
621 \end{code}
622
623 ---------------------------------------
624         AvailEnv and friends
625
626 All this AvailEnv stuff is hardly used; only in a very small
627 part of RnNames.  Todo: remove?
628 ---------------------------------------
629
630 \begin{code}
631 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
632
633 emptyAvailEnv :: AvailEnv
634 emptyAvailEnv = emptyNameEnv
635
636 unitAvailEnv :: AvailInfo -> AvailEnv
637 unitAvailEnv a = unitNameEnv (availName a) a
638
639 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
640 plusAvailEnv = plusNameEnv_C plusAvail
641
642 availEnvElts :: AvailEnv -> [AvailInfo]
643 availEnvElts = nameEnvElts
644
645 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
646 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
647
648 mkAvailEnv :: [AvailInfo] -> AvailEnv
649         -- 'avails' may have several items with the same availName
650         -- E.g  import Ix( Ix(..), index )
651         -- will give Ix(Ix,index,range) and Ix(index)
652         -- We want to combine these; addAvail does that
653 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
654
655 -- After combining the avails, we need to ensure that the parent name is the
656 -- first entry in the list of subnames, if it is included at all.  (Subsequent
657 -- functions rely on that.)
658 normaliseAvail :: AvailInfo -> AvailInfo
659 normaliseAvail avail@(Avail _)     = avail
660 normaliseAvail (AvailTC name subs) = AvailTC name subs'
661   where
662     subs' = if name `elem` subs then name : (delete name subs) else subs
663
664 -- | combines 'AvailInfo's from the same family
665 nubAvails :: [AvailInfo] -> [AvailInfo]
666 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
667 \end{code}
668
669
670 %************************************************************************
671 %*                                                                      *
672 \subsection{Export list processing}
673 %*                                                                      *
674 %************************************************************************
675
676 Processing the export list.
677
678 You might think that we should record things that appear in the export
679 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
680 wrong.  We do check (here) that they are in scope, but there is no
681 need to slurp in their actual declaration (which is what
682 @addOccurrenceName@ forces).
683
684 Indeed, doing so would big trouble when compiling @PrelBase@, because
685 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
686 @ConcBase.StateAndSynchVar#@, and so on...
687
688 \begin{code}
689 type ExportAccum        -- The type of the accumulating parameter of
690                         -- the main worker function in rnExports
691      = ([LIE Name],             -- Export items with Names
692         ExportOccMap,           -- Tracks exported occurrence names
693         [AvailInfo])            -- The accumulated exported stuff
694                                 --   Not nub'd!
695
696 emptyExportAccum = ([], emptyOccEnv, []) 
697
698 type ExportOccMap = OccEnv (Name, IE RdrName)
699         -- Tracks what a particular exported OccName
700         --   in an export list refers to, and which item
701         --   it came from.  It's illegal to export two distinct things
702         --   that have the same occurrence name
703
704 rnExports :: Bool    -- False => no 'module M(..) where' header at all
705           -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
706           -> RnM (Maybe [LIE Name], [AvailInfo])
707
708         -- Complains if two distinct exports have same OccName
709         -- Warns about identical exports.
710         -- Complains about exports items not in scope
711
712 rnExports explicit_mod exports
713  = do TcGblEnv { tcg_mod     = this_mod,
714                  tcg_rdr_env = rdr_env, 
715                  tcg_imports = imports } <- getGblEnv
716
717         -- If the module header is omitted altogether, then behave
718         -- as if the user had written "module Main(main) where..."
719         -- EXCEPT in interactive mode, when we behave as if he had
720         -- written "module Main where ..."
721         -- Reason: don't want to complain about 'main' not in scope
722         --         in interactive mode
723       ghc_mode <- getGhcMode
724       real_exports <- 
725           case () of
726             () | explicit_mod
727                    -> return exports
728                | ghc_mode == Interactive
729                    -> return Nothing
730                | otherwise
731                    -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
732                          return (Just ([noLoc (IEVar main_RDR_Unqual)]))
733                 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns
734                 -- out to be out of scope
735
736       (exp_spec, avails) <- exports_from_avail real_exports rdr_env imports this_mod
737
738       return (exp_spec, nubAvails avails)     -- Combine families
739
740 exports_from_avail :: Maybe [LIE RdrName]
741                          -- Nothing => no explicit export list
742                    -> GlobalRdrEnv
743                    -> ImportAvails
744                    -> Module
745                    -> RnM (Maybe [LIE Name], [AvailInfo])
746
747 exports_from_avail Nothing rdr_env imports this_mod
748  = -- The same as (module M) where M is the current module name,
749    -- so that's how we handle it.
750    let
751        avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
752                                  isLocalGRE gre ]
753    in
754    return (Nothing, avails)
755
756 exports_from_avail (Just rdr_items) rdr_env imports this_mod
757   = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
758
759        return (Just ie_names, exports)
760   where
761     do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
762     do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
763
764     kids_env :: NameEnv [Name]  -- Maps a parent to its in-scope children
765     kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
766
767     exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
768     exports_from_item acc@(ie_names, occs, exports) 
769                       (L loc ie@(IEModuleContents mod))
770         | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
771         , mod `elem` earlier_mods       -- Duplicate export of M
772         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
773                warnIf warn_dup_exports (dupModuleExport mod) ;
774                returnM acc }
775
776         | otherwise
777         = do { implicit_prelude <- doptM Opt_ImplicitPrelude
778              ; let gres = filter (isModuleExported implicit_prelude mod) 
779                                  (globalRdrEnvElts rdr_env)
780
781              ; warnIf (null gres) (nullModuleExport mod)
782
783              ; occs' <- check_occs ie occs (map gre_name gres)
784                       -- This check_occs not only finds conflicts
785                       -- between this item and others, but also
786                       -- internally within this item.  That is, if
787                       -- 'M.x' is in scope in several ways, we'll have
788                       -- several members of mod_avails with the same
789                       -- OccName.
790              ; return (L loc (IEModuleContents mod) : ie_names,
791                        occs', map greAvail gres ++ exports) }
792
793     exports_from_item acc@(lie_names, occs, exports) (L loc ie)
794         | isDoc ie
795         = do new_ie <- lookup_doc_ie ie
796              return (L loc new_ie : lie_names, occs, exports)
797
798         | otherwise
799         = do (new_ie, avail) <- lookup_ie ie
800              if isUnboundName (ieName new_ie)
801                   then return acc       -- Avoid error cascade
802                   else do
803
804              occs' <- check_occs ie occs (availNames avail)
805
806              return (L loc new_ie : lie_names, occs', avail : exports)
807
808     -------------
809     lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
810     lookup_ie (IEVar rdr) 
811         = do gre <- lookupGreRn rdr
812              return (IEVar (gre_name gre), greAvail gre)
813
814     lookup_ie (IEThingAbs rdr) 
815         = do name <- lookupGlobalOccRn rdr
816              case lookupGRE_RdrName rdr rdr_env of
817                []    -> panic "RnNames.lookup_ie"
818                elt:_ -> case gre_par elt of
819                           NoParent   -> return (IEThingAbs name, 
820                                                 AvailTC name [name])
821                           ParentIs p -> return (IEThingAbs name, 
822                                                 AvailTC p [name])
823
824     lookup_ie ie@(IEThingAll rdr) 
825         = do name <- lookupGlobalOccRn rdr
826              let kids = findChildren kids_env name
827              when (null kids)
828                   (if (isTyConName name) then addWarn (dodgyExportWarn name)
829                                 -- This occurs when you export T(..), but
830                                 -- only import T abstractly, or T is a synonym.  
831                    else addErr (exportItemErr ie))
832                         
833              return (IEThingAll name, AvailTC name (name:kids))
834
835     lookup_ie ie@(IEThingWith rdr sub_rdrs)
836         = do name <- lookupGlobalOccRn rdr
837              if isUnboundName name
838                 then return (IEThingWith name [], AvailTC name [name])
839                 else do
840              let env = mkOccEnv [ (nameOccName s, s) 
841                                 | s <- findChildren kids_env name ]
842                  mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
843              if any isNothing mb_names
844                 then do addErr (exportItemErr ie)
845                         return (IEThingWith name [], AvailTC name [name])
846                 else do let names = catMaybes mb_names
847                         optIdxTypes <- doptM Opt_IndexedTypes
848                         when (not optIdxTypes && any isTyConName names) $
849                           addErr (typeItemErr ( head
850                                               . filter isTyConName 
851                                               $ names )
852                                               (text "in export list"))
853                         return (IEThingWith name names, AvailTC name (name:names))
854
855     lookup_ie ie = panic "lookup_ie"    -- Other cases covered earlier
856
857     -------------
858     lookup_doc_ie :: IE RdrName -> RnM (IE Name)
859     lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
860                                          return (IEGroup lev rn_doc)
861     lookup_doc_ie (IEDoc doc)       = do rn_doc <- rnHsDoc doc
862                                          return (IEDoc rn_doc)
863     lookup_doc_ie (IEDocNamed str)  = return (IEDocNamed str)
864     lookup_doc_ie ie = panic "lookup_doc_ie"    -- Other cases covered earlier
865
866
867 isDoc (IEDoc _)      = True
868 isDoc (IEDocNamed _) = True
869 isDoc (IEGroup _ _)  = True
870 isDoc _ = False
871
872 -------------------------------
873 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
874 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
875 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
876   | implicit_prelude && isBuiltInSyntax name = False
877         -- Optimisation: filter out names for built-in syntax
878         -- They just clutter up the environment (esp tuples), and the parser
879         -- will generate Exact RdrNames for them, so the cluttered
880         -- envt is no use.  To avoid doing this filter all the time,
881         -- we use -fno-implicit-prelude as a clue that the filter is
882         -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
883         --
884         -- It's worth doing because it makes the environment smaller for
885         -- every module that imports the Prelude
886   | otherwise
887   = case prov of
888         LocalDef    -> moduleName (nameModule name) == mod
889         Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
890
891 -------------------------------
892 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
893 check_occs ie occs names
894   = foldlM check occs names
895   where
896     check occs name
897       = case lookupOccEnv occs name_occ of
898           Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
899
900           Just (name', ie') 
901             | name == name'     -- Duplicate export
902             ->  do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
903                      warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
904                      returnM occs }
905
906             | otherwise         -- Same occ name but different names: an error
907             ->  do { global_env <- getGlobalRdrEnv ;
908                      addErr (exportClashErr global_env name' name ie' ie) ;
909                      returnM occs }
910       where
911         name_occ = nameOccName name
912 \end{code}
913
914 %*********************************************************
915 %*                                                       *
916                 Deprecations
917 %*                                                       *
918 %*********************************************************
919
920 \begin{code}
921 reportDeprecations :: DynFlags -> TcGblEnv -> RnM ()
922 reportDeprecations dflags tcg_env
923   = ifOptM Opt_WarnDeprecations $
924     do  { (eps,hpt) <- getEpsAndHpt
925                 -- By this time, typechecking is complete, 
926                 -- so the PIT is fully populated
927         ; mapM_ (check hpt (eps_PIT eps)) all_gres }
928   where
929     used_names = allUses (tcg_dus tcg_env) 
930         -- Report on all deprecated uses; hence allUses
931     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
932
933     check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
934       | name `elemNameSet` used_names
935       , Just deprec_txt <- lookupDeprec dflags hpt pit gre
936       = addWarnAt (importSpecLoc imp_spec)
937                   (sep [ptext SLIT("Deprecated use of") <+> 
938                         pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
939                         quotes (ppr name),
940                       (parens imp_msg) <> colon,
941                       (ppr deprec_txt) ])
942         where
943           name_mod = nameModule name
944           imp_mod  = importSpecModule imp_spec
945           imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
946           extra | imp_mod == moduleName name_mod = empty
947                 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
948
949     check hpt pit ok_gre = returnM ()   -- Local, or not used, or not deprectated
950             -- The Imported pattern-match: don't deprecate locally defined names
951             -- For a start, we may be exporting a deprecated thing
952             -- Also we may use a deprecated thing in the defn of another
953             -- deprecated things.  We may even use a deprecated thing in
954             -- the defn of a non-deprecated thing, when changing a module's 
955             -- interface
956
957 lookupDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable 
958              -> GlobalRdrElt -> Maybe DeprecTxt
959 lookupDeprec dflags hpt pit gre
960   = case lookupIfaceByModule dflags hpt pit (nameModule name) of
961         Just iface -> mi_dep_fn iface name `seqMaybe`   -- Bleat if the thing, *or
962                       case gre_par gre of       
963                         ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
964                         NoParent   -> Nothing
965         Nothing    
966           | isWiredInName name -> Nothing
967                 -- We have not necessarily loaded the .hi file for a 
968                 -- wired-in name (yet), although we *could*.
969                 -- And we never deprecate them
970
971          | otherwise -> pprPanic "lookupDeprec" (ppr name)      
972                 -- By now all the interfaces should have been loaded
973   where
974         name = gre_name gre
975 \end{code}
976
977 %*********************************************************
978 %*                                                       *
979                 Unused names
980 %*                                                       *
981 %*********************************************************
982
983 \begin{code}
984 reportUnusedNames :: Maybe [LIE RdrName]        -- Export list
985                   -> TcGblEnv -> RnM ()
986 reportUnusedNames export_decls gbl_env 
987   = do  { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
988         ; warnUnusedTopBinds   unused_locals
989         ; warnUnusedModules    unused_imp_mods
990         ; warnUnusedImports    unused_imports   
991         ; warnDuplicateImports defined_and_used
992         ; printMinimalImports  minimal_imports }
993   where
994     used_names :: NameSet
995     used_names = findUses (tcg_dus gbl_env) emptyNameSet
996         -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
997         -- Hence findUses
998
999         -- Collect the defined names from the in-scope environment
1000     defined_names :: [GlobalRdrElt]
1001     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1002
1003         -- Note that defined_and_used, defined_but_not_used
1004         -- are both [GRE]; that's why we need defined_and_used
1005         -- rather than just used_names
1006     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1007     (defined_and_used, defined_but_not_used) 
1008         = partition (gre_is_used used_names) defined_names
1009     
1010     kids_env = mkChildEnv defined_names
1011         -- This is done in mkExports too; duplicated work
1012
1013     gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1014     gre_is_used used_names (GRE {gre_name = name})
1015         = name `elemNameSet` used_names
1016           || any (`elemNameSet` used_names) (findChildren kids_env name)
1017                 -- A use of C implies a use of T,
1018                 -- if C was brought into scope by T(..) or T(C)
1019
1020         -- Filter out the ones that are 
1021         --  (a) defined in this module, and
1022         --  (b) not defined by a 'deriving' clause 
1023         -- The latter have an Internal Name, so we can filter them out easily
1024     unused_locals :: [GlobalRdrElt]
1025     unused_locals = filter is_unused_local defined_but_not_used
1026     is_unused_local :: GlobalRdrElt -> Bool
1027     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1028     
1029     unused_imports :: [GlobalRdrElt]
1030     unused_imports = filter unused_imp defined_but_not_used
1031     unused_imp (GRE {gre_prov = Imported imp_specs}) 
1032         = not (all (module_unused . importSpecModule) imp_specs)
1033           && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
1034                 -- Don't complain about unused imports if we've already said the
1035                 -- entire import is unused
1036     unused_imp other = False
1037     
1038     -- To figure out the minimal set of imports, start with the things
1039     -- that are in scope (i.e. in gbl_env).  Then just combine them
1040     -- into a bunch of avails, so they are properly grouped
1041     --
1042     -- BUG WARNING: this does not deal properly with qualified imports!
1043     minimal_imports :: FiniteMap ModuleName AvailEnv
1044     minimal_imports0 = foldr add_expall   emptyFM          expall_mods
1045     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
1046     minimal_imports  = foldr add_inst_mod minimal_imports1 direct_import_mods
1047         -- The last line makes sure that we retain all direct imports
1048         -- even if we import nothing explicitly.
1049         -- It's not necessarily redundant to import such modules. Consider 
1050         --            module This
1051         --              import M ()
1052         --
1053         -- The import M() is not *necessarily* redundant, even if
1054         -- we suck in no instance decls from M (e.g. it contains 
1055         -- no instance decls, or This contains no code).  It may be 
1056         -- that we import M solely to ensure that M's orphan instance 
1057         -- decls (or those in its imports) are visible to people who 
1058         -- import This.  Sigh. 
1059         -- There's really no good way to detect this, so the error message 
1060         -- in RnEnv.warnUnusedModules is weakened instead
1061     
1062         -- We've carefully preserved the provenance so that we can
1063         -- construct minimal imports that import the name by (one of)
1064         -- the same route(s) as the programmer originally did.
1065     add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc 
1066         = addToFM_C plusAvailEnv acc 
1067                     (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1068     add_name gre acc = acc      -- Local
1069
1070         -- Modules mentioned as 'module M' in the export list
1071     expall_mods = case export_decls of
1072                     Nothing -> []
1073                     Just es -> [m | L _ (IEModuleContents m) <- es]
1074
1075         -- This is really bogus.  The idea is that if we see 'module M' in 
1076         -- the export list we must retain the import decls that drive it
1077         -- If we aren't careful we might see
1078         --      module A( module M ) where
1079         --        import M
1080         --        import N
1081         -- and suppose that N exports everything that M does.  Then we 
1082         -- must not drop the import of M even though N brings it all into
1083         -- scope.
1084         --
1085         -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1086         --
1087         -- The reason that add_expall is bogus is that it doesn't take
1088         -- qualified imports into account.  But it's an improvement.
1089     add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1090
1091     add_inst_mod (mod,_,_) acc 
1092       | mod_name `elemFM` acc = acc     -- We import something already
1093       | otherwise             = addToFM acc mod_name emptyAvailEnv
1094       where
1095         mod_name = moduleName mod
1096         -- Add an empty collection of imports for a module
1097         -- from which we have sucked only instance decls
1098    
1099     imports = tcg_imports gbl_env
1100
1101     direct_import_mods :: [(Module, Bool, SrcSpan)]
1102         -- See the type of the imp_mods for this triple
1103     direct_import_mods = moduleEnvElts (imp_mods imports)
1104
1105     -- unused_imp_mods are the directly-imported modules 
1106     -- that are not mentioned in minimal_imports1
1107     -- [Note: not 'minimal_imports', because that includes directly-imported
1108     --        modules even if we use nothing from them; see notes above]
1109     --
1110     -- BUG WARNING: does not deal correctly with multiple imports of the same module
1111     --              becuase direct_import_mods has only one entry per module
1112     unused_imp_mods = [(mod_name,loc) | (mod,no_imp,loc) <- direct_import_mods,
1113                        let mod_name = moduleName mod,
1114                        not (mod_name `elemFM` minimal_imports1),
1115                        mod /= pRELUDE,
1116                        not no_imp]
1117         -- The not no_imp part is not to complain about
1118         -- import M (), which is an idiom for importing
1119         -- instance declarations
1120     
1121     module_unused :: ModuleName -> Bool
1122     module_unused mod = any (((==) mod) . fst) unused_imp_mods
1123
1124 ---------------------
1125 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1126 -- Given the GREs for names that are used, figure out which imports 
1127 -- could be omitted without changing the top-level environment.
1128 --
1129 -- NB: Given import Foo( T )
1130 --           import qualified Foo
1131 -- we do not report a duplicate import, even though Foo.T is brought
1132 -- into scope by both, because there's nothing you can *omit* without
1133 -- changing the top-level environment.  So we complain only if it's
1134 -- explicitly named in both imports or neither.
1135 --
1136 -- Furthermore, we complain about Foo.T only if 
1137 -- there is no complaint about (unqualified) T
1138
1139 warnDuplicateImports gres
1140   = ifOptM Opt_WarnUnusedImports $ 
1141     sequenceM_  [ warn name pr
1142                         -- The 'head' picks the first offending group
1143                         -- for this particular name
1144                 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1145                 , pr <- redundants imps ]
1146   where
1147     warn name (red_imp, cov_imp)
1148         = addWarnAt (importSpecLoc red_imp)
1149             (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1150                    ptext SLIT("It is also") <+> ppr cov_imp])
1151         where
1152           pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1153                   | otherwise       = ppr occ
1154           occ = nameOccName name
1155           red_decl = is_decl red_imp
1156     
1157     redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1158         -- The returned pair is (redundant-import, covering-import)
1159     redundants imps 
1160         = [ (red_imp, cov_imp) 
1161           | red_imp <- imps
1162           , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1163
1164         -- "red_imp" is a putative redundant import
1165         -- "cov_imp" potentially covers it
1166         -- This test decides whether red_imp could be dropped 
1167         --
1168         -- NOTE: currently the test does not warn about
1169         --              import M( x )
1170         --              imoprt N( x )
1171         -- even if the same underlying 'x' is involved, because dropping
1172         -- either import would change the qualified names in scope (M.x, N.x)
1173         -- But if the qualified names aren't used, the import is indeed redundant
1174         -- Sadly we don't know that.  Oh well.
1175     covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item }) 
1176            cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1177         | red_loc == cov_loc
1178         = False         -- Ignore diagonal elements
1179         | not (is_as red_decl == is_as cov_decl)
1180         = False         -- They bring into scope different qualified names
1181         | not (is_qual red_decl) && is_qual cov_decl
1182         = False         -- Covering one doesn't bring unqualified name into scope
1183         | red_selective
1184         = not cov_selective     -- Redundant one is selective and covering one isn't
1185           || red_later          -- Both are explicit; tie-break using red_later
1186         | otherwise             
1187         = not cov_selective     -- Neither import is selective
1188           && (is_mod red_decl == is_mod cov_decl)       -- They import the same module
1189           && red_later          -- Tie-break
1190         where
1191           red_loc   = importSpecLoc red_imp
1192           cov_loc   = importSpecLoc cov_imp
1193           red_later = red_loc > cov_loc
1194           cov_selective = selectiveImpItem cov_item
1195           red_selective = selectiveImpItem red_item
1196
1197 selectiveImpItem :: ImpItemSpec -> Bool
1198 selectiveImpItem ImpAll       = False
1199 selectiveImpItem (ImpSome {}) = True
1200
1201 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1202 printMinimalImports :: FiniteMap ModuleName AvailEnv    -- Minimal imports
1203                     -> RnM ()
1204 printMinimalImports imps
1205  = ifOptM Opt_D_dump_minimal_imports $ do {
1206
1207    mod_ies  <-  mappM to_ies (fmToList imps) ;
1208    this_mod <- getModule ;
1209    rdr_env  <- getGlobalRdrEnv ;
1210    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1211                   printForUser h (mkPrintUnqualified rdr_env) 
1212                                  (vcat (map ppr_mod_ie mod_ies)) })
1213    }
1214   where
1215     mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1216     ppr_mod_ie (mod_name, ies) 
1217         | mod_name == moduleName pRELUDE
1218         = empty
1219         | null ies      -- Nothing except instances comes from here
1220         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
1221         | otherwise
1222         = ptext SLIT("import") <+> ppr mod_name <> 
1223                     parens (fsep (punctuate comma (map ppr ies)))
1224
1225     to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1226                                  returnM (mod, ies)
1227
1228     to_ie :: AvailInfo -> RnM (IE Name)
1229         -- The main trick here is that if we're importing all the constructors
1230         -- we want to say "T(..)", but if we're importing only a subset we want
1231         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1232     to_ie (Avail n)       = returnM (IEVar n)
1233     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
1234                             returnM (IEThingAbs n)
1235     to_ie (AvailTC n ns)  
1236         = loadSrcInterface doc n_mod False                      `thenM` \ iface ->
1237           case [xs | (m,as) <- mi_exports iface,
1238                      moduleName m == n_mod,
1239                      AvailTC x xs <- as, 
1240                      x == nameOccName n] of
1241               [xs] | all_used xs -> returnM (IEThingAll n)
1242                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
1243               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1244                                     returnM (IEVar n)
1245         where
1246           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1247           doc = text "Compute minimal imports from" <+> ppr n
1248           n_mod = moduleName (nameModule n)
1249 \end{code}
1250
1251
1252 %************************************************************************
1253 %*                                                                      *
1254 \subsection{Errors}
1255 %*                                                                      *
1256 %************************************************************************
1257
1258 \begin{code}
1259 badImportItemErr iface decl_spec ie
1260   = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1261          ptext SLIT("does not export"), quotes (ppr ie)]
1262   where
1263     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1264                   | otherwise     = empty
1265
1266 illegalImportItemErr = ptext SLIT("Illegal import item")
1267
1268 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1269 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1270
1271 dodgyMsg kind tc
1272   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1273           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1274           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1275           
1276 exportItemErr export_item
1277   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1278           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1279
1280 typeItemErr name wherestr
1281   = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1282           ptext SLIT("Use -findexed-types to enable this extension") ]
1283
1284 exportClashErr global_env name1 name2 ie1 ie2
1285   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1286          , ppr_export ie1 name1 
1287          , ppr_export ie2 name2  ]
1288   where
1289     occ = nameOccName name1
1290     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
1291                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1292
1293         -- get_gre finds a GRE for the Name, so that we can show its provenance
1294     get_gre name
1295         = case lookupGRE_Name global_env name of
1296              (gre:_) -> gre
1297              []      -> pprPanic "exportClashErr" (ppr name)
1298
1299 addDupDeclErr :: Name -> Name -> TcRn ()
1300 addDupDeclErr name_a name_b
1301   = addErrAt (srcLocSpan loc2) $
1302     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1303           ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1304   where
1305     loc2 = nameSrcLoc name2
1306     (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1307                   | otherwise                             = (name_a,name_b)
1308         -- Report the error at the later location
1309
1310 dupExportWarn occ_name ie1 ie2
1311   = hsep [quotes (ppr occ_name), 
1312           ptext SLIT("is exported by"), quotes (ppr ie1),
1313           ptext SLIT("and"),            quotes (ppr ie2)]
1314
1315 dupModuleExport mod
1316   = hsep [ptext SLIT("Duplicate"),
1317           quotes (ptext SLIT("Module") <+> ppr mod), 
1318           ptext SLIT("in export list")]
1319
1320 nullModuleExport mod
1321   = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1322
1323 moduleDeprec mod txt
1324   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
1325           nest 4 (ppr txt) ]      
1326 \end{code}