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