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