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