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