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