63fd99dde1ae688b645f5f128dbd16bbaf7e814c
[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(..), DynFlags(..) )
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
28 import Module
29 import Name             ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
30                           nameParent, nameParent_maybe, isExternalName,
31                           isBuiltInSyntax )
32 import NameSet
33 import NameEnv
34 import OccName          ( srcDataName, isTcOcc, pprNonVarNameSpace,
35                           occNameSpace,
36                           OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
37                           extendOccEnv )
38 import HscTypes         ( GenAvailInfo(..), AvailInfo,
39                           HomePackageTable, PackageIfaceTable, 
40                           mkPrintUnqualified,
41                           Deprecs(..), ModIface(..), Dependencies(..), 
42                           lookupIfaceByModule, ExternalPackageState(..)
43                         )
44 import RdrName          ( RdrName, rdrNameOcc, setRdrNameSpace, 
45                           GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..), 
46                           emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
47                           extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
48                           Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), 
49                           importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance )
50 import Outputable
51 import UniqFM
52 import Maybes           ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
53 import SrcLoc           ( Located(..), mkGeneralSrcSpan,
54                           unLoc, noLoc, srcLocSpan, SrcSpan )
55 import BasicTypes       ( DeprecTxt )
56 import DriverPhases     ( isHsBoot )
57 import Util             ( notNull )
58 import List             ( partition )
59 import IO               ( openFile, IOMode(..) )
60 \end{code}
61
62
63
64 %************************************************************************
65 %*                                                                      *
66                 rnImports
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
72 rnImports imports
73          -- PROCESS IMPORT DECLS
74          -- Do the non {- SOURCE -} ones first, so that we get a helpful
75          -- warning for {- SOURCE -} ones that are unnecessary
76     = do this_mod <- getModule
77          implicit_prelude <- doptM Opt_ImplicitPrelude
78          let all_imports               = mk_prel_imports this_mod implicit_prelude ++ imports
79              (source, ordinary) = partition is_source_import all_imports
80              is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
81              get_imports = rnImportDecl this_mod
82
83          stuff1 <- mapM get_imports ordinary
84          stuff2 <- mapM get_imports source
85          return (stuff1 ++ stuff2)
86     where
87 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
88 -- because the former doesn't even look at Prelude.hi for instance 
89 -- declarations, whereas the latter does.
90    mk_prel_imports this_mod implicit_prelude
91        |  this_mod == pRELUDE
92           || explicit_prelude_import
93           || not implicit_prelude
94            = []
95        | otherwise = [preludeImportDecl]
96    explicit_prelude_import
97        = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports, 
98                    unLoc mod == pRELUDE_NAME ]
99
100 preludeImportDecl :: LImportDecl RdrName
101 preludeImportDecl
102   = L loc $
103         ImportDecl (L loc pRELUDE_NAME)
104                False {- Not a boot interface -}
105                False    {- Not qualified -}
106                Nothing  {- No "as" -}
107                Nothing  {- No import list -}
108   where
109     loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")         
110
111 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
112 mkRdrEnvAndImports imports
113   = do this_mod <- getModule
114        let get_imports = importsFromImportDecl this_mod
115        stuff <- mapM get_imports imports
116        let (imp_gbl_envs, imp_avails) = unzip stuff
117            gbl_env :: GlobalRdrEnv
118            gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
119
120            all_avails :: ImportAvails
121            all_avails = foldr plusImportAvails emptyImportAvails imp_avails
122        -- ALL DONE
123        return (gbl_env, all_avails)
124
125 \end{code}
126         
127 \begin{code}
128 rnImportDecl :: Module
129              -> LImportDecl RdrName
130              -> RnM (LImportDecl Name)
131 rnImportDecl this_mod (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
132     = setSrcSpan loc $
133       do iface <- loadSrcInterface doc imp_mod_name want_boot
134          let qual_mod_name = case as_mod of
135                                Nothing           -> imp_mod_name
136                                Just another_name -> another_name
137              imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
138                                        is_dloc = loc, is_as = qual_mod_name }
139          total_avails <- ifaceExportNames (mi_exports iface)
140          importDecl' <- rnImportDecl' iface imp_spec importDecl total_avails
141          return (L loc importDecl')
142     where imp_mod_name = unLoc loc_imp_mod_name
143           doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
144
145 rnImportDecl' :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
146 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod Nothing) all_names
147     = return $ ImportDecl mod_name want_boot qual_only as_mod Nothing
148 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
149     = do import_items_mbs <- mapM (srcSpanWrapper) import_items
150          let rn_import_items = concat . catMaybes $ import_items_mbs
151          return $ ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
152     where
153     srcSpanWrapper (L span ieRdr)
154         = setSrcSpan span $
155           case get_item ieRdr of
156             Nothing
157                 -> do addErr (badImportItemErr iface decl_spec ieRdr)
158                       return Nothing
159             Just ieNames
160                 -> return (Just [L span ie | ie <- ieNames])
161     occ_env :: OccEnv Name      -- Maps OccName to corresponding Name
162     occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
163         -- This env will have entries for data constructors too,
164         -- they won't make any difference because naked entities like T
165         -- in an import list map to TcOccs, not VarOccs.
166
167     sub_env :: NameEnv [Name]
168     sub_env = mkSubNameEnv all_names
169
170     get_item :: IE RdrName -> Maybe [IE Name]
171         -- Empty result for a bad item.
172         -- Singleton result is typical case.
173         -- Can have two when we are hiding, and mention C which might be
174         --      both a class and a data constructor.  
175     get_item item@(IEModuleContents _) 
176         = Nothing
177     get_item (IEThingAll tc)
178         = do name <- check_name tc
179              return [IEThingAll name]
180     get_item (IEThingAbs tc)
181         | want_hiding   -- hiding ( C )
182                         -- Here the 'C' can be a data constructor 
183                         --  *or* a type/class, or even both
184             = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
185                 []    -> Nothing
186                 names -> return [ IEThingAbs n | n <- names ]
187         | otherwise
188             = do name <- check_name tc
189                  return [IEThingAbs name]
190     get_item (IEThingWith n ns) -- import (C (A,B))
191         = do name <- check_name n
192              let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
193                  mb_names = map (lookupOccEnv env . rdrNameOcc) ns
194              names <- sequence mb_names
195              return [IEThingWith name names]
196     get_item (IEVar n)
197         = do name <- check_name n
198              return [IEVar name]
199
200     check_name :: RdrName -> Maybe Name
201     check_name rdrName
202         = lookupOccEnv occ_env (rdrNameOcc rdrName)
203
204
205 importsFromImportDecl :: Module
206                       -> LImportDecl Name
207                       -> RnM (GlobalRdrEnv, ImportAvails)
208
209 importsFromImportDecl this_mod
210         (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
211   = 
212     setSrcSpan loc $
213
214         -- If there's an error in loadInterface, (e.g. interface
215         -- file not found) we get lots of spurious errors from 'filterImports'
216     let
217         imp_mod_name = unLoc loc_imp_mod_name
218         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
219     in
220     loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
221
222         -- Compiler sanity check: if the import didn't say
223         -- {-# SOURCE #-} we should not get a hi-boot file
224     WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
225
226         -- Issue a user warning for a redundant {- SOURCE -} import
227         -- NB that we arrange to read all the ordinary imports before 
228         -- any of the {- SOURCE -} imports
229     warnIf (want_boot && not (mi_boot iface))
230            (warnRedundantSourceImport imp_mod_name)     `thenM_`
231
232     let
233         imp_mod = mi_module iface
234         deprecs = mi_deprecs iface
235         is_orph = mi_orphan iface 
236         deps    = mi_deps iface
237
238         filtered_exports = filter not_this_mod (mi_exports iface)
239         not_this_mod (mod,_) = mod /= this_mod
240         -- If the module exports anything defined in this module, just ignore it.
241         -- Reason: otherwise it looks as if there are two local definition sites
242         -- for the thing, and an error gets reported.  Easiest thing is just to
243         -- filter them out up front. This situation only arises if a module
244         -- imports itself, or another module that imported it.  (Necessarily,
245         -- this invoves a loop.)  
246         --
247         -- Tiresome consequence: if you say
248         --      module A where
249         --         import B( AType )
250         --         type AType = ...
251         --
252         --      module B( AType ) where
253         --         import {-# SOURCE #-} A( AType )
254         --
255         -- then you'll get a 'B does not export AType' message.  Oh well.
256
257         qual_mod_name = case as_mod of
258                           Nothing           -> imp_mod_name
259                           Just another_name -> another_name
260         imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
261                                   is_dloc = loc, is_as = qual_mod_name }
262     in
263         -- Get the total imports, and filter them according to the import list
264     ifaceExportNames filtered_exports           `thenM` \ total_avails ->
265     filterImports iface imp_spec
266                   imp_details total_avails      `thenM` \ (avail_env, gbl_env) ->
267
268     getDOpts `thenM` \ dflags ->
269
270     let
271         -- Compute new transitive dependencies
272
273         orphans | is_orph   = ASSERT( not (imp_mod `elem` dep_orphs deps) )
274                               imp_mod : dep_orphs deps
275                 | otherwise = dep_orphs deps
276
277         pkg = modulePackageId (mi_module iface)
278
279         (dependent_mods, dependent_pkgs) 
280            | pkg == thisPackage dflags =
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            | otherwise =
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      = unitUFM 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 = unitUFM (moduleName 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      = ([ModuleName],           -- '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 (foldUFM 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 (foldUFM 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 lookupUFM 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 :: DynFlags -> TcGblEnv -> RnM ()
742 reportDeprecations dflags 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 dflags 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 == moduleName 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 :: DynFlags -> HomePackageTable -> PackageIfaceTable 
778              -> Name -> Maybe DeprecTxt
779 lookupDeprec dflags hpt pit n 
780   = case lookupIfaceByModule dflags 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 ModuleName 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_name `elemFM` acc = acc     -- We import something already
913       | otherwise             = addToFM acc mod_name emptyAvailEnv
914       where
915         mod_name = moduleName mod
916         -- Add an empty collection of imports for a module
917         -- from which we have sucked only instance decls
918    
919     imports = tcg_imports gbl_env
920
921     direct_import_mods :: [(Module, Bool, SrcSpan)]
922         -- See the type of the imp_mods for this triple
923     direct_import_mods = moduleEnvElts (imp_mods imports)
924
925     -- unused_imp_mods are the directly-imported modules 
926     -- that are not mentioned in minimal_imports1
927     -- [Note: not 'minimal_imports', because that includes directly-imported
928     --        modules even if we use nothing from them; see notes above]
929     --
930     -- BUG WARNING: does not deal correctly with multiple imports of the same module
931     --              becuase direct_import_mods has only one entry per module
932     unused_imp_mods = [(mod_name,loc) | (mod,no_imp,loc) <- direct_import_mods,
933                        let mod_name = moduleName mod,
934                        not (mod_name `elemFM` minimal_imports1),
935                        mod /= pRELUDE,
936                        not no_imp]
937         -- The not no_imp part is not to complain about
938         -- import M (), which is an idiom for importing
939         -- instance declarations
940     
941     module_unused :: ModuleName -> Bool
942     module_unused mod = any (((==) mod) . fst) unused_imp_mods
943
944 ---------------------
945 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
946 -- Given the GREs for names that are used, figure out which imports 
947 -- could be omitted without changing the top-level environment.
948 --
949 -- NB: Given import Foo( T )
950 --           import qualified Foo
951 -- we do not report a duplicate import, even though Foo.T is brought
952 -- into scope by both, because there's nothing you can *omit* without
953 -- changing the top-level environment.  So we complain only if it's
954 -- explicitly named in both imports or neither.
955 --
956 -- Furthermore, we complain about Foo.T only if 
957 -- there is no complaint about (unqualified) T
958
959 warnDuplicateImports gres
960   = ifOptM Opt_WarnUnusedImports $ 
961     sequenceM_  [ warn name pr
962                         -- The 'head' picks the first offending group
963                         -- for this particular name
964                 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
965                 , pr <- redundants imps ]
966   where
967     warn name (red_imp, cov_imp)
968         = addWarnAt (importSpecLoc red_imp)
969             (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
970                    ptext SLIT("It is also") <+> ppr cov_imp])
971         where
972           pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
973                   | otherwise       = ppr occ
974           occ = nameOccName name
975           red_decl = is_decl red_imp
976     
977     redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
978         -- The returned pair is (redundant-import, covering-import)
979     redundants imps 
980         = [ (red_imp, cov_imp) 
981           | red_imp <- imps
982           , cov_imp <- take 1 (filter (covers red_imp) imps) ]
983
984         -- "red_imp" is a putative redundant import
985         -- "cov_imp" potentially covers it
986         -- This test decides whether red_imp could be dropped 
987         --
988         -- NOTE: currently the test does not warn about
989         --              import M( x )
990         --              imoprt N( x )
991         -- even if the same underlying 'x' is involved, because dropping
992         -- either import would change the qualified names in scope (M.x, N.x)
993         -- But if the qualified names aren't used, the import is indeed redundant
994         -- Sadly we don't know that.  Oh well.
995     covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item }) 
996            cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
997         | red_loc == cov_loc
998         = False         -- Ignore diagonal elements
999         | not (is_as red_decl == is_as cov_decl)
1000         = False         -- They bring into scope different qualified names
1001         | not (is_qual red_decl) && is_qual cov_decl
1002         = False         -- Covering one doesn't bring unqualified name into scope
1003         | red_selective
1004         = not cov_selective     -- Redundant one is selective and covering one isn't
1005           || red_later          -- Both are explicit; tie-break using red_later
1006         | otherwise             
1007         = not cov_selective     -- Neither import is selective
1008           && (is_mod red_decl == is_mod cov_decl)       -- They import the same module
1009           && red_later          -- Tie-break
1010         where
1011           red_loc   = importSpecLoc red_imp
1012           cov_loc   = importSpecLoc cov_imp
1013           red_later = red_loc > cov_loc
1014           cov_selective = selectiveImpItem cov_item
1015           red_selective = selectiveImpItem red_item
1016
1017 selectiveImpItem :: ImpItemSpec -> Bool
1018 selectiveImpItem ImpAll       = False
1019 selectiveImpItem (ImpSome {}) = True
1020
1021 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1022 printMinimalImports :: FiniteMap ModuleName AvailEnv    -- Minimal imports
1023                     -> RnM ()
1024 printMinimalImports imps
1025  = ifOptM Opt_D_dump_minimal_imports $ do {
1026
1027    mod_ies  <-  mappM to_ies (fmToList imps) ;
1028    this_mod <- getModule ;
1029    rdr_env  <- getGlobalRdrEnv ;
1030    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1031                   printForUser h (mkPrintUnqualified rdr_env) 
1032                                  (vcat (map ppr_mod_ie mod_ies)) })
1033    }
1034   where
1035     mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1036     ppr_mod_ie (mod_name, ies) 
1037         | mod_name == moduleName pRELUDE
1038         = empty
1039         | null ies      -- Nothing except instances comes from here
1040         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
1041         | otherwise
1042         = ptext SLIT("import") <+> ppr mod_name <> 
1043                     parens (fsep (punctuate comma (map ppr ies)))
1044
1045     to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1046                                  returnM (mod, ies)
1047
1048     to_ie :: AvailInfo -> RnM (IE Name)
1049         -- The main trick here is that if we're importing all the constructors
1050         -- we want to say "T(..)", but if we're importing only a subset we want
1051         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1052     to_ie (Avail n)       = returnM (IEVar n)
1053     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
1054                             returnM (IEThingAbs n)
1055     to_ie (AvailTC n ns)  
1056         = loadSrcInterface doc n_mod False                      `thenM` \ iface ->
1057           case [xs | (m,as) <- mi_exports iface,
1058                      moduleName m == n_mod,
1059                      AvailTC x xs <- as, 
1060                      x == nameOccName n] of
1061               [xs] | all_used xs -> returnM (IEThingAll n)
1062                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
1063               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1064                                     returnM (IEVar n)
1065         where
1066           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1067           doc = text "Compute minimal imports from" <+> ppr n
1068           n_mod = moduleName (nameModule n)
1069 \end{code}
1070
1071
1072 %************************************************************************
1073 %*                                                                      *
1074 \subsection{Errors}
1075 %*                                                                      *
1076 %************************************************************************
1077
1078 \begin{code}
1079 badImportItemErr iface decl_spec ie
1080   = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1081          ptext SLIT("does not export"), quotes (ppr ie)]
1082   where
1083     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1084                   | otherwise     = empty
1085
1086 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1087 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1088
1089 dodgyMsg kind tc
1090   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1091           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1092           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1093           
1094 modExportErr mod
1095   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1096
1097 exportItemErr export_item
1098   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1099           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1100
1101 exportClashErr global_env name1 name2 ie1 ie2
1102   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1103          , ppr_export ie1 name1 
1104          , ppr_export ie2 name2  ]
1105   where
1106     occ = nameOccName name1
1107     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
1108                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1109
1110         -- get_gre finds a GRE for the Name, so that we can show its provenance
1111     get_gre name
1112         = case lookupGRE_Name global_env name of
1113              (gre:_) -> gre
1114              []      -> pprPanic "exportClashErr" (ppr name)
1115
1116 addDupDeclErr :: Name -> Name -> TcRn ()
1117 addDupDeclErr name_a name_b
1118   = addErrAt (srcLocSpan loc2) $
1119     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1120           ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1121   where
1122     loc2 = nameSrcLoc name2
1123     (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1124                   | otherwise                             = (name_a,name_b)
1125         -- Report the error at the later location
1126
1127 dupExportWarn occ_name ie1 ie2
1128   = hsep [quotes (ppr occ_name), 
1129           ptext SLIT("is exported by"), quotes (ppr ie1),
1130           ptext SLIT("and"),            quotes (ppr ie2)]
1131
1132 dupModuleExport mod
1133   = hsep [ptext SLIT("Duplicate"),
1134           quotes (ptext SLIT("Module") <+> ppr mod), 
1135           ptext SLIT("in export list")]
1136
1137 moduleDeprec mod txt
1138   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
1139           nest 4 (ppr txt) ]      
1140 \end{code}