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