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