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