241863a8cb24b2f9af952551195aee6ed95b9e91
[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         reportUnusedNames, reportDeprecations, 
10         mkModDeps, exportsFromAvail
11     ) where
12
13 #include "HsVersions.h"
14
15 import DynFlags         ( DynFlag(..), GhcMode(..) )
16 import HsSyn            ( IE(..), ieName, ImportDecl(..), LImportDecl,
17                           ForeignDecl(..), HsGroup(..), HsBindGroup(..), 
18                           Sig(..), collectGroupBinders, tyClDeclNames 
19                         )
20 import RnEnv
21 import IfaceEnv         ( ifaceExportNames )
22 import LoadIface        ( loadSrcInterface )
23 import TcRnMonad
24
25 import FiniteMap
26 import PrelNames        ( pRELUDE, isUnboundName, main_RDR_Unqual )
27 import Module           ( Module, moduleUserString, unitModuleEnv, 
28                           lookupModuleEnv, moduleEnvElts, foldModuleEnv )
29 import Name             ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
30                           nameParent, nameParent_maybe, isExternalName,
31                           isBuiltInSyntax )
32 import NameSet
33 import NameEnv
34 import OccName          ( srcDataName, isTcOcc, occNameFlavour, OccEnv, 
35                           mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
36 import HscTypes         ( GenAvailInfo(..), AvailInfo,
37                           IfaceExport, HomePackageTable, PackageIfaceTable, 
38                           availNames, unQualInScope, 
39                           Deprecs(..), ModIface(..), Dependencies(..), 
40                           lookupIface, ExternalPackageState(..)
41                         )
42 import Packages         ( PackageIdH(..) )
43 import RdrName          ( RdrName, rdrNameOcc, setRdrNameSpace, 
44                           GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..), 
45                           emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
46                           unQualOK, lookupGRE_Name,
47                           Provenance(..), ImportSpec(..), 
48                           isLocalGRE, pprNameProvenance )
49 import Outputable
50 import Maybes           ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
51 import SrcLoc           ( Located(..), mkGeneralSrcSpan,
52                           unLoc, noLoc, srcLocSpan, combineSrcSpans, SrcSpan )
53 import BasicTypes       ( DeprecTxt )
54 import ListSetOps       ( removeDups )
55 import Util             ( sortLe, notNull, isSingleton )
56 import List             ( partition )
57 import IO               ( openFile, IOMode(..) )
58 \end{code}
59
60
61
62 %************************************************************************
63 %*                                                                      *
64                 rnImports
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69 rnImports :: [LImportDecl RdrName]
70           -> RnM (GlobalRdrEnv, ImportAvails)
71
72 rnImports imports
73   = do  {       -- PROCESS IMPORT DECLS
74                 -- Do the non {- SOURCE -} ones first, so that we get a helpful
75                 -- warning for {- SOURCE -} ones that are unnecessary
76           this_mod <- getModule
77         ; implicit_prelude <- doptM Opt_ImplicitPrelude
78         ; let
79             all_imports        = mk_prel_imports this_mod implicit_prelude ++ imports
80             (source, ordinary) = partition is_source_import all_imports
81             is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
82
83             get_imports = importsFromImportDecl this_mod
84
85         ; stuff1 <- mappM get_imports ordinary
86         ; stuff2 <- mappM get_imports source
87
88                 -- COMBINE RESULTS
89         ; let
90             (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
91             gbl_env :: GlobalRdrEnv
92             gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
93
94             all_avails :: ImportAvails
95             all_avails = foldr plusImportAvails emptyImportAvails imp_avails
96
97                 -- ALL DONE
98         ; return (gbl_env, all_avails) }
99   where
100         -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
101         -- because the former doesn't even look at Prelude.hi for instance 
102         -- declarations, whereas the latter does.
103     mk_prel_imports this_mod implicit_prelude
104         |  this_mod == pRELUDE
105         || explicit_prelude_import
106         || not implicit_prelude
107         = []
108
109         | otherwise = [preludeImportDecl]
110
111     explicit_prelude_import
112       = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports, 
113                        unLoc mod == pRELUDE ]
114
115 preludeImportDecl
116   = L loc $
117         ImportDecl (L loc pRELUDE)
118                False {- Not a boot interface -}
119                False    {- Not qualified -}
120                Nothing  {- No "as" -}
121                Nothing  {- No import list -}
122   where
123     loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
124 \end{code}
125         
126 \begin{code}
127 importsFromImportDecl :: Module
128                       -> LImportDecl RdrName
129                       -> RnM (GlobalRdrEnv, ImportAvails)
130
131 importsFromImportDecl this_mod
132         (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
133   = 
134     setSrcSpan loc $
135
136         -- If there's an error in loadInterface, (e.g. interface
137         -- file not found) we get lots of spurious errors from 'filterImports'
138     let
139         imp_mod_name = unLoc loc_imp_mod_name
140         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
141     in
142     loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
143
144         -- Compiler sanity check: if the import didn't say
145         -- {-# SOURCE #-} we should not get a hi-boot file
146     WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
147
148         -- Issue a user warning for a redundant {- SOURCE -} import
149         -- NB that we arrange to read all the ordinary imports before 
150         -- any of the {- SOURCE -} imports
151     warnIf (want_boot && not (mi_boot iface))
152            (warnRedundantSourceImport imp_mod_name)     `thenM_`
153
154     let
155         imp_mod = mi_module iface
156         deprecs = mi_deprecs iface
157         is_orph = mi_orphan iface 
158         deps    = mi_deps iface
159
160         filtered_exports = filter not_this_mod (mi_exports iface)
161         not_this_mod (mod,_) = mod /= this_mod
162         -- If the module exports anything defined in this module, just ignore it.
163         -- Reason: otherwise it looks as if there are two local definition sites
164         -- for the thing, and an error gets reported.  Easiest thing is just to
165         -- filter them out up front. This situation only arises if a module
166         -- imports itself, or another module that imported it.  (Necessarily,
167         -- this invoves a loop.)  
168         --
169         -- Tiresome consequence: if you say
170         --      module A where
171         --         import B( AType )
172         --         type AType = ...
173         --
174         --      module B( AType ) where
175         --         import {-# SOURCE #-} A( AType )
176         --
177         -- then you'll get a 'B does not export AType' message.  Oh well.
178
179         qual_mod_name = case as_mod of
180                           Nothing           -> imp_mod_name
181                           Just another_name -> another_name
182         imp_spec  = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,  
183                                  is_loc = loc, is_as = qual_mod_name }
184     in
185         -- Get the total imports, and filter them according to the import list
186     ifaceExportNames filtered_exports           `thenM` \ total_avails ->
187     filterImports iface imp_spec
188                   imp_details total_avails      `thenM` \ (avail_env, gbl_env) ->
189
190     getDOpts `thenM` \ dflags ->
191
192     let
193         -- Compute new transitive dependencies
194
195         orphans | is_orph   = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
196                               imp_mod_name : dep_orphs deps
197                 | otherwise = dep_orphs deps
198
199         (dependent_mods, dependent_pkgs) 
200            = case mi_package iface of
201                 HomePackage ->
202                 -- Imported module is from the home package
203                 -- Take its dependent modules and add imp_mod itself
204                 -- Take its dependent packages unchanged
205                 --
206                 -- NB: (dep_mods deps) might include a hi-boot file
207                 -- for the module being compiled, CM. Do *not* filter
208                 -- this out (as we used to), because when we've
209                 -- finished dealing with the direct imports we want to
210                 -- know if any of them depended on CM.hi-boot, in
211                 -- which case we should do the hi-boot consistency
212                 -- check.  See LoadIface.loadHiBootInterface
213                   ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
214
215                 ExtPackage pkg ->
216                 -- Imported module is from another package
217                 -- Dump the dependent modules
218                 -- Add the package imp_mod comes from to the dependent packages
219                  ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
220                  ([], pkg : dep_pkgs deps)
221
222         import_all = case imp_details of
223                         Just (is_hiding, ls)     -- Imports are spec'd explicitly
224                           | not is_hiding -> Just (not (null ls))
225                         _ -> Nothing            -- Everything is imported, 
226                                                 -- (or almost everything [hiding])
227
228         -- unqual_avails is the Avails that are visible in *unqualified* form
229         -- We need to know this so we know what to export when we see
230         --      module M ( module P ) where ...
231         -- Then we must export whatever came from P unqualified.
232         imports   = ImportAvails { 
233                         imp_env      = unitModuleEnv qual_mod_name avail_env,
234                         imp_mods     = unitModuleEnv imp_mod (imp_mod, import_all, loc),
235                         imp_orphs    = orphans,
236                         imp_dep_mods = mkModDeps dependent_mods,
237                         imp_dep_pkgs = dependent_pkgs }
238
239     in
240         -- Complain if we import a deprecated module
241     ifOptM Opt_WarnDeprecations (
242        case deprecs of  
243           DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
244           other         -> returnM ()
245     )                                                   `thenM_`
246
247     returnM (gbl_env, imports)
248
249 warnRedundantSourceImport mod_name
250   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
251           <+> quotes (ppr mod_name)
252 \end{code}
253
254
255 %************************************************************************
256 %*                                                                      *
257                 importsFromLocalDecls
258 %*                                                                      *
259 %************************************************************************
260
261 From the top-level declarations of this module produce
262         * the lexical environment
263         * the ImportAvails
264 created by its bindings.  
265         
266 Complain about duplicate bindings
267
268 \begin{code}
269 importsFromLocalDecls :: HsGroup RdrName
270                       -> RnM (GlobalRdrEnv, ImportAvails)
271 importsFromLocalDecls group
272   = getModule                           `thenM` \ this_mod ->
273     getLocalDeclBinders this_mod group  `thenM` \ avails ->
274         -- The avails that are returned don't include the "system" names
275     let
276         all_names :: [Name]     -- All the defns; no dups eliminated
277         all_names = [name | avail <- avails, name <- availNames avail]
278
279         dups :: [[Name]]
280         (_, dups) = removeDups compare all_names
281     in
282         -- Check for duplicate definitions
283         -- The complaint will come out as "Multiple declarations of Foo.f" because
284         -- since 'f' is in the env twice, the unQualInScope used by the error-msg
285         -- printer returns False.  It seems awkward to fix, unfortunately.
286     mappM_ addDupDeclErr dups                   `thenM_` 
287
288     doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude ->
289     let
290         prov     = LocalDef this_mod
291         gbl_env  = mkGlobalRdrEnv gres
292         gres     = [ GRE { gre_name = name, gre_prov = prov}
293                    | name <- all_names]
294
295             -- Optimisation: filter out names for built-in syntax
296             -- They just clutter up the environment (esp tuples), and the parser
297             -- will generate Exact RdrNames for them, so the cluttered
298             -- envt is no use.  To avoid doing this filter all the time,
299             -- we use -fno-implicit-prelude as a clue that the filter is
300             -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
301             --
302             -- It's worth doing because it makes the environment smaller for
303             -- every module that imports the Prelude
304             --
305             -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
306             -- in defn of gres above).      Stupid reason: when parsing 
307             -- data type decls, the constructors start as Exact tycon-names,
308             -- and then get turned into data con names by zapping the name space;
309             -- but that stops them being Exact, so they get looked up.  
310             -- Ditto in fixity decls; e.g.      infix 5 :
311             -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
312             -- The important thing is to trim down the exports.
313         filtered_names 
314           | implicit_prelude = all_names
315           | otherwise        = filter (not . isBuiltInSyntax) all_names
316
317         imports = emptyImportAvails {
318                         imp_env = unitModuleEnv this_mod $
319                                   mkNameSet filtered_names
320                     }
321     in
322     returnM (gbl_env, imports)
323 \end{code}
324
325
326 %*********************************************************
327 %*                                                      *
328 \subsection{Getting binders out of a declaration}
329 %*                                                      *
330 %*********************************************************
331
332 @getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
333 used for source code.
334
335         *** See "THE NAMING STORY" in HsDecls ****
336
337 \begin{code}
338 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
339 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls, 
340                                   hs_tyclds = tycl_decls, 
341                                   hs_fords = foreign_decls })
342   =     -- For type and class decls, we generate Global names, with
343         -- no export indicator.  They need to be global because they get
344         -- permanently bound into the TyCons and Classes.  They don't need
345         -- an export indicator because they are all implicitly exported.
346
347     mappM new_tc     tycl_decls                         `thenM` \ tc_avails ->
348         
349         -- In a hs-boot file, the value binders come from the
350         --  *signatures*, and there should be no foreign binders 
351     tcIsHsBoot                                          `thenM` \ is_hs_boot ->
352     let val_bndrs | is_hs_boot = sig_hs_bndrs
353                   | otherwise  = for_hs_bndrs ++ val_hs_bndrs
354     in
355     mappM new_simple val_bndrs                          `thenM` \ names ->
356
357     returnM (tc_avails ++ map Avail names)
358   where
359     new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
360
361     sig_hs_bndrs = [nm | HsBindGroup _ lsigs _  <- val_decls, 
362                          L _ (Sig nm _) <- lsigs]
363     val_hs_bndrs = collectGroupBinders val_decls
364     for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
365
366     new_tc tc_decl 
367         = newTopSrcBinder mod Nothing main_rdr                  `thenM` \ main_name ->
368           mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
369           returnM (AvailTC main_name (main_name : sub_names))
370         where
371           (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
372 \end{code}
373
374
375 %************************************************************************
376 %*                                                                      *
377 \subsection{Filtering imports}
378 %*                                                                      *
379 %************************************************************************
380
381 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
382 available, and filters it through the import spec (if any).
383
384 \begin{code}
385 filterImports :: ModIface
386               -> ImportSpec                     -- The span for the entire import decl
387               -> Maybe (Bool, [Located (IE RdrName)])   -- Import spec; True => hiding
388               -> NameSet                        -- What's available
389               -> RnM (NameSet,                  -- What's imported (qualified or unqualified)
390                       GlobalRdrEnv)             -- Same again, but in GRE form
391
392         -- Complains if import spec mentions things that the module doesn't export
393         -- Warns/informs if import spec contains duplicates.
394                         
395 mkGenericRdrEnv imp_spec names
396   = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
397                    | name <- nameSetToList names ]
398
399 filterImports iface imp_spec Nothing all_names
400   = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
401
402 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
403   = mappM (addLocM get_item) import_items       `thenM` \ gres_s ->
404     let
405         gres = concat gres_s
406         specified_names = mkNameSet (map gre_name gres)
407     in
408     if not want_hiding then
409       return (specified_names, mkGlobalRdrEnv gres)
410     else
411     let
412         keep n = not (n `elemNameSet` specified_names)
413         pruned_avails = filterNameSet keep all_names
414     in
415     return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
416
417   where
418     occ_env :: OccEnv Name      -- Maps OccName to corresponding Name
419     occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
420         -- This env will have entries for data constructors too,
421         -- they won't make any difference because naked entities like T
422         -- in an import list map to TcOccs, not VarOccs.
423
424     sub_env :: NameEnv [Name]
425     sub_env = mkSubNameEnv all_names
426
427     bale_out item = addErr (badImportItemErr iface imp_spec item)  `thenM_`
428                     returnM []
429
430     succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
431     succeed_with all_explicit names
432       = do { loc <- getSrcSpanM
433            ; returnM (map (mk_gre loc) names) }
434       where
435         mk_gre loc name = GRE { gre_name = name, 
436                                 gre_prov = Imported [this_imp_spec loc] (explicit name) }
437         this_imp_spec loc = imp_spec { is_loc = loc }
438         explicit name = all_explicit || isNothing (nameParent_maybe name)
439
440     get_item :: IE RdrName -> RnM [GlobalRdrElt]
441         -- Empty result for a bad item.
442         -- Singleton result is typical case.
443         -- Can have two when we are hiding, and mention C which might be
444         --      both a class and a data constructor.  
445     get_item item@(IEModuleContents _) 
446       = bale_out item
447
448     get_item item@(IEThingAll tc)
449       = case check_item item of
450           []    -> bale_out item
451
452           [n]   -> -- This occurs when you import T(..), but
453                         -- only export T abstractly.  The single [n]
454                         -- in the AvailTC is the type or class itself
455                         ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
456                         succeed_with False [n]
457
458           names -> succeed_with False names
459
460     get_item item@(IEThingAbs n)
461       | want_hiding     -- hiding( C ) 
462                         -- Here the 'C' can be a data constructor 
463                         --  *or* a type/class, or even both
464       = case concat [check_item item, check_item (IEVar data_n)] of
465           []    -> bale_out item
466           names -> succeed_with True names
467       where
468         data_n = setRdrNameSpace n srcDataName
469
470     get_item item
471       = case check_item item of
472           []    -> bale_out item
473           names -> succeed_with True names
474
475     check_item :: IE RdrName -> [Name]
476     check_item item 
477         = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
478             Nothing   -> []
479             Just name -> filterAvail item name sub_env
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485 \subsection{Export list processing}
486 %*                                                                      *
487 %************************************************************************
488
489 Processing the export list.
490
491 You might think that we should record things that appear in the export
492 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
493 wrong.  We do check (here) that they are in scope, but there is no
494 need to slurp in their actual declaration (which is what
495 @addOccurrenceName@ forces).
496
497 Indeed, doing so would big trouble when compiling @PrelBase@, because
498 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
499 @ConcBase.StateAndSynchVar#@, and so on...
500
501 \begin{code}
502 type ExportAccum        -- The type of the accumulating parameter of
503                         -- the main worker function in exportsFromAvail
504      = ([Module],               -- 'module M's seen so far
505         ExportOccMap,           -- Tracks exported occurrence names
506         NameSet)                -- The accumulated exported stuff
507 emptyExportAccum = ([], emptyOccEnv, emptyNameSet) 
508
509 type ExportOccMap = OccEnv (Name, IE RdrName)
510         -- Tracks what a particular exported OccName
511         --   in an export list refers to, and which item
512         --   it came from.  It's illegal to export two distinct things
513         --   that have the same occurrence name
514
515
516 exportsFromAvail :: Bool  -- False => no 'module M(..) where' header at all
517                  -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
518                  -> RnM NameSet
519         -- Complains if two distinct exports have same OccName
520         -- Warns about identical exports.
521         -- Complains about exports items not in scope
522
523 exportsFromAvail explicit_mod exports
524  = do { TcGblEnv { tcg_rdr_env = rdr_env, 
525                    tcg_imports = imports } <- getGblEnv ;
526
527         -- If the module header is omitted altogether, then behave
528         -- as if the user had written "module Main(main) where..."
529         -- EXCEPT in interactive mode, when we behave as if he had
530         -- written "module Main where ..."
531         -- Reason: don't want to complain about 'main' not in scope
532         --         in interactive mode
533         ghci_mode <- getGhciMode ;
534         let { real_exports 
535                 | explicit_mod             = exports
536                 | ghci_mode == Interactive = Nothing
537                 | otherwise                = Just [noLoc (IEVar main_RDR_Unqual)] } ;
538         exports_from_avail real_exports rdr_env imports }
539
540
541 exports_from_avail Nothing rdr_env imports
542  =      -- Export all locally-defined things
543         -- We do this by filtering the global RdrEnv,
544         -- keeping only things that are locally-defined
545    return (mkNameSet [ gre_name gre 
546                      | gre <- globalRdrEnvElts rdr_env,
547                        isLocalGRE gre ])
548
549 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env }) 
550   = foldlM do_litem emptyExportAccum items    `thenM` \ (_, _, exports) ->
551     returnM exports
552   where
553     sub_env :: NameEnv [Name]   -- Classify each name by its parent
554     sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
555
556     do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
557     do_litem acc = addLocM (exports_from_item acc)
558
559     exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
560     exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
561         | mod `elem` mods       -- Duplicate export of M
562         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
563                warnIf warn_dup_exports (dupModuleExport mod) ;
564                returnM acc }
565
566         | otherwise
567         = case lookupModuleEnv imp_env mod of
568             Nothing -> addErr (modExportErr mod)        `thenM_`
569                        returnM acc
570             Just names
571                 -> let
572                      new_exports = filterNameSet (inScopeUnqual rdr_env) names
573                    in
574
575                 -- This check_occs not only finds conflicts between this item
576                 -- and others, but also internally within this item.  That is,
577                 -- if 'M.x' is in scope in several ways, we'll have several
578                 -- members of mod_avails with the same OccName.
579                    check_occs ie occs (nameSetToList new_exports)       `thenM` \ occs' ->
580                    returnM (mod:mods, occs', exports `unionNameSets` new_exports)
581
582     exports_from_item acc@(mods, occs, exports) ie
583         = lookupGlobalOccRn (ieName ie)                 `thenM` \ name -> 
584           if isUnboundName name then
585                 returnM acc     -- Avoid error cascade
586           else let
587             new_exports = filterAvail ie name sub_env
588           in
589           checkErr (not (null new_exports)) (exportItemErr ie)  `thenM_`
590           checkForDodgyExport ie new_exports                    `thenM_`
591           check_occs ie occs new_exports                        `thenM` \ occs' ->
592           returnM (mods, occs', addListToNameSet exports new_exports)
593           
594 -------------------------------
595 filterAvail :: IE RdrName       -- Wanted
596             -> Name             -- The Name of the ieName of the item
597             -> NameEnv [Name]   -- Maps type/class names to their sub-names
598             -> [Name]           -- Empty if even one thing reqd is missing
599
600 filterAvail (IEVar _)            n subs = [n]
601 filterAvail (IEThingAbs _)       n subs = [n]
602 filterAvail (IEThingAll _)       n subs = n : subNames subs n
603 filterAvail (IEThingWith _ rdrs) n subs
604   | any isNothing mb_names = []
605   | otherwise              = n : catMaybes mb_names
606   where
607     env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
608     mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
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 = findUses (tcg_dus tcg_env) emptyNameSet
678     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
679
680     check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
681       | name `elemNameSet` used_names
682       , Just deprec_txt <- lookupDeprec hpt pit name
683       = setSrcSpan (is_loc imp_spec) $
684         addWarn (sep [ptext SLIT("Deprecated use of") <+> 
685                         occNameFlavour (nameOccName name) <+> 
686                         quotes (ppr name),
687                       (parens imp_msg),
688                       (ppr deprec_txt) ])
689         where
690           name_mod = nameModule name
691           imp_mod  = is_mod imp_spec
692           imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
693           extra | imp_mod == name_mod = empty
694                 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
695
696     check hpt pit ok_gre = returnM ()   -- Local, or not used, or not deprectated
697             -- The Imported pattern-match: don't deprecate locally defined names
698             -- For a start, we may be exporting a deprecated thing
699             -- Also we may use a deprecated thing in the defn of another
700             -- deprecated things.  We may even use a deprecated thing in
701             -- the defn of a non-deprecated thing, when changing a module's 
702             -- interface
703
704 lookupDeprec :: HomePackageTable -> PackageIfaceTable 
705              -> Name -> Maybe DeprecTxt
706 lookupDeprec hpt pit n 
707   = case lookupIface hpt pit (nameModule n) of
708         Just iface -> mi_dep_fn iface n `seqMaybe`      -- Bleat if the thing, *or
709                       mi_dep_fn iface (nameParent n)    -- its parent*, is deprec'd
710         Nothing    
711           | isWiredInName n -> Nothing
712                 -- We have not necessarily loaded the .hi file for a 
713                 -- wired-in name (yet), although we *could*.
714                 -- And we never deprecate them
715
716          | otherwise -> pprPanic "lookupDeprec" (ppr n) 
717                 -- By now all the interfaces should have been loaded
718
719 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
720 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
721 \end{code}
722
723 %*********************************************************
724 %*                                                       *
725                 Unused names
726 %*                                                       *
727 %*********************************************************
728
729 \begin{code}
730 reportUnusedNames :: Maybe [Located (IE RdrName)]       -- Export list
731                   -> TcGblEnv -> RnM ()
732 reportUnusedNames export_decls gbl_env 
733   = do  { warnUnusedTopBinds   unused_locals
734         ; warnUnusedModules    unused_imp_mods
735         ; warnUnusedImports    unused_imports   
736         ; warnDuplicateImports dup_imps
737         ; printMinimalImports  minimal_imports }
738   where
739     used_names, all_used_names :: NameSet
740     used_names = findUses (tcg_dus gbl_env) emptyNameSet
741     all_used_names = used_names `unionNameSets` 
742                      mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
743                         -- A use of C implies a use of T,
744                         -- if C was brought into scope by T(..) or T(C)
745
746         -- Collect the defined names from the in-scope environment
747     defined_names :: [GlobalRdrElt]
748     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
749
750         -- Note that defined_and_used, defined_but_not_used
751         -- are both [GRE]; that's why we need defined_and_used
752         -- rather than just all_used_names
753     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
754     (defined_and_used, defined_but_not_used) 
755         = partition (gre_is_used all_used_names) defined_names
756     
757         -- Find the duplicate imports
758     dup_imps = filter is_dup defined_and_used
759     is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
760     is_dup other                                     = False
761
762         -- Filter out the ones that are 
763         --  (a) defined in this module, and
764         --  (b) not defined by a 'deriving' clause 
765         -- The latter have an Internal Name, so we can filter them out easily
766     unused_locals :: [GlobalRdrElt]
767     unused_locals = filter is_unused_local defined_but_not_used
768     is_unused_local :: GlobalRdrElt -> Bool
769     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
770     
771     unused_imports :: [GlobalRdrElt]
772     unused_imports = filter unused_imp defined_but_not_used
773     unused_imp (GRE {gre_prov = Imported imp_specs True}) 
774         = not (all (module_unused . is_mod) 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 (is_mod (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 warnDuplicateImports gres
872   = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
873   where
874     warn (GRE { gre_name = name, gre_prov = Imported imps _ })
875         = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:")) 
876                $$ nest 2 (vcat (map ppr imps)))
877                               
878
879 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
880 printMinimalImports :: FiniteMap Module AvailEnv        -- Minimal imports
881                     -> RnM ()
882 printMinimalImports imps
883  = ifOptM Opt_D_dump_minimal_imports $ do {
884
885    mod_ies  <-  mappM to_ies (fmToList imps) ;
886    this_mod <- getModule ;
887    rdr_env  <- getGlobalRdrEnv ;
888    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
889                   printForUser h (unQualInScope rdr_env) 
890                                  (vcat (map ppr_mod_ie mod_ies)) })
891    }
892   where
893     mkFilename this_mod = moduleUserString this_mod ++ ".imports"
894     ppr_mod_ie (mod_name, ies) 
895         | mod_name == pRELUDE 
896         = empty
897         | null ies      -- Nothing except instances comes from here
898         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
899         | otherwise
900         = ptext SLIT("import") <+> ppr mod_name <> 
901                     parens (fsep (punctuate comma (map ppr ies)))
902
903     to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env)      `thenM` \ ies ->
904                               returnM (mod, ies)
905
906     to_ie :: AvailInfo -> RnM (IE Name)
907         -- The main trick here is that if we're importing all the constructors
908         -- we want to say "T(..)", but if we're importing only a subset we want
909         -- to say "T(A,B,C)".  So we have to find out what the module exports.
910     to_ie (Avail n)       = returnM (IEVar n)
911     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
912                             returnM (IEThingAbs n)
913     to_ie (AvailTC n ns)  
914         = loadSrcInterface doc n_mod False                      `thenM` \ iface ->
915           case [xs | (m,as) <- mi_exports iface,
916                      m == n_mod,
917                      AvailTC x xs <- as, 
918                      x == nameOccName n] of
919               [xs] | all_used xs -> returnM (IEThingAll n)
920                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
921               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
922                                     returnM (IEVar n)
923         where
924           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
925           doc = text "Compute minimal imports from" <+> ppr n
926           n_mod = nameModule n
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932 \subsection{Errors}
933 %*                                                                      *
934 %************************************************************************
935
936 \begin{code}
937 badImportItemErr iface imp_spec ie
938   = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
939          ptext SLIT("does not export"), quotes (ppr ie)]
940   where
941     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
942                   | otherwise     = empty
943
944 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
945 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
946
947 dodgyMsg kind tc
948   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
949           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
950           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
951           
952 modExportErr mod
953   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
954
955 exportItemErr export_item
956   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
957           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
958
959 exportClashErr global_env name1 name2 ie1 ie2
960   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
961          , ppr_export ie1 name1 
962          , ppr_export ie2 name2  ]
963   where
964     occ = nameOccName name1
965     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
966                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
967
968         -- get_gre finds a GRE for the Name, so that we can show its provenance
969     get_gre name
970         = case lookupGRE_Name global_env name of
971              (gre:_) -> gre
972              []      -> pprPanic "exportClashErr" (ppr name)
973
974 addDupDeclErr :: [Name] -> TcRn ()
975 addDupDeclErr names
976   = addErrAt big_loc $
977     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
978           ptext SLIT("Declared at:") <+> vcat (map ppr sorted_locs)]
979   where
980     locs    = map nameSrcLoc names
981     big_loc = foldr1 combineSrcSpans (map srcLocSpan locs)
982     name1   = head names
983     sorted_locs = sortLe (<=) (sortLe (<=) locs)
984
985 dupExportWarn occ_name ie1 ie2
986   = hsep [quotes (ppr occ_name), 
987           ptext SLIT("is exported by"), quotes (ppr ie1),
988           ptext SLIT("and"),            quotes (ppr ie2)]
989
990 dupModuleExport mod
991   = hsep [ptext SLIT("Duplicate"),
992           quotes (ptext SLIT("Module") <+> ppr mod), 
993           ptext SLIT("in export list")]
994
995 moduleDeprec mod txt
996   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
997           nest 4 (ppr txt) ]      
998 \end{code}