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