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