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