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