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