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