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