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