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