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