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