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