658028c3f30f1943b23c5e27e81eb06a5d1b8bfd
[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, mkRdrEnvAndImports, importsFromLocalDecls,
9         rnExports, mkExportNameSet,
10         getLocalDeclBinders, extendRdrEnvRn,
11         reportUnusedNames, reportDeprecations
12     ) where
13
14 #include "HsVersions.h"
15
16 import DynFlags         ( DynFlag(..), GhcMode(..) )
17 import HsSyn            ( IE(..), ieName, ImportDecl(..), LImportDecl,
18                           ForeignDecl(..), HsGroup(..), HsValBinds(..),
19                           Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
20                           LIE )
21 import RnEnv
22 import IfaceEnv         ( ifaceExportNames )
23 import LoadIface        ( loadSrcInterface )
24 import TcRnMonad hiding (LIE)
25
26 import FiniteMap
27 import PrelNames        ( pRELUDE, isUnboundName, main_RDR_Unqual )
28 import Module           ( Module, moduleString, unitModuleEnv, 
29                           lookupModuleEnv, moduleEnvElts, foldModuleEnv )
30 import Name             ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
31                           nameParent, nameParent_maybe, isExternalName,
32                           isBuiltInSyntax )
33 import NameSet
34 import NameEnv
35 import OccName          ( srcDataName, isTcOcc, pprNonVarNameSpace,
36                           occNameSpace,
37                           OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
38                           extendOccEnv )
39 import HscTypes         ( GenAvailInfo(..), AvailInfo,
40                           HomePackageTable, PackageIfaceTable, 
41                           unQualInScope, 
42                           Deprecs(..), ModIface(..), Dependencies(..), 
43                           lookupIface, ExternalPackageState(..)
44                         )
45 import Packages         ( PackageIdH(..) )
46 import RdrName          ( RdrName, rdrNameOcc, setRdrNameSpace, 
47                           GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..), 
48                           emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
49                           extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
50                           Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), 
51                           importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance )
52 import Outputable
53 import Maybes           ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
54 import SrcLoc           ( Located(..), mkGeneralSrcSpan,
55                           unLoc, noLoc, srcLocSpan, SrcSpan )
56 import BasicTypes       ( DeprecTxt )
57 import DriverPhases     ( isHsBoot )
58 import Util             ( notNull )
59 import List             ( partition )
60 import IO               ( openFile, IOMode(..) )
61 \end{code}
62
63
64
65 %************************************************************************
66 %*                                                                      *
67                 rnImports
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
73 rnImports imports
74          -- PROCESS IMPORT DECLS
75          -- Do the non {- SOURCE -} ones first, so that we get a helpful
76          -- warning for {- SOURCE -} ones that are unnecessary
77     = do this_mod <- getModule
78          implicit_prelude <- doptM Opt_ImplicitPrelude
79          let all_imports               = mk_prel_imports this_mod implicit_prelude ++ imports
80              (source, ordinary) = partition is_source_import all_imports
81              is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
82              get_imports = rnImportDecl this_mod
83
84          stuff1 <- mapM get_imports ordinary
85          stuff2 <- mapM get_imports source
86          return (stuff1 ++ stuff2)
87     where
88 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
89 -- because the former doesn't even look at Prelude.hi for instance 
90 -- declarations, whereas the latter does.
91    mk_prel_imports this_mod implicit_prelude
92        |  this_mod == pRELUDE
93           || explicit_prelude_import
94           || not implicit_prelude
95            = []
96        | otherwise = [preludeImportDecl]
97    explicit_prelude_import
98        = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports, 
99                    unLoc mod == pRELUDE ]
100
101 preludeImportDecl :: LImportDecl RdrName
102 preludeImportDecl
103   = L loc $
104         ImportDecl (L loc pRELUDE)
105                False {- Not a boot interface -}
106                False    {- Not qualified -}
107                Nothing  {- No "as" -}
108                Nothing  {- No import list -}
109   where
110     loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")         
111
112 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
113 mkRdrEnvAndImports imports
114   = do this_mod <- getModule
115        let get_imports = importsFromImportDecl this_mod
116        stuff <- mapM get_imports imports
117        let (imp_gbl_envs, imp_avails) = unzip stuff
118            gbl_env :: GlobalRdrEnv
119            gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
120
121            all_avails :: ImportAvails
122            all_avails = foldr plusImportAvails emptyImportAvails imp_avails
123        -- ALL DONE
124        return (gbl_env, all_avails)
125
126 \end{code}
127         
128 \begin{code}
129 rnImportDecl :: Module
130              -> LImportDecl RdrName
131              -> RnM (LImportDecl Name)
132 rnImportDecl this_mod (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
133     = setSrcSpan loc $
134       do iface <- loadSrcInterface doc imp_mod_name want_boot
135          let qual_mod_name = case as_mod of
136                                Nothing           -> imp_mod_name
137                                Just another_name -> another_name
138              imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
139                                        is_dloc = loc, is_as = qual_mod_name }
140          total_avails <- ifaceExportNames (mi_exports iface)
141          importDecl' <- rnImportDecl' iface imp_spec importDecl total_avails
142          return (L loc importDecl')
143     where imp_mod_name = unLoc loc_imp_mod_name
144           doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
145
146 rnImportDecl' :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
147 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod Nothing) all_names
148     = return $ ImportDecl mod_name want_boot qual_only as_mod Nothing
149 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
150     = do import_items_mbs <- mapM (srcSpanWrapper) import_items
151          let rn_import_items = concat . catMaybes $ import_items_mbs
152          return $ ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
153     where
154     srcSpanWrapper (L span ieRdr)
155         = setSrcSpan span $
156           case get_item ieRdr of
157             Nothing
158                 -> do addErr (badImportItemErr iface decl_spec ieRdr)
159                       return Nothing
160             Just ieNames
161                 -> return (Just [L span ie | ie <- ieNames])
162     occ_env :: OccEnv Name      -- Maps OccName to corresponding Name
163     occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
164         -- This env will have entries for data constructors too,
165         -- they won't make any difference because naked entities like T
166         -- in an import list map to TcOccs, not VarOccs.
167
168     sub_env :: NameEnv [Name]
169     sub_env = mkSubNameEnv all_names
170
171     get_item :: IE RdrName -> Maybe [IE Name]
172         -- Empty result for a bad item.
173         -- Singleton result is typical case.
174         -- Can have two when we are hiding, and mention C which might be
175         --      both a class and a data constructor.  
176     get_item item@(IEModuleContents _) 
177         = Nothing
178     get_item (IEThingAll tc)
179         = do name <- check_name tc
180              return [IEThingAll name]
181     get_item (IEThingAbs tc)
182         | want_hiding   -- hiding ( C )
183                         -- Here the 'C' can be a data constructor 
184                         --  *or* a type/class, or even both
185             = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
186                 []    -> Nothing
187                 names -> return [ IEThingAbs n | n <- names ]
188         | otherwise
189             = do name <- check_name tc
190                  return [IEThingAbs name]
191     get_item (IEThingWith n ns) -- import (C (A,B))
192         = do name <- check_name n
193              let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
194                  mb_names = map (lookupOccEnv env . rdrNameOcc) ns
195              names <- sequence mb_names
196              return [IEThingWith name names]
197     get_item (IEVar n)
198         = do name <- check_name n
199              return [IEVar name]
200
201     check_name :: RdrName -> Maybe Name
202     check_name rdrName
203         = lookupOccEnv occ_env (rdrNameOcc rdrName)
204
205
206 importsFromImportDecl :: Module
207                       -> LImportDecl Name
208                       -> RnM (GlobalRdrEnv, ImportAvails)
209
210 importsFromImportDecl this_mod
211         (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
212   = 
213     setSrcSpan loc $
214
215         -- If there's an error in loadInterface, (e.g. interface
216         -- file not found) we get lots of spurious errors from 'filterImports'
217     let
218         imp_mod_name = unLoc loc_imp_mod_name
219         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
220     in
221     loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
222
223         -- Compiler sanity check: if the import didn't say
224         -- {-# SOURCE #-} we should not get a hi-boot file
225     WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
226
227         -- Issue a user warning for a redundant {- SOURCE -} import
228         -- NB that we arrange to read all the ordinary imports before 
229         -- any of the {- SOURCE -} imports
230     warnIf (want_boot && not (mi_boot iface))
231            (warnRedundantSourceImport imp_mod_name)     `thenM_`
232
233     let
234         imp_mod = mi_module iface
235         deprecs = mi_deprecs iface
236         is_orph = mi_orphan iface 
237         deps    = mi_deps iface
238
239         filtered_exports = filter not_this_mod (mi_exports iface)
240         not_this_mod (mod,_) = mod /= this_mod
241         -- If the module exports anything defined in this module, just ignore it.
242         -- Reason: otherwise it looks as if there are two local definition sites
243         -- for the thing, and an error gets reported.  Easiest thing is just to
244         -- filter them out up front. This situation only arises if a module
245         -- imports itself, or another module that imported it.  (Necessarily,
246         -- this invoves a loop.)  
247         --
248         -- Tiresome consequence: if you say
249         --      module A where
250         --         import B( AType )
251         --         type AType = ...
252         --
253         --      module B( AType ) where
254         --         import {-# SOURCE #-} A( AType )
255         --
256         -- then you'll get a 'B does not export AType' message.  Oh well.
257
258         qual_mod_name = case as_mod of
259                           Nothing           -> imp_mod_name
260                           Just another_name -> another_name
261         imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
262                                   is_dloc = loc, is_as = qual_mod_name }
263     in
264         -- Get the total imports, and filter them according to the import list
265     ifaceExportNames filtered_exports           `thenM` \ total_avails ->
266     filterImports iface imp_spec
267                   imp_details total_avails      `thenM` \ (avail_env, gbl_env) ->
268
269     getDOpts `thenM` \ dflags ->
270
271     let
272         -- Compute new transitive dependencies
273
274         orphans | is_orph   = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
275                               imp_mod_name : dep_orphs deps
276                 | otherwise = dep_orphs deps
277
278         (dependent_mods, dependent_pkgs) 
279            = case mi_package iface of
280                 HomePackage ->
281                 -- Imported module is from the home package
282                 -- Take its dependent modules and add imp_mod itself
283                 -- Take its dependent packages unchanged
284                 --
285                 -- NB: (dep_mods deps) might include a hi-boot file
286                 -- for the module being compiled, CM. Do *not* filter
287                 -- this out (as we used to), because when we've
288                 -- finished dealing with the direct imports we want to
289                 -- know if any of them depended on CM.hi-boot, in
290                 -- which case we should do the hi-boot consistency
291                 -- check.  See LoadIface.loadHiBootInterface
292                   ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
293
294                 ExtPackage pkg ->
295                 -- Imported module is from another package
296                 -- Dump the dependent modules
297                 -- Add the package imp_mod comes from to the dependent packages
298                  ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
299                  ([], pkg : dep_pkgs deps)
300
301         -- True <=> import M ()
302         import_all = case imp_details of
303                         Just (is_hiding, ls) -> not is_hiding && null ls        
304                         other                -> False
305
306         -- unqual_avails is the Avails that are visible in *unqualified* form
307         -- We need to know this so we know what to export when we see
308         --      module M ( module P ) where ...
309         -- Then we must export whatever came from P unqualified.
310         imports   = ImportAvails { 
311                         imp_env      = unitModuleEnv qual_mod_name avail_env,
312                         imp_mods     = unitModuleEnv imp_mod (imp_mod, import_all, loc),
313                         imp_orphs    = orphans,
314                         imp_dep_mods = mkModDeps dependent_mods,
315                         imp_dep_pkgs = dependent_pkgs }
316
317     in
318         -- Complain if we import a deprecated module
319     ifOptM Opt_WarnDeprecations (
320        case deprecs of  
321           DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
322           other         -> returnM ()
323     )                                                   `thenM_`
324
325     returnM (gbl_env, imports)
326
327 warnRedundantSourceImport mod_name
328   = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
329           <+> quotes (ppr mod_name)
330 \end{code}
331
332
333 %************************************************************************
334 %*                                                                      *
335                 importsFromLocalDecls
336 %*                                                                      *
337 %************************************************************************
338
339 From the top-level declarations of this module produce
340         * the lexical environment
341         * the ImportAvails
342 created by its bindings.  
343         
344 Complain about duplicate bindings
345
346 \begin{code}
347 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
348 importsFromLocalDecls group
349   = do  { gbl_env  <- getGblEnv
350
351         ; names <- getLocalDeclBinders gbl_env group
352
353         ; implicit_prelude <- doptM Opt_ImplicitPrelude
354         ; let {
355             -- Optimisation: filter out names for built-in syntax
356             -- They just clutter up the environment (esp tuples), and the parser
357             -- will generate Exact RdrNames for them, so the cluttered
358             -- envt is no use.  To avoid doing this filter all the time,
359             -- we use -fno-implicit-prelude as a clue that the filter is
360             -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
361             --
362             -- It's worth doing because it makes the environment smaller for
363             -- every module that imports the Prelude
364             --
365             -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
366             -- in defn of gres above).      Stupid reason: when parsing 
367             -- data type decls, the constructors start as Exact tycon-names,
368             -- and then get turned into data con names by zapping the name space;
369             -- but that stops them being Exact, so they get looked up.  
370             -- Ditto in fixity decls; e.g.      infix 5 :
371             -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
372             -- The important thing is to trim down the exports.
373               filtered_names 
374                 | implicit_prelude = names
375                 | otherwise        = filter (not . isBuiltInSyntax) names ;
376
377             ; this_mod = tcg_mod gbl_env
378             ; imports = emptyImportAvails {
379                           imp_env = unitModuleEnv this_mod $
380                                     mkNameSet filtered_names
381                         }
382             }
383
384         ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
385
386         ; returnM (gbl_env { tcg_rdr_env = rdr_env',
387                              tcg_imports = imports `plusImportAvails` tcg_imports gbl_env }) 
388         }
389
390 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
391 -- Add the new locally-bound names one by one, checking for duplicates as
392 -- we do so.  Remember that in Template Haskell the duplicates
393 -- might *already be* in the GlobalRdrEnv from higher up the module
394 extendRdrEnvRn rdr_env names
395   = foldlM add_local rdr_env names
396   where
397     add_local rdr_env name
398         | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
399         , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
400         = do { addDupDeclErr (gre_name dup_gre) name
401              ; return rdr_env }
402         | otherwise
403         = return (extendGlobalRdrEnv rdr_env new_gre)
404         where
405           new_gre = GRE {gre_name = name, gre_prov = LocalDef}
406 \end{code}
407
408 @getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
409 used for source code.
410
411         *** See "THE NAMING STORY" in HsDecls ****
412
413 \begin{code}
414 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
415 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs, 
416                                       hs_tyclds = tycl_decls, 
417                                       hs_fords = foreign_decls })
418   = do  { tc_names_s <- mappM new_tc tycl_decls
419         ; val_names  <- mappM new_simple val_bndrs
420         ; return (foldr (++) val_names tc_names_s) }
421   where
422     mod        = tcg_mod gbl_env
423     is_hs_boot = isHsBoot (tcg_src gbl_env) ;
424     val_bndrs | is_hs_boot = sig_hs_bndrs
425               | otherwise  = for_hs_bndrs ++ val_hs_bndrs
426         -- In a hs-boot file, the value binders come from the
427         --  *signatures*, and there should be no foreign binders 
428
429     new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
430
431     sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
432     val_hs_bndrs = collectHsBindLocatedBinders val_decls
433     for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
434
435     new_tc tc_decl 
436         = do { main_name <- newTopSrcBinder mod Nothing main_rdr
437              ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
438              ; return (main_name : sub_names) }
439         where
440           (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
441 \end{code}
442
443
444 %************************************************************************
445 %*                                                                      *
446 \subsection{Filtering imports}
447 %*                                                                      *
448 %************************************************************************
449
450 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
451 available, and filters it through the import spec (if any).
452
453 \begin{code}
454 filterImports :: ModIface
455               -> ImpDeclSpec                    -- The span for the entire import decl
456               -> Maybe (Bool, [LIE Name])       -- Import spec; True => hiding
457               -> NameSet                        -- What's available
458               -> RnM (NameSet,                  -- What's imported (qualified or unqualified)
459                       GlobalRdrEnv)             -- Same again, but in GRE form
460
461         -- Complains if import spec mentions things that the module doesn't export
462         -- Warns/informs if import spec contains duplicates.
463                         
464 mkGenericRdrEnv decl_spec names
465   = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
466                    | name <- nameSetToList names ]
467   where
468     imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
469
470 filterImports iface decl_spec Nothing all_names
471   = return (all_names, mkGenericRdrEnv decl_spec all_names)
472
473 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
474   = mapM (addLocM get_item) import_items >>= \gres_s ->
475     let gres = concat gres_s
476         specified_names = mkNameSet (map gre_name gres)
477     in if not want_hiding then
478        return (specified_names, mkGlobalRdrEnv gres)
479     else let keep n = not (n `elemNameSet` specified_names)
480              pruned_avails = filterNameSet keep all_names
481          in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
482   where
483     sub_env :: NameEnv [Name]   -- Classify each name by its parent
484     sub_env = mkSubNameEnv all_names
485
486     succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
487     succeed_with all_explicit names
488       = do { loc <- getSrcSpanM
489            ; returnM (map (mk_gre loc) names) }
490       where
491         mk_gre loc name = GRE { gre_name = name, 
492                                 gre_prov = Imported [imp_spec] }
493           where
494             imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
495             item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
496             explicit  = all_explicit || isNothing (nameParent_maybe name)
497
498     get_item :: IE Name -> RnM [GlobalRdrElt]
499         -- Empty result for a bad item.
500         -- Singleton result is typical case.
501         -- Can have two when we are hiding, and mention C which might be
502         --      both a class and a data constructor.  
503     get_item item@(IEModuleContents _) 
504         -- This case should be filtered out by 'rnImports'.
505         = panic "filterImports: IEModuleContents?" 
506
507     get_item (IEThingAll name)
508         = case subNames sub_env name of
509             [] ->       -- This occurs when you import T(..), but
510                         -- only export T abstractly.
511                   do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
512                      succeed_with False [name]
513             names -> succeed_with False (name:names)
514
515     get_item (IEThingAbs name)
516         = succeed_with True [name]
517
518     get_item (IEThingWith name names)
519         = succeed_with True (name:names)
520     get_item (IEVar name)
521         = succeed_with True [name]
522
523 \end{code}
524
525
526 %************************************************************************
527 %*                                                                      *
528 \subsection{Export list processing}
529 %*                                                                      *
530 %************************************************************************
531
532 Processing the export list.
533
534 You might think that we should record things that appear in the export
535 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
536 wrong.  We do check (here) that they are in scope, but there is no
537 need to slurp in their actual declaration (which is what
538 @addOccurrenceName@ forces).
539
540 Indeed, doing so would big trouble when compiling @PrelBase@, because
541 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
542 @ConcBase.StateAndSynchVar#@, and so on...
543
544 \begin{code}
545 type ExportAccum        -- The type of the accumulating parameter of
546                         -- the main worker function in rnExports
547      = ([Module],               -- 'module M's seen so far
548         ExportOccMap,           -- Tracks exported occurrence names
549         NameSet)                -- The accumulated exported stuff
550 emptyExportAccum = ([], emptyOccEnv, emptyNameSet) 
551
552 type ExportOccMap = OccEnv (Name, IE RdrName)
553         -- Tracks what a particular exported OccName
554         --   in an export list refers to, and which item
555         --   it came from.  It's illegal to export two distinct things
556         --   that have the same occurrence name
557
558 rnExports :: Maybe [LIE RdrName]
559           -> RnM (Maybe [LIE Name])
560 rnExports Nothing = return Nothing
561 rnExports (Just exports)
562     = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
563          let sub_env :: NameEnv [Name]  -- Classify each name by its parent
564              sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
565              rnExport (IEVar rdrName)
566                  = do name <- lookupGlobalOccRn rdrName
567                       return (IEVar name)
568              rnExport (IEThingAbs rdrName)
569                  = do name <- lookupGlobalOccRn rdrName
570                       return (IEThingAbs name)
571              rnExport (IEThingAll rdrName)
572                  = do name <- lookupGlobalOccRn rdrName
573                       return (IEThingAll name)
574              rnExport ie@(IEThingWith rdrName rdrNames)
575                  = do name <- lookupGlobalOccRn rdrName
576                       if isUnboundName name
577                          then return (IEThingWith name [])
578                          else do
579                       let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
580                           mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
581                       if any isNothing mb_names
582                          then do addErr (exportItemErr ie)
583                                  return (IEThingWith name [])
584                          else return (IEThingWith name (catMaybes mb_names))
585              rnExport (IEModuleContents mod)
586                  = return (IEModuleContents mod)
587          rn_exports <- mapM (wrapLocM rnExport) exports
588          return (Just rn_exports)
589
590 mkExportNameSet :: Bool  -- False => no 'module M(..) where' header at all
591                 -> Maybe ([LIE Name], [LIE RdrName]) -- Nothing => no explicit export list
592                 -> RnM NameSet
593         -- Complains if two distinct exports have same OccName
594         -- Warns about identical exports.
595         -- Complains about exports items not in scope
596
597 mkExportNameSet explicit_mod exports
598  = do TcGblEnv { tcg_rdr_env = rdr_env, 
599                  tcg_imports = imports } <- getGblEnv
600
601         -- If the module header is omitted altogether, then behave
602         -- as if the user had written "module Main(main) where..."
603         -- EXCEPT in interactive mode, when we behave as if he had
604         -- written "module Main where ..."
605         -- Reason: don't want to complain about 'main' not in scope
606         --         in interactive mode
607       ghc_mode <- getGhcMode
608       real_exports <- case () of
609                         () | explicit_mod
610                                -> return exports
611                            | ghc_mode == Interactive
612                                -> return Nothing
613                            | otherwise
614                                -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
615                                      return (Just ([noLoc (IEVar mainName)]
616                                                   ,[noLoc (IEVar main_RDR_Unqual)]))
617                 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
618       exports_from_avail real_exports rdr_env imports
619
620
621 exports_from_avail Nothing rdr_env imports
622  =      -- Export all locally-defined things
623         -- We do this by filtering the global RdrEnv,
624         -- keeping only things that are locally-defined
625    return (mkNameSet [ gre_name gre 
626                      | gre <- globalRdrEnvElts rdr_env,
627                        isLocalGRE gre ])
628
629 exports_from_avail (Just (items,origItems)) rdr_env (ImportAvails { imp_env = imp_env }) 
630   = do (_, _, exports) <- foldlM do_litem emptyExportAccum (zip items origItems)
631        return exports
632   where
633     sub_env :: NameEnv [Name]   -- Classify each name by its parent
634     sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
635
636     do_litem :: ExportAccum -> (LIE Name, LIE RdrName) -> RnM ExportAccum
637     do_litem acc (ieName, ieRdr)
638         = addLocM (exports_from_item acc (unLoc ieRdr)) ieName
639
640     exports_from_item :: ExportAccum -> IE RdrName -> IE Name -> RnM ExportAccum
641     exports_from_item acc@(mods, occs, exports) ieRdr@(IEModuleContents mod) ie
642         | mod `elem` mods       -- Duplicate export of M
643         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
644                warnIf warn_dup_exports (dupModuleExport mod) ;
645                returnM acc }
646
647         | otherwise
648         = case lookupModuleEnv imp_env mod of
649             Nothing -> do addErr (modExportErr mod)
650                           return acc
651             Just names
652                 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
653                       -- This check_occs not only finds conflicts between this item
654                       -- and others, but also internally within this item.  That is,
655                       -- if 'M.x' is in scope in several ways, we'll have several
656                       -- members of mod_avails with the same OccName.
657                       occs' <- check_occs ieRdr occs (nameSetToList new_exports)
658                       return (mod:mods, occs', exports `unionNameSets` new_exports)
659
660     exports_from_item acc@(mods, occs, exports) ieRdr ie
661         = if isUnboundName (ieName ie)
662           then return acc       -- Avoid error cascade
663           else let new_exports = filterAvail ie sub_env in
664           do -- checkErr (not (null (drop 1 new_exports))) (exportItemErr ie)
665              checkForDodgyExport ie new_exports
666              occs' <- check_occs ieRdr occs new_exports
667              return (mods, occs', addListToNameSet exports new_exports)
668           
669 -------------------------------
670 filterAvail :: IE Name          -- Wanted
671             -> NameEnv [Name]   -- Maps type/class names to their sub-names
672             -> [Name]
673
674 filterAvail (IEVar n)          subs = [n]
675 filterAvail (IEThingAbs n)     subs = [n]
676 filterAvail (IEThingAll n)     subs = n : subNames subs n
677 filterAvail (IEThingWith n ns) subs = n : ns
678 filterAvail (IEModuleContents _) _  = panic "filterAvail"
679
680 subNames :: NameEnv [Name] -> Name -> [Name]
681 subNames env n = lookupNameEnv env n `orElse` []
682
683 mkSubNameEnv :: NameSet -> NameEnv [Name]
684 -- Maps types and classes to their constructors/classops respectively
685 -- This mapping just makes it easier to deal with A(..) export items
686 mkSubNameEnv names
687   = foldNameSet add_name emptyNameEnv names
688   where
689     add_name name env 
690         | Just parent <- nameParent_maybe name 
691         = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
692         | otherwise = env
693
694 -------------------------------
695 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
696 -- Checks whether the Name is in scope unqualified, 
697 -- regardless of whether it's ambiguous or not
698 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
699
700 -------------------------------
701 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
702 checkForDodgyExport ie@(IEThingAll tc) [n] 
703   | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
704         -- This occurs when you export T(..), but
705         -- only import T abstractly, or T is a synonym.  
706         -- The single [n] is the type or class itself
707   | otherwise = addErr (exportItemErr ie)
708         -- This happes if you export x(..), which is bogus
709 checkForDodgyExport _ _ = return ()
710
711 -------------------------------
712 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
713 check_occs ie occs names
714   = foldlM check occs names
715   where
716     check occs name
717       = case lookupOccEnv occs name_occ of
718           Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
719
720           Just (name', ie') 
721             | name == name'     -- Duplicate export
722             ->  do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
723                      warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
724                      returnM occs }
725
726             | otherwise         -- Same occ name but different names: an error
727             ->  do { global_env <- getGlobalRdrEnv ;
728                      addErr (exportClashErr global_env name name' ie ie') ;
729                      returnM occs }
730       where
731         name_occ = nameOccName name
732 \end{code}
733
734 %*********************************************************
735 %*                                                       *
736                 Deprecations
737 %*                                                       *
738 %*********************************************************
739
740 \begin{code}
741 reportDeprecations :: TcGblEnv -> RnM ()
742 reportDeprecations tcg_env
743   = ifOptM Opt_WarnDeprecations $
744     do  { (eps,hpt) <- getEpsAndHpt
745                 -- By this time, typechecking is complete, 
746                 -- so the PIT is fully populated
747         ; mapM_ (check hpt (eps_PIT eps)) all_gres }
748   where
749     used_names = allUses (tcg_dus tcg_env) 
750         -- Report on all deprecated uses; hence allUses
751     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
752
753     check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
754       | name `elemNameSet` used_names
755       , Just deprec_txt <- lookupDeprec hpt pit name
756       = setSrcSpan (importSpecLoc imp_spec) $
757         addWarn (sep [ptext SLIT("Deprecated use of") <+> 
758                         pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
759                         quotes (ppr name),
760                       (parens imp_msg) <> colon,
761                       (ppr deprec_txt) ])
762         where
763           name_mod = nameModule name
764           imp_mod  = importSpecModule imp_spec
765           imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
766           extra | imp_mod == name_mod = empty
767                 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
768
769     check hpt pit ok_gre = returnM ()   -- Local, or not used, or not deprectated
770             -- The Imported pattern-match: don't deprecate locally defined names
771             -- For a start, we may be exporting a deprecated thing
772             -- Also we may use a deprecated thing in the defn of another
773             -- deprecated things.  We may even use a deprecated thing in
774             -- the defn of a non-deprecated thing, when changing a module's 
775             -- interface
776
777 lookupDeprec :: HomePackageTable -> PackageIfaceTable 
778              -> Name -> Maybe DeprecTxt
779 lookupDeprec hpt pit n 
780   = case lookupIface hpt pit (nameModule n) of
781         Just iface -> mi_dep_fn iface n `seqMaybe`      -- Bleat if the thing, *or
782                       mi_dep_fn iface (nameParent n)    -- its parent*, is deprec'd
783         Nothing    
784           | isWiredInName n -> Nothing
785                 -- We have not necessarily loaded the .hi file for a 
786                 -- wired-in name (yet), although we *could*.
787                 -- And we never deprecate them
788
789          | otherwise -> pprPanic "lookupDeprec" (ppr n) 
790                 -- By now all the interfaces should have been loaded
791
792 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
793 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
794 \end{code}
795
796 %*********************************************************
797 %*                                                       *
798                 Unused names
799 %*                                                       *
800 %*********************************************************
801
802 \begin{code}
803 reportUnusedNames :: Maybe [LIE RdrName]        -- Export list
804                   -> TcGblEnv -> RnM ()
805 reportUnusedNames export_decls gbl_env 
806   = do  { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
807         ; warnUnusedTopBinds   unused_locals
808         ; warnUnusedModules    unused_imp_mods
809         ; warnUnusedImports    unused_imports   
810         ; warnDuplicateImports defined_and_used
811         ; printMinimalImports  minimal_imports }
812   where
813     used_names, all_used_names :: NameSet
814     used_names = findUses (tcg_dus gbl_env) emptyNameSet
815         -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
816         -- Hence findUses
817
818     all_used_names = used_names `unionNameSets` 
819                      mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
820                         -- A use of C implies a use of T,
821                         -- if C was brought into scope by T(..) or T(C)
822
823         -- Collect the defined names from the in-scope environment
824     defined_names :: [GlobalRdrElt]
825     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
826
827         -- Note that defined_and_used, defined_but_not_used
828         -- are both [GRE]; that's why we need defined_and_used
829         -- rather than just all_used_names
830     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
831     (defined_and_used, defined_but_not_used) 
832         = partition (gre_is_used all_used_names) defined_names
833     
834         -- Filter out the ones that are 
835         --  (a) defined in this module, and
836         --  (b) not defined by a 'deriving' clause 
837         -- The latter have an Internal Name, so we can filter them out easily
838     unused_locals :: [GlobalRdrElt]
839     unused_locals = filter is_unused_local defined_but_not_used
840     is_unused_local :: GlobalRdrElt -> Bool
841     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
842     
843     unused_imports :: [GlobalRdrElt]
844     unused_imports = filter unused_imp defined_but_not_used
845     unused_imp (GRE {gre_prov = Imported imp_specs}) 
846         = not (all (module_unused . importSpecModule) imp_specs)
847           && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
848                 -- Don't complain about unused imports if we've already said the
849                 -- entire import is unused
850     unused_imp other = False
851     
852     -- To figure out the minimal set of imports, start with the things
853     -- that are in scope (i.e. in gbl_env).  Then just combine them
854     -- into a bunch of avails, so they are properly grouped
855     --
856     -- BUG WARNING: this does not deal properly with qualified imports!
857     minimal_imports :: FiniteMap Module AvailEnv
858     minimal_imports0 = foldr add_expall   emptyFM          expall_mods
859     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
860     minimal_imports  = foldr add_inst_mod minimal_imports1 direct_import_mods
861         -- The last line makes sure that we retain all direct imports
862         -- even if we import nothing explicitly.
863         -- It's not necessarily redundant to import such modules. Consider 
864         --            module This
865         --              import M ()
866         --
867         -- The import M() is not *necessarily* redundant, even if
868         -- we suck in no instance decls from M (e.g. it contains 
869         -- no instance decls, or This contains no code).  It may be 
870         -- that we import M solely to ensure that M's orphan instance 
871         -- decls (or those in its imports) are visible to people who 
872         -- import This.  Sigh. 
873         -- There's really no good way to detect this, so the error message 
874         -- in RnEnv.warnUnusedModules is weakened instead
875     
876         -- We've carefully preserved the provenance so that we can
877         -- construct minimal imports that import the name by (one of)
878         -- the same route(s) as the programmer originally did.
879     add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc 
880         = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
881                     (unitAvailEnv (mk_avail n (nameParent_maybe n)))
882     add_name other acc 
883         = acc
884
885         -- Modules mentioned as 'module M' in the export list
886     expall_mods = case export_decls of
887                     Nothing -> []
888                     Just es -> [m | L _ (IEModuleContents m) <- es]
889
890         -- This is really bogus.  The idea is that if we see 'module M' in 
891         -- the export list we must retain the import decls that drive it
892         -- If we aren't careful we might see
893         --      module A( module M ) where
894         --        import M
895         --        import N
896         -- and suppose that N exports everything that M does.  Then we 
897         -- must not drop the import of M even though N brings it all into
898         -- scope.
899         --
900         -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
901         --
902         -- The reason that add_expall is bogus is that it doesn't take
903         -- qualified imports into account.  But it's an improvement.
904     add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
905
906         -- n is the name of the thing, p is the name of its parent
907     mk_avail n (Just p)                          = AvailTC p [p,n]
908     mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
909                        | otherwise               = Avail n
910     
911     add_inst_mod (mod,_,_) acc 
912       | mod `elemFM` acc = acc  -- We import something already
913       | otherwise        = addToFM acc mod emptyAvailEnv
914       where
915         -- Add an empty collection of imports for a module
916         -- from which we have sucked only instance decls
917    
918     imports = tcg_imports gbl_env
919
920     direct_import_mods :: [(Module, Bool, SrcSpan)]
921         -- See the type of the imp_mods for this triple
922     direct_import_mods = moduleEnvElts (imp_mods imports)
923
924     -- unused_imp_mods are the directly-imported modules 
925     -- that are not mentioned in minimal_imports1
926     -- [Note: not 'minimal_imports', because that includes directly-imported
927     --        modules even if we use nothing from them; see notes above]
928     --
929     -- BUG WARNING: does not deal correctly with multiple imports of the same module
930     --              becuase direct_import_mods has only one entry per module
931     unused_imp_mods = [(mod,loc) | (mod,no_imp,loc) <- direct_import_mods,
932                        not (mod `elemFM` minimal_imports1),
933                        mod /= pRELUDE,
934                        not no_imp]
935         -- The not no_imp part is not to complain about
936         -- import M (), which is an idiom for importing
937         -- instance declarations
938     
939     module_unused :: Module -> Bool
940     module_unused mod = any (((==) mod) . fst) unused_imp_mods
941
942 ---------------------
943 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
944 -- Given the GREs for names that are used, figure out which imports 
945 -- could be omitted without changing the top-level environment.
946 --
947 -- NB: Given import Foo( T )
948 --           import qualified Foo
949 -- we do not report a duplicate import, even though Foo.T is brought
950 -- into scope by both, because there's nothing you can *omit* without
951 -- changing the top-level environment.  So we complain only if it's
952 -- explicitly named in both imports or neither.
953 --
954 -- Furthermore, we complain about Foo.T only if 
955 -- there is no complaint about (unqualified) T
956
957 warnDuplicateImports gres
958   = ifOptM Opt_WarnUnusedImports $ 
959     sequenceM_  [ warn name pr
960                         -- The 'head' picks the first offending group
961                         -- for this particular name
962                 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
963                 , pr <- redundants imps ]
964   where
965     warn name (red_imp, cov_imp)
966         = addWarnAt (importSpecLoc red_imp)
967             (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
968                    ptext SLIT("It is also") <+> ppr cov_imp])
969         where
970           pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
971                   | otherwise       = ppr occ
972           occ = nameOccName name
973           red_decl = is_decl red_imp
974     
975     redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
976         -- The returned pair is (redundant-import, covering-import)
977     redundants imps 
978         = [ (red_imp, cov_imp) 
979           | red_imp <- imps
980           , cov_imp <- take 1 (filter (covers red_imp) imps) ]
981
982         -- "red_imp" is a putative redundant import
983         -- "cov_imp" potentially covers it
984         -- This test decides whether red_imp could be dropped 
985         --
986         -- NOTE: currently the test does not warn about
987         --              import M( x )
988         --              imoprt N( x )
989         -- even if the same underlying 'x' is involved, because dropping
990         -- either import would change the qualified names in scope (M.x, N.x)
991         -- But if the qualified names aren't used, the import is indeed redundant
992         -- Sadly we don't know that.  Oh well.
993     covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item }) 
994            cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
995         | red_loc == cov_loc
996         = False         -- Ignore diagonal elements
997         | not (is_as red_decl == is_as cov_decl)
998         = False         -- They bring into scope different qualified names
999         | not (is_qual red_decl) && is_qual cov_decl
1000         = False         -- Covering one doesn't bring unqualified name into scope
1001         | red_selective
1002         = not cov_selective     -- Redundant one is selective and covering one isn't
1003           || red_later          -- Both are explicit; tie-break using red_later
1004         | otherwise             
1005         = not cov_selective     -- Neither import is selective
1006           && (is_mod red_decl == is_mod cov_decl)       -- They import the same module
1007           && red_later          -- Tie-break
1008         where
1009           red_loc   = importSpecLoc red_imp
1010           cov_loc   = importSpecLoc cov_imp
1011           red_later = red_loc > cov_loc
1012           cov_selective = selectiveImpItem cov_item
1013           red_selective = selectiveImpItem red_item
1014
1015 selectiveImpItem :: ImpItemSpec -> Bool
1016 selectiveImpItem ImpAll       = False
1017 selectiveImpItem (ImpSome {}) = True
1018
1019 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1020 printMinimalImports :: FiniteMap Module AvailEnv        -- Minimal imports
1021                     -> RnM ()
1022 printMinimalImports imps
1023  = ifOptM Opt_D_dump_minimal_imports $ do {
1024
1025    mod_ies  <-  mappM to_ies (fmToList imps) ;
1026    this_mod <- getModule ;
1027    rdr_env  <- getGlobalRdrEnv ;
1028    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1029                   printForUser h (unQualInScope rdr_env) 
1030                                  (vcat (map ppr_mod_ie mod_ies)) })
1031    }
1032   where
1033     mkFilename this_mod = moduleString this_mod ++ ".imports"
1034     ppr_mod_ie (mod_name, ies) 
1035         | mod_name == pRELUDE 
1036         = empty
1037         | null ies      -- Nothing except instances comes from here
1038         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
1039         | otherwise
1040         = ptext SLIT("import") <+> ppr mod_name <> 
1041                     parens (fsep (punctuate comma (map ppr ies)))
1042
1043     to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1044                                  returnM (mod, ies)
1045
1046     to_ie :: AvailInfo -> RnM (IE Name)
1047         -- The main trick here is that if we're importing all the constructors
1048         -- we want to say "T(..)", but if we're importing only a subset we want
1049         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1050     to_ie (Avail n)       = returnM (IEVar n)
1051     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
1052                             returnM (IEThingAbs n)
1053     to_ie (AvailTC n ns)  
1054         = loadSrcInterface doc n_mod False                      `thenM` \ iface ->
1055           case [xs | (m,as) <- mi_exports iface,
1056                      m == n_mod,
1057                      AvailTC x xs <- as, 
1058                      x == nameOccName n] of
1059               [xs] | all_used xs -> returnM (IEThingAll n)
1060                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
1061               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1062                                     returnM (IEVar n)
1063         where
1064           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1065           doc = text "Compute minimal imports from" <+> ppr n
1066           n_mod = nameModule n
1067 \end{code}
1068
1069
1070 %************************************************************************
1071 %*                                                                      *
1072 \subsection{Errors}
1073 %*                                                                      *
1074 %************************************************************************
1075
1076 \begin{code}
1077 badImportItemErr iface decl_spec ie
1078   = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1079          ptext SLIT("does not export"), quotes (ppr ie)]
1080   where
1081     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1082                   | otherwise     = empty
1083
1084 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1085 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1086
1087 dodgyMsg kind tc
1088   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1089           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1090           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1091           
1092 modExportErr mod
1093   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1094
1095 exportItemErr export_item
1096   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1097           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1098
1099 exportClashErr global_env name1 name2 ie1 ie2
1100   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1101          , ppr_export ie1 name1 
1102          , ppr_export ie2 name2  ]
1103   where
1104     occ = nameOccName name1
1105     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
1106                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1107
1108         -- get_gre finds a GRE for the Name, so that we can show its provenance
1109     get_gre name
1110         = case lookupGRE_Name global_env name of
1111              (gre:_) -> gre
1112              []      -> pprPanic "exportClashErr" (ppr name)
1113
1114 addDupDeclErr :: Name -> Name -> TcRn ()
1115 addDupDeclErr name_a name_b
1116   = addErrAt (srcLocSpan loc2) $
1117     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1118           ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1119   where
1120     loc2 = nameSrcLoc name2
1121     (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1122                   | otherwise                             = (name_a,name_b)
1123         -- Report the error at the later location
1124
1125 dupExportWarn occ_name ie1 ie2
1126   = hsep [quotes (ppr occ_name), 
1127           ptext SLIT("is exported by"), quotes (ppr ie1),
1128           ptext SLIT("and"),            quotes (ppr ie2)]
1129
1130 dupModuleExport mod
1131   = hsep [ptext SLIT("Duplicate"),
1132           quotes (ptext SLIT("Module") <+> ppr mod), 
1133           ptext SLIT("in export list")]
1134
1135 moduleDeprec mod txt
1136   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
1137           nest 4 (ppr txt) ]      
1138 \end{code}